From b21888181554cc3fe959ffe4720149750aca5810 Mon Sep 17 00:00:00 2001 From: shaoxiang <519517384@qq.com> Date: Mon, 16 Nov 2026 16:57:14 +0800 Subject: [PATCH 01/20] Add measured automatic layout and USDCraft filtering --- CHANGELOG.md | 9 + OPEN_SOURCE_NOTICES.md | 5 +- README.md | 10 +- docs/asset-catalog.md | 37 +- docs/packaging.md | 6 +- docs/scene-layout.md | 85 ++++ examples/automatic_cabinet_layout/README.md | 76 +++ .../automatic_cabinet_layout/assets.lock.json | 420 +++++++++++++++++ examples/automatic_cabinet_layout/case.json | 150 ++++++ examples/automatic_cabinet_layout/check.py | 122 +++++ examples/automatic_cabinet_layout/recipe.json | 441 ++++++++++++++++++ .../supplemental-checks.json | 30 ++ pyproject.toml | 2 +- .../build-scene/references/measured-layout.md | 19 + src/simscene/acquisition/plans.py | 2 +- src/simscene/catalog/providers/hf_manifest.py | 8 +- .../catalog/providers/simready_package.py | 55 ++- src/simscene/catalog/search.py | 24 +- src/simscene/catalog/store.py | 22 +- src/simscene/layout_synthesis.py | 318 +++++++++++++ src/simscene/layout_synthesis_worker.py | 107 +++++ src/simscene/mcp_server.py | 23 + tests/agent/test_catalog_mcp_contract.py | 4 +- tests/agent/test_layout_mcp.py | 76 +++ tests/agent/test_package.py | 9 +- tests/test_catalog_simready_package.py | 170 +++++++ tests/test_layout_synthesis.py | 326 +++++++++++++ tests/test_packaging_contract.py | 2 +- 28 files changed, 2530 insertions(+), 28 deletions(-) create mode 100644 docs/scene-layout.md create mode 100644 examples/automatic_cabinet_layout/README.md create mode 100644 examples/automatic_cabinet_layout/assets.lock.json create mode 100644 examples/automatic_cabinet_layout/case.json create mode 100644 examples/automatic_cabinet_layout/check.py create mode 100644 examples/automatic_cabinet_layout/recipe.json create mode 100644 examples/automatic_cabinet_layout/supplemental-checks.json create mode 100644 src/simscene/layout_synthesis.py create mode 100644 src/simscene/layout_synthesis_worker.py create mode 100644 tests/agent/test_layout_mcp.py create mode 100644 tests/test_layout_synthesis.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 2aba7e6..3fa7e7a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## 0.2.0.dev2 — development, not released + +- Optional isolated scene_synthesizer layout proposals for verified prepared + props on measured static supports, returned as ordinary editable scene edits. +- USDCraft manifest filtering by declared joint type and count, with explicit + unknown results for contradictory metadata and versioned index migration. +- A specific cabinet-and-props trial exercises one fixed layout. It does not + certify arbitrary assets, collisions, stability or generalized layouts. + ## 0.2.0.dev1 — V2 preview Python package `0.2.0.dev1` maps explicitly to plugin `0.2.0-dev.1`. diff --git a/OPEN_SOURCE_NOTICES.md b/OPEN_SOURCE_NOTICES.md index 96c8709..1b12738 100644 --- a/OPEN_SOURCE_NOTICES.md +++ b/OPEN_SOURCE_NOTICES.md @@ -3,7 +3,10 @@ SimScene code is Apache-2.0; see [LICENSE](LICENSE) and [NOTICE](NOTICE). Python dependency versions and the built wheel hash are recorded in each plugin's `server/` build receipts. Optional Isaac Sim, Node/GLB decoding and -Sand3D runtimes are installed separately under their own terms. +Sand3D runtimes are installed separately under their own terms. The optional +[scene_synthesizer](https://github.com/NVlabs/scene_synthesizer) layout backend +is also installed separately and is distributed by its authors under Apache-2.0; +its Python and native dependencies retain their own terms. The repository distributes recipes, references, tests and selected rendered outputs. It does not bundle downloaded models, textures, vendor SDKs or complete diff --git a/README.md b/README.md index 517a8b8..56187e0 100644 --- a/README.md +++ b/README.md @@ -77,7 +77,8 @@ with this repository. ## V2 catalog and preparation -The V2 development line is **0.2.0.dev1** (plugin **0.2.0-dev.1**). It adds +This unreleased development branch is **0.2.0.dev2** (plugin **0.2.0-dev.2**). +The published V2 preview is **0.2.0.dev1** (plugin **0.2.0-dev.1**). It adds unified metadata search, immutable preparation plans, persistent preparation jobs, role-based scene recipes and optional isolated Sand3D generation. See the [source registry](docs/assets/SOURCES.md) and [measured validation scope](docs/validation/catalog-capabilities.md). @@ -106,6 +107,11 @@ provides a complete selected-asset route. [Preparation](docs/asset-catalog.md), [scene recipes](docs/scene-recipes.md), and [optional generation](docs/asset-generation.md) describe setup and reuse. Existing asset and simulation tools remain compatible. +This development branch also offers [optional automatic measured layout](docs/scene-layout.md) +for existing props on an explicitly measured support. It proposes editable +placements; the original USD and separate physical verification remain intact. +The pinned v0.2.0-dev.1 release above predates this tool. + ## Connect your agent Run the MCP server from the installed environment: @@ -146,6 +152,7 @@ Try a prompt such as: | Only one sugar cube | [Editable whole-home experiment](examples/whole_home_sugar/README.md) · [55-second film](docs/media/only-one-sugar-public-55s.mp4) · [Red-rope control](docs/media/red-rope-causal-comparison-20s.mp4) | | Multi-source kinetic gallery | [Editable recipe](examples/kinetic_asset_gallery/README.md) · [66-second film](docs/media/kinetic-asset-gallery-1080p30.mp4) | | Cross-catalog gravity cell | [Locked assets, physical case and reproduction](examples/catalog_gravity_cell/README.md) | +| Automatic cabinet layout (development branch) | [Editable recipe, source lock and physical checks](examples/automatic_cabinet_layout/README.md) | | Three-level chain reaction | [Editable recipe and reproduction steps](examples/three_level_chain/README.md) · [Film](docs/media/chain-workshop-1080p30.mp4) | | Precision sorting workshop | [Scene recipe](examples/precision_sorting_corner/README.md) · [Film](docs/media/precision-workshop-1080p30.mp4) | | Maintenance workbench | [Scene recipe](examples/maintenance_workbench/README.md) · [Film](docs/media/maintenance-workbench-1080p30.mp4) | @@ -167,6 +174,7 @@ cross-machine deployment still needs validation in the target environment. - [Quick start / 快速开始](docs/快速开始.md) - [Plugin packaging and installation](docs/packaging.md) - [Cameras, video, and layout](docs/视频交付.md) +- [Optional automatic measured layout](docs/scene-layout.md) - [Validation scope](docs/validation.md) - [Repository contents and asset distribution](docs/开源发布说明.md) - [Contributing](CONTRIBUTING.md) diff --git a/docs/asset-catalog.md b/docs/asset-catalog.md index b639864..c747bcc 100644 --- a/docs/asset-catalog.md +++ b/docs/asset-catalog.md @@ -1,9 +1,11 @@ # Online catalog and prepared assets -The V2 workflow adds six MCP tools: `catalog_search`, `asset_plan`, +The original V2 preview added six MCP tools: `catalog_search`, `asset_plan`, `asset_prepare`, `catalog_discover`, `scene_compile_recipe` and `asset_generate`. The original 46 tools retain their interfaces. Source availability, static preparation, and successful physical execution are separate results. +This later development branch also adds the optional `scene_plan_layout` tool; +see [automatic layout](scene-layout.md) for its setup and limits. ## Select a source and search metadata @@ -28,6 +30,39 @@ when the source recovers. Cursor pages retain the original query's cost under `request_preview_bytes` for per-call transfer accounting. Cached cursor pages make no network requests. +USDCraft is enabled but not selected by default. To find candidates whose +manifest declares one rotational joint, call `catalog_search` with: + +```json +{ + "query": "cabinet", + "filters": { + "source_ids": ["usdcraft"], + "required_capabilities": ["declared_single_joint", "declared_rotational_joint"] + }, + "limit": 8 +} +``` + +Use `declared_translational_joint` to search for a declared prismatic joint. +The rotational filter includes both `revolute` and `continuous`; a continuous +joint does not establish finite limits. All requested capabilities must match. +These filters describe the source's joint-type labels and joint count, not the +number of independent DOFs, an openable object, or a runtime-verified asset. +Unknown types, malformed lists, and conflicting type/count/physics declarations +remain unknown and do not satisfy these requirements, even with +`allow_unknown_constraints`. The pinned manifest itself contains such conflicts. + +The linked detailed record retains the original row, declared `part_count`, +`joint_count`, parsed `joint_types` and `has_textures` facts. Search returns +compact summaries; retrieving an asset and discovering its dependency closure +remain separate. An old USDCraft index projection refreshes the pinned manifest +on the next search; it does not download models, and old query cursors may need +to be restarted. Planning against a stale index asks for a search or refresh +first. Restart older SimScene servers sharing that index after upgrading; they +may still present their previous projection. Preparation still inspects the selected native USD and rejects +unsupported graphs or physics. + ABO is a community conversion of Amazon Berkeley Objects; preserve its source identity and CC-BY notices. NVIDIA search indexes upstream libraries with different terms: an asset's license can remain unknown even when search works. diff --git a/docs/packaging.md b/docs/packaging.md index 874972e..d2b8c98 100644 --- a/docs/packaging.md +++ b/docs/packaging.md @@ -1,8 +1,8 @@ # Plugin packages -Python package version `0.2.0.dev1` is an experimental V2 candidate. The single version +Python package version `0.2.0.dev2` is an unreleased experimental V2 candidate. The single version source is `pyproject.toml`; the builder maps its development suffix explicitly to -plugin version `0.2.0-dev.1`. Building or installing files does not publish a +plugin version `0.2.0-dev.2`. Building or installing files does not publish a release or establish physical compatibility for arbitrary assets. The [V2 preview release](https://github.com/ros-claw/simscene/releases/tag/v0.2.0-dev.1) @@ -56,7 +56,7 @@ A wheel can also be installed using ordinary pip: ```sh python3 -m venv /absolute/path/to/new-venv -/absolute/path/to/new-venv/bin/python -m pip install /absolute/path/to/new-dist/wheels/rosclaw_simscene-0.2.0.dev1-py3-none-any.whl +/absolute/path/to/new-venv/bin/python -m pip install /absolute/path/to/new-dist/wheels/rosclaw_simscene-0.2.0.dev2-py3-none-any.whl ``` That installs the base Python dependencies. It does not install Isaac or optional diff --git a/docs/scene-layout.md b/docs/scene-layout.md new file mode 100644 index 0000000..c117fd5 --- /dev/null +++ b/docs/scene-layout.md @@ -0,0 +1,85 @@ +# Automatic measured layout + +This development branch adds `scene_plan_layout`, an optional MCP planner for +one horizontal support and up to eight existing objects. It proposes regular +`place_on` operations, leaving the scene and the original USD assets unchanged. +The v0.2.0-dev.1 release predates this tool. + +## Set up the separate backend + +Install [NVIDIA scene_synthesizer](https://github.com/NVlabs/scene_synthesizer) +version 1.15.0 in its own Python environment on the machine running the +SimScene MCP server. Do not install it into the Isaac Sim Python environment: + +```bash +python3 -m venv /absolute/path/to/layout-env +/absolute/path/to/layout-env/bin/python -m pip install 'scene-synthesizer==1.15.0' +export SIMSCENE_LAYOUT_PYTHON=/absolute/path/to/layout-env/bin/python +``` + +Pass `SIMSCENE_LAYOUT_PYTHON` into the MCP server environment, including when +starting it from a client. The base SimScene environment still needs USD Python +bindings to measure imported models. Search, other MCP tools and existing +manual placement do not require this optional backend. Installation downloads +Python packages, not a model library. The backend is never installed automatically. + +## Plan and apply + +First add the objects and the support to a scene. Imported objects, supports, +and named obstacles must use locally present, hash-verified prepared packages. +Imported supports require a `static_fixture_v1` or `container_v1` collider; +inspect the geometry and declare a named `support_surfaces` region in local +metres. A static box can use its top directly; when placing dynamic objects on +it, explicitly set `collision: true`. Dynamic props and the support also need +enabled collision shapes and must not exclude each other. Instanced imported +supports and compounds with attached visuals are not supported by this planner. +Measure and reserve moving-door, robot and other +activity regions explicitly. For example: + +```json +{ + "scene_id": "workshop", + "ids": ["notebook", "box_1", "box_2"], + "support": "bench", + "support_surface": "worktop", + "seed": 42, + "clearance_m": 0.02, + "gap_m": 0.001, + "avoid_ids": ["fixed_fixture"], + "keepout_bounds": [{"min": [0.2, -0.4, 0.7], "max": [0.6, 0.1, 1.4]}] +} +``` + +Send this object to `scene_plan_layout`. If `bench` is a primitive box with no +named region, omit `support_surface`. The response contains the seed, backend +and dependency versions, an identifying `plan_sha256`, support relationships, +`base_revision`, and normal scene `operations`. Apply the entire batch using +`scene_apply` with the returned scene and revision. A revision conflict rejects +the batch; plan again against the current scene. A saved operation list can be +reapplied to an equivalent starting scene without re-running the sampler; +verify the source and resulting scene in that environment. + +The worker seeds the upstream and NumPy random generators in a fresh process. +The returned identity records the scene inputs, all installed Python package +versions, Python, platform and the observed GEOS version. A repeated seed was +checked in separate processes on one environment; package versions do not pin +every native library or guarantee identical results across machines. The +`verified_prepared` source entries include each manifest hash and profile. +The planner verifies the local package, and scene edits and runs recheck their +bindings. Fixed model files and package hashes belong in the project’s normal +asset lock and run snapshot. + +## What the proposal checks + +The worker uses conservative boxes from measured render bounds, samples on the +declared region, and checks footprints, edge clearance and explicit exclusions. +SimScene independently rechecks the proposed operations before returning them. +Object orientations stay as supplied. Obstacles and keepouts are conservatively +projected to support-local XY regardless of height; this can reject feasible +placements. Unlisted objects and moving-door sweeps are not inferred. Infeasible +packing, missing dependencies and unsupported backends fail instead of silently +placing partial results. + +Render bounds are not the collision geometry or a stability certificate. +`physics_tested` remains false. Check actual USD bindings, collider clearance, +joint travel, contacts, and settling in a fresh Isaac run using a frozen case. diff --git a/examples/automatic_cabinet_layout/README.md b/examples/automatic_cabinet_layout/README.md new file mode 100644 index 0000000..5d00c01 --- /dev/null +++ b/examples/automatic_cabinet_layout/README.md @@ -0,0 +1,76 @@ +# Automatically placed props and a native cabinet hinge + +This editable example places two ABO notebooks and a GSO box on a primitive +worktable, alongside a USDCraft lift-up cabinet with its original two-link, +single-hinge structure. The three prop positions came from the optional +`scene_synthesizer` planner with seed 42 and an explicit cabinet-door keepout. +The cabinet is driven by a declared schedule; this is not a contact-triggered +or passive causal chain. The 0.12 kg rigid-prop masses are experimental. + +One 600-step Isaac Sim 6.2.0-rc.14 run passed the frozen core case and the +supplemental checks in this directory. The cabinet's measured native joint +readback reached approximately 1.36 rad, and the three imported props made +direct table contact and settled. This establishes only that specific layout, +preparation, case and run; different assets or placements need new checks. +The first preview failed because its table and floor lacked collisions; the +recipe explicitly enables them. + +The three selected models are not included. `assets.lock.json` records their +individual source revisions, file hashes, acquisition and preparation +parameters and license declarations: USDCraft's selected cabinet is +Apache-2.0; the selected ABO and GSO conversions declare CC-BY-4.0. Check the +actual source and attribution terms before use. Acquisition obtains the +selected models and required dependencies, not the entire datasets. + +## Rebuild and verify + +On a simulation host, install SimScene, USD bindings and FFmpeg. Set these +paths **before** probing the runtime, so the probe and asset preparation use +the same state directory. Use an empty, writable output directory outside the +checkout. The separate GLB decoder is required for this example's ABO and GSO +models; its Node.js prerequisites are in [asset preparation](../../docs/asset-catalog.md). + +```bash +export SIMSCENE_HOME=/your/new-layout/state +export SIMSCENE_CACHE=/your/selected-source-cache +export SIMSCENE_V2_CONFIG=/your/layout-v2.json +export SIMSCENE_ISAAC_PYTHON=/your/isaac-sim/python.sh +mkdir -p /your/new-layout +simscene asset setup-decoder --output /your/new-layout/decoder +export SIMSCENE_GLTF_TRANSFORM_PREFIX=/your/new-layout/decoder +simscene asset probe + +python3 experiments/acquire_recipe_assets.py examples/automatic_cabinet_layout/assets.lock.json \ + --cache "$SIMSCENE_CACHE" --catalog-output /your/new-layout/bindings.json +python3 experiments/apply_scene_recipe.py examples/automatic_cabinet_layout/recipe.json \ + --scene-id cabinet_layout --asset-catalog /your/new-layout/bindings.json \ + --asset-lock examples/automatic_cabinet_layout/assets.lock.json \ + --save-directory /your/new-layout/applied +python3 experiments/freeze_recipe_case.py examples/automatic_cabinet_layout/case.json \ + --bindings /your/new-layout/bindings.json \ + --asset-lock examples/automatic_cabinet_layout/assets.lock.json \ + --output /your/new-layout/frozen-case.json +simscene run --scene cabinet_layout --steps 600 --seed 42 \ + --case /your/new-layout/frozen-case.json +simscene wait --job JOB_ID --receipt /your/new-layout/run-receipt.json +python3 examples/automatic_cabinet_layout/check.py \ + --run /your/new-layout/state/runs/RUN_ID --output /your/new-layout/check.json +``` + +Use the returned job and run IDs. This recipe includes two native 1080p/30fps +cameras; rendering takes additional GPU time and disk space. The case template +is frozen against the newly acquired package hashes before the run; rebuilding +the scene or the case does not reuse the earlier physical verdict. `check.py` +also verifies run/evidence locks, native DOF readback, original joint and mass +attributes, direct support, sampled keepout, contacts and settling. It requires +the original prepared source file retained in the selected package. The checker +requires the full example case re-frozen against the run's bindings; it refuses a +case with omitted components or weakened thresholds. + +The saved recipe already contains ordinary final placement operations, so its +reconstruction does not need `scene_synthesizer`. To generate a new layout, +install the optional isolated backend and use the documented +[`scene_plan_layout`](../../docs/scene-layout.md) workflow. Save the new plan, +apply it to the current revision, update the case if necessary, and run a new +physical trial. Fixed-seed repeatability in one environment is not a promise +that arbitrary layouts are collision-free or stable. diff --git a/examples/automatic_cabinet_layout/assets.lock.json b/examples/automatic_cabinet_layout/assets.lock.json new file mode 100644 index 0000000..f5a1470 --- /dev/null +++ b/examples/automatic_cabinet_layout/assets.lock.json @@ -0,0 +1,420 @@ +{ + "schema": "simscene.selected_assets.v2", + "assets": { + "cabinet": { + "provider": "prepared", + "source_ref": { + "source_id": "usdcraft", + "asset_id": "ds_R021_02", + "revision": "92f4e908415d7532a02661d6502ab49dc3aa33f9", + "variant_id": null + }, + "profile_id": "articulated_prop_v1", + "profile_version": 1, + "parameters": { + "ccd": false, + "collision_method": "preserve", + "dynamic_friction": 0.5, + "proxy_tolerance_m": 0.002, + "restitution": 0.05, + "scale_mode": "preserve", + "source_physics_policy": "preserve_valid", + "static_friction": 0.6 + }, + "target": { + "engine": "physx", + "isaac_version": "6.2.0-rc.14+release.52805.02189a84.gl", + "platform": "linux-x86_64", + "usd_version": "0.25.11" + }, + "toolchain": { + "backend": "openusd", + "version": "0.25.11" + }, + "source_sha256": "72dbc3b8479048ff07b838a951c4dd58617eeddc8668a861415a5ca087f32be5", + "source_closure_sha256": "a8b18e9ab32ef792c1409fa05e741b2316b2869cf1348cd6ed2c731d483779ef", + "source_files": [ + { + "path": "rigid/kitchen_dining/R021_kitchen_wall_cabinet/02_lift_up_wall_cabinet/physx/model.usdc", + "size_bytes": 63716, + "sha256": "72dbc3b8479048ff07b838a951c4dd58617eeddc8668a861415a5ca087f32be5" + } + ], + "previous_preparation": { + "prepared_id": "781e55aa1dda2360052337c952099fe713a205ee7978754ed0d5a7d030104694", + "manifest_sha256": "993b5f45e7c9f89f65dd4294cbd3ca4c6969408226f25e24829c570b31fb2a19", + "source_manifest_sha256": "19a4f3486fbed40e340d793b951157146e1b2da204e673d2f006c835245a74ba", + "scope": "informational; rebuild may change absolute provenance; no physics verdict reused" + }, + "source_record": { + "ref": { + "asset_id": "ds_R021_02", + "revision": "92f4e908415d7532a02661d6502ab49dc3aa33f9", + "source_id": "usdcraft", + "variant_id": null + }, + "title": "Lift-Up Wall Cabinet", + "format": "usd", + "entry_path": "rigid/kitchen_dining/R021_kitchen_wall_cabinet/02_lift_up_wall_cabinet/physx/model.usdc", + "license": { + "basis": "pinned_USDCraft_asset_distribution_card", + "evidence": "declared", + "license": "Apache-2.0", + "notices_required": true, + "status": "known" + }, + "availability": { + "acquisition": { + "dependency_mode": "inspect_selected_usd_closure", + "files": [ + { + "path": "rigid/kitchen_dining/R021_kitchen_wall_cabinet/02_lift_up_wall_cabinet/physx/model.usdc", + "sha256": "72dbc3b8479048ff07b838a951c4dd58617eeddc8668a861415a5ca087f32be5", + "size": null + } + ], + "files_complete": false, + "kind": "hf_usd_package", + "package_path": "rigid/kitchen_dining/R021_kitchen_wall_cabinet/02_lift_up_wall_cabinet", + "path": "rigid/kitchen_dining/R021_kitchen_wall_cabinet/02_lift_up_wall_cabinet/physx/model.usdc", + "repository": "nvidia/USDCraft-10K", + "revision": "92f4e908415d7532a02661d6502ab49dc3aa33f9" + }, + "estimated_download_bytes": null, + "files_complete": false, + "granularity": "dependency_closure", + "status": "declared" + }, + "provenance": { + "license_scope": "USDCraft-generated native distribution; not a license rule for arbitrary owner packages", + "metadata_revision": "92f4e908415d7532a02661d6502ab49dc3aa33f9", + "original_metadata": { + "category": "Kitchen Wall Cabinet", + "category_id": "R021", + "group": "kitchen_dining", + "has_textures": "false", + "joint_count": "1", + "joint_types": "revolute", + "object_id": "ds_R021_02", + "part_count": "2", + "path": "rigid/kitchen_dining/R021_kitchen_wall_cabinet/02_lift_up_wall_cabinet", + "physics_type": "articulated", + "physx_sha256": "72dbc3b8479048ff07b838a951c4dd58617eeddc8668a861415a5ca087f32be5", + "prompt": "Lift-up wall cabinet, 90 x 35 x 40 cm, in matte grey-painted wood with a single wide flap door and a recessed handle bar. The interior has one wooden shelf and a flat back. To store light items above the counter, the user grips the recessed handle bar and lifts the flap door upward to reach the shelf; the flap is hinged along its top edge on a horizontal revolute axis and swings up 80 degrees; every part is a rigid body, with no deformable, cloth, soft-volume or dynamic rod parts.", + "title": "Lift-Up Wall Cabinet" + }, + "repository": "nvidia/USDCraft-10K", + "unit_axis_evidence": "dataset_card_declared_meters_Z_up" + } + } + }, + "box": { + "provider": "prepared", + "source_ref": { + "source_id": "gso-glb", + "asset_id": "ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box", + "revision": "75e8895e4f4e854cddd7009a7e60f86812041012", + "variant_id": null + }, + "profile_id": "rigid_prop_v1", + "profile_version": 1, + "parameters": { + "ccd": true, + "collision_method": "convex_hull", + "dynamic_friction": 0.5, + "mass_kg": 0.12, + "mass_note": "Experimental120mm scaled scanned box/.12kg assumption; not manufacturer values.", + "proxy_tolerance_m": 0.002, + "restitution": 0.05, + "scale_mode": "fit_longest", + "source_physics_policy": "reject_if_physics", + "static_friction": 0.6, + "target_longest_extent_m": 0.12 + }, + "target": { + "engine": "physx", + "isaac_version": "6.2.0-rc.14+release.52805.02189a84.gl", + "platform": "linux-x86_64", + "usd_version": "0.25.11" + }, + "toolchain": { + "backend": "omni.kit.asset_converter", + "canonicalization": "explicit_Rx90_once", + "codec_policy_version": 2, + "predecoder": { + "backend": "gltf-transform-meshopt", + "core_version": "4.5.1", + "extensions_version": "4.5.1", + "max_decoded_bytes": 268435456, + "meshoptimizer_version": "1.3.0", + "node_modules_sha256": "3bfdef144f9a32d73ab5147f5be0dcd2e9e731a28b56f9ae7e521a46e590c302", + "node_version": "v22.23.2", + "package_lock_sha256": "bac0ab1332c821de5680b887f828014d86a71eb930b14d91fd938e36c45bdff0", + "script_sha256": "06af0eaf70d3cfda095cadef3de0afde388d1c9b4ba1e930d408e95c002602e4" + }, + "usd_version": "0.25.11", + "version": "6.1.0" + }, + "source_sha256": "5454424606ed780b806c99a5a3ffc0f4b0b9ade2fc9afa9c63fbf932ea187949", + "source_closure_sha256": "c2800268fbde5b01d93558746942ffc8446780f390573605f2979056c6223975", + "source_files": [ + { + "path": "README.md", + "size_bytes": 11624, + "sha256": "a283318ac5c8990a1fb49ddd5b2f2f91aaaddece678e3a97941e90b29deb8ad9" + }, + { + "path": "objects/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box.glb", + "size_bytes": 263232, + "sha256": "5454424606ed780b806c99a5a3ffc0f4b0b9ade2fc9afa9c63fbf932ea187949" + } + ], + "previous_preparation": { + "prepared_id": "dd50547b39fed14df8ddecbe15ee71952928b21b43fb302cc105aece9e66947b", + "manifest_sha256": "52de9211b27fc73eaaadedd4725f1122224c0f31d5ab07a95baa340902244990", + "source_manifest_sha256": "bd310cb197a405b1671b990a1daeb72be6062d4419fadf252dd88ed8f23e6c67", + "scope": "informational; rebuild may change absolute provenance; no physics verdict reused" + }, + "source_record": { + "ref": { + "asset_id": "ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box", + "revision": "75e8895e4f4e854cddd7009a7e60f86812041012", + "source_id": "gso-glb", + "variant_id": null + }, + "title": "Ready-to-Use Rolled Fondant, Pure White - 24 oz box", + "format": "glb", + "entry_path": "objects/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box.glb", + "license": { + "basis": "object_metadata_row", + "evidence": "declared", + "license": "CC-BY-4.0", + "notices_required": true, + "status": "known" + }, + "availability": { + "acquisition": { + "additional_paths": [ + "README.md" + ], + "kind": "hf_single_glb", + "path": "objects/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box.glb", + "repository": "codepawl/scanned-objects-glb", + "revision": "75e8895e4f4e854cddd7009a7e60f86812041012" + }, + "estimated_download_bytes": 263232, + "files_complete": null, + "granularity": "single_file", + "status": "declared" + }, + "provenance": { + "mass_estimate_note": "metadata estimates are not measured/manufacturer dynamics", + "metadata_revision": "75e8895e4f4e854cddd7009a7e60f86812041012", + "original_metadata": { + "brand": "Ready-to-Use", + "category": "food and drink", + "category_source": "name rule", + "file": "objects/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box.glb", + "file_name": "engine/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box.glb", + "id": "ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box", + "license": "CC-BY-4.0", + "mass_estimate_kg": 0.2866, + "mpn": null, + "name": "Ready-to-Use Rolled Fondant, Pure White - 24 oz box", + "pack_bytes": 263232, + "pack_texture_px": 2048, + "size_metres": [ + 0.1217, + 0.1687, + 0.0491 + ], + "sku": "00070896423016", + "source": "https://fuel.gazebosim.org/1.0/GoogleResearch/models/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box", + "source_bytes": 13264125, + "source_categories": [ + "Consumer Goods" + ], + "source_texture_px": 4096, + "thumb": "thumbs/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box.webp", + "triangles": 1744, + "vertices": 949 + }, + "relationship": "community_conversion", + "repository": "codepawl/scanned-objects-glb", + "selected_variant": "standard_objects_glb", + "upstream_source": "https://fuel.gazebosim.org/1.0/GoogleResearch/models/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box", + "viewer_variant_not_selected": "engine/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box.glb" + } + } + }, + "book_a": { + "provider": "prepared", + "source_ref": { + "source_id": "abo-glb", + "asset_id": "B01DN8TB5U", + "revision": "c7c8293fed3b7ab122ef5d7896521a187e0962d7", + "variant_id": null + }, + "profile_id": "rigid_prop_v1", + "profile_version": 1, + "parameters": { + "ccd": true, + "collision_method": "convex_hull", + "dynamic_friction": 0.5, + "mass_kg": 0.12, + "mass_note": "Experimental 150mm scaled notebook surrogate for 200mm routing channels; mass assumption, not full-size manufacturer specification.", + "proxy_tolerance_m": 0.002, + "restitution": 0.05, + "scale_mode": "fit_longest", + "source_physics_policy": "reject_if_physics", + "static_friction": 0.6, + "target_longest_extent_m": 0.15 + }, + "target": { + "engine": "physx", + "isaac_version": "6.2.0-rc.14+release.52805.02189a84.gl", + "platform": "linux-x86_64", + "usd_version": "0.25.11" + }, + "toolchain": { + "backend": "omni.kit.asset_converter", + "canonicalization": "explicit_Rx90_once", + "codec_policy_version": 2, + "predecoder": { + "backend": "gltf-transform-meshopt", + "core_version": "4.5.1", + "extensions_version": "4.5.1", + "max_decoded_bytes": 268435456, + "meshoptimizer_version": "1.3.0", + "node_modules_sha256": "3bfdef144f9a32d73ab5147f5be0dcd2e9e731a28b56f9ae7e521a46e590c302", + "node_version": "v22.23.2", + "package_lock_sha256": "bac0ab1332c821de5680b887f828014d86a71eb930b14d91fd938e36c45bdff0", + "script_sha256": "06af0eaf70d3cfda095cadef3de0afde388d1c9b4ba1e930d408e95c002602e4" + }, + "usd_version": "0.25.11", + "version": "6.1.0" + }, + "source_sha256": "67d61db31084d820ca9b1b0d2d3761662f6a5532944573afceee8f57c8151845", + "source_closure_sha256": "6dbe5eddcba3d8c26d5b3f27a0272a59420e565492957a3cbfef22753a87de9a", + "source_files": [ + { + "path": "LICENSE-CC-BY-4.0.txt", + "size_bytes": 14527, + "sha256": "419896aea50c15d6e40c5b4baf4bd346f78223b9a354c7357ad00262afdc08ec" + }, + { + "path": "objects/B01DN8TB5U/B01DN8TB5U.glb", + "size_bytes": 524720, + "sha256": "67d61db31084d820ca9b1b0d2d3761662f6a5532944573afceee8f57c8151845" + } + ], + "previous_preparation": { + "prepared_id": "4f6ada04a8274c8ce1dadbd4a13242ab1f688b407e09d106cab2f613795684ec", + "manifest_sha256": "c00b0427d407b564b116c7b79426f9db3d5ccc1ed239e68186484918e85a759b", + "source_manifest_sha256": "7d3ae44fb94faa434650be896d80eb6b2fdff835a276afdafff3bc077bd0fc6a", + "scope": "informational; rebuild may change absolute provenance; no physics verdict reused" + }, + "source_record": { + "ref": { + "asset_id": "B01DN8TB5U", + "revision": "c7c8293fed3b7ab122ef5d7896521a187e0962d7", + "source_id": "abo-glb", + "variant_id": null + }, + "title": "AmazonBasics Classic Blank Notebook, 240 Pages, Hardcover - Plain", + "format": "glb", + "entry_path": "objects/B01DN8TB5U/B01DN8TB5U.glb", + "license": { + "basis": "dataset_card", + "evidence": "declared", + "license": "CC-BY-4.0", + "notices_required": true, + "status": "known" + }, + "availability": { + "acquisition": { + "kind": "hf_single_glb", + "path": "objects/B01DN8TB5U/B01DN8TB5U.glb", + "repository": "codepawl/abo-glb", + "revision": "c7c8293fed3b7ab122ef5d7896521a187e0962d7" + }, + "estimated_download_bytes": 524720, + "files_complete": null, + "granularity": "single_file", + "status": "declared" + }, + "provenance": { + "coordinate_system": "Y-up", + "dimensions_evidence": "declared", + "license": "CC-BY-4.0", + "metadata_revision": "c7c8293fed3b7ab122ef5d7896521a187e0962d7", + "original_metadata": { + "amazon_item_ids": [ + "B01DN8TB5U" + ], + "bounds_min": [ + -0.0635, + 0, + -0.0079 + ], + "brand": "AmazonBasics", + "catalog_dimensions_cm": { + "height": 12.7, + "length": 21, + "width": 1.5 + }, + "catalog_weight_kg": null, + "color": "Black", + "domain": "amazon.com", + "file": "objects/B01DN8TB5U/B01DN8TB5U.glb", + "hull_volume_m3": 0.00041, + "id": "B01DN8TB5U", + "ktx2_bytes": 634804, + "ktx2_file": "objects_ktx2/B01DN8TB5U/B01DN8TB5U.glb", + "lods": [ + { + "bytes": 182952, + "file": "lods/B01DN8TB5U/B01DN8TB5U_lod1.glb", + "texture_px": 1024, + "triangles": 786 + }, + { + "bytes": 50384, + "file": "lods/B01DN8TB5U/B01DN8TB5U_lod2.glb", + "texture_px": 512, + "triangles": 314 + }, + { + "bytes": 20140, + "file": "lods/B01DN8TB5U/B01DN8TB5U_lod3.glb", + "texture_px": 256, + "triangles": 220 + } + ], + "material": null, + "materials": 1, + "name": "AmazonBasics Classic Blank Notebook, 240 Pages, Hardcover - Plain", + "pack_bytes": 524720, + "product_type": "paper product", + "size_metres": [ + 0.127, + 0.2128, + 0.0157 + ], + "source_bytes": 14891808, + "source_texture_px": 4096, + "style": "Plain", + "texture_vram_mib_ktx2": 12, + "texture_vram_mib_webp": 64, + "triangles": 1574, + "vertices": 1164 + }, + "relationship": "community_conversion", + "repository": "codepawl/abo-glb", + "upstream_asset_id": "B01DN8TB5U", + "upstream_source": "amazon-berkeley-objects" + } + } + } + } +} diff --git a/examples/automatic_cabinet_layout/case.json b/examples/automatic_cabinet_layout/case.json new file mode 100644 index 0000000..637b003 --- /dev/null +++ b/examples/automatic_cabinet_layout/case.json @@ -0,0 +1,150 @@ +{ + "schema": "simscene.asset_gallery.v1", + "schema_version": 1, + "components": [ + { + "id": "box_support", + "case": { + "schema": "simscene.rigid_asset_smoke.v1", + "schema_version": 1, + "objects": { + "box": { + "motion_body": "/World/box/Asset/Body", + "contact_bodies": [ + "/World/box/Asset/Body" + ], + "visual_roots": [ + "/World/box/Asset/Body/Visual" + ], + "support_actors": [ + "/World/table" + ], + "target_bounds": { + "min": [ + -1.3, + -0.75, + 0.8 + ], + "max": [ + 1.3, + 0.75, + 1.25 + ] + }, + "initial_height_m": 0.8874879157630889, + "min_drop_m": 0.015 + } + }, + "source_ref": "${box.source_ref}", + "prepared_manifest_sha256": "${box.manifest_sha256}", + "physical_assumptions": "Imported geometry, experimental 0.12 kg, starts 0.04 m above an ordinary static table." + } + }, + { + "id": "book_support", + "case": { + "schema": "simscene.rigid_asset_smoke.v1", + "schema_version": 1, + "objects": { + "book_a": { + "motion_body": "/World/book_a/Asset/Body", + "contact_bodies": [ + "/World/book_a/Asset/Body" + ], + "visual_roots": [ + "/World/book_a/Asset/Body/Visual" + ], + "support_actors": [ + "/World/table" + ], + "target_bounds": { + "min": [ + -1.3, + -0.75, + 0.8 + ], + "max": [ + 1.3, + 0.75, + 1.25 + ] + }, + "initial_height_m": 0.8755482700515315, + "min_drop_m": 0.015 + }, + "book_b": { + "motion_body": "/World/book_b/Asset/Body", + "contact_bodies": [ + "/World/book_b/Asset/Body" + ], + "visual_roots": [ + "/World/book_b/Asset/Body/Visual" + ], + "support_actors": [ + "/World/table" + ], + "target_bounds": { + "min": [ + -1.3, + -0.75, + 0.8 + ], + "max": [ + 1.3, + 0.75, + 1.25 + ] + }, + "initial_height_m": 0.8755482659645374, + "min_drop_m": 0.015 + } + }, + "source_ref": "${book_a.source_ref}", + "prepared_manifest_sha256": "${book_a.manifest_sha256}", + "physical_assumptions": "Imported geometry, experimental 0.12 kg, starts 0.04 m above an ordinary static table." + } + }, + { + "id": "native_joint", + "case": { + "schema": "simscene.articulated_asset_smoke.v1", + "schema_version": 1, + "mode": "driven", + "objects": { + "cabinet": { + "joint_id": "main", + "joint_path": "/World/cabinet/Asset/Native/Joints/flap_hinge", + "parent_body": "/World/cabinet/Asset/Native/Links/cabinet_carcass", + "child_body": "/World/cabinet/Asset/Native/Links/flap_door", + "initial_position": 0.0, + "position_unit": "rad", + "limits": [ + 0.0, + 1.3962634015954636 + ], + "min_travel": 1.0, + "limit_tolerance": 0.015, + "anchor_tolerance_m": 0.003, + "source_ref": "${cabinet.source_ref}", + "prepared_manifest_sha256": "${cabinet.manifest_sha256}", + "waypoints": [ + { + "command_step": 0, + "target_position": 1.3962634015954636, + "by_step": 200, + "tolerance": 0.08 + }, + { + "command_step": 240, + "target_position": 0.0, + "by_step": 500, + "tolerance": 0.04 + } + ] + } + }, + "physical_model_note": "Original native two-link hinge and mass/colliders/friction; experimental scheduled drive. Supplemental acceptance SHA-256: 7e22adc1ce4eacad1edbfcc947b65efd3db0f7a11ce405f5fcdcc36109206b94" + } + } + ] +} diff --git a/examples/automatic_cabinet_layout/check.py b/examples/automatic_cabinet_layout/check.py new file mode 100644 index 0000000..f193bbc --- /dev/null +++ b/examples/automatic_cabinet_layout/check.py @@ -0,0 +1,122 @@ +"""Check the frozen cabinet layout case and its additional physical evidence.""" +import argparse +import hashlib +import json +import math +from pathlib import Path + +from pxr import Usd +from simscene.evidence_integrity import verify as verify_evidence +from simscene.physics_binding import validate_asset_binding +from simscene.preparation.articulation import inspect_articulation +from simscene.recipes.cases import freeze_case +from simscene.run_integrity import verify as verify_inputs +from simscene.verification.asset_gallery import verify_run +from simscene.verification.settling import stable + + +def sha(path): + digest = hashlib.sha256() + with path.open('rb') as stream: + for chunk in iter(lambda: stream.read(1024 * 1024), b''): + digest.update(chunk) + return digest.hexdigest() + + +def verify(run): + root = Path(__file__).resolve().parent + run = Path(run).resolve() + checks_path = root / 'supplemental-checks.json' + checks = json.loads(checks_path.read_text()) + selections = json.loads((root / 'assets.lock.json').read_text())['assets'] + selection = selections['cabinet'] + result = json.loads((run / 'result.json').read_text()) + spec = json.loads((run / 'spec.json').read_text()) + case = json.loads((run / 'acceptance-case.json').read_text()) + bindings = {role: {'asset_path': spec['objects'][role]['asset_path'], + 'asset_binding': spec['objects'][role]['asset_binding']} for role in selections} + template = json.loads((root / 'case.json').read_text()) + expected_case = freeze_case(template, bindings, selections)['case'] + inputs, evidence, core = verify_inputs(run), verify_evidence(run), verify_run(run) + frames = [result['initial_observation'], *result['samples']] + parent, door = checks['cabinet_parent'], checks['cabinet_child'] + records = [frame.get('mechanisms', {}).get('cabinet', {}).get('joints', {}).get('main', {}) for frame in frames] + + def finite(value): + return type(value) in (int, float) and math.isfinite(value) + + native = all(finite(record.get('native_position')) and finite(record.get('native_velocity')) and + record.get('native_measurement_source') == 'PhysX_articulation_tensor_DOF_readback_SI' and + finite(record.get('position')) and abs(record['native_position'] - record['position']) <= .015 + for record in records) + initial = frames[0]['positions'][parent] + displacements = [math.dist(initial, frame['positions'][parent]) for frame in frames] + contacts = set() + for frame in frames: + for pair in frame.get('contact_pairs', []): + actors = pair.get('actor_paths', []) + if len(actors) == 2 and pair.get('count', 0) > 0: + contacts.add(frozenset(actors)) + prop_bodies = [result['body_bindings'][name]['motion_body'] for name in checks['rigid_objects']] + forbidden = [sorted(pair) for pair in contacts if door in pair and any(body in pair for body in prop_bodies)] + keep = checks['reserved_volume'] + + def intersects(a, b): + return all(a['max'][i] > b['min'][i] and b['max'][i] > a['min'][i] for i in range(3)) + + prop_clear = all(not intersects(frame['bounds'][name], keep) for frame in frames for name in checks['rigid_objects']) + cabinet_contained = all(all(keep['min'][i] - .01 <= frame['bounds']['cabinet']['min'][i] and + frame['bounds']['cabinet']['max'][i] <= keep['max'][i] + .01 + for i in range(3)) for frame in frames) + obj = spec['objects']['cabinet'] + manifest = validate_asset_binding(obj['asset_binding'], require_dynamic=True, asset_path=obj['asset_path']) + package = Path(obj['asset_binding']['manifest_path']).parent + source_file = package / 'source' / selection['source_files'][0]['path'] + source = inspect_articulation(Usd.Stage.Open(str(source_file))) + source_joint, prepared_joint = source['joint_map']['main'], result['body_bindings']['cabinet']['joints']['main'] + joint_keys = ('type', 'axis', 'limits', 'position_unit', 'native_authored_attributes', + 'local_pos0_m', 'local_pos1_m', 'local_rot0_wxyz', 'local_rot1_wxyz') + source_masses = sorted(item['mass_kg'] for item in source['body_map'].values() if item.get('role') == 'rigid') + prepared_masses = sorted(item['mass_kg'] for item in manifest['body_map'].values() if item.get('role') == 'rigid') + note = case['components'][-1]['case']['physical_model_note'] + supplemental = { + 'case_matches_frozen_example': case == expected_case, + 'requirements_pinned_in_case': ('Supplemental acceptance SHA-256: ' + sha(checks_path)) in note, + 'native_dof_readback_each_step': native, + 'cabinet_supported_by_table': frozenset((parent, checks['support_actor'])) in contacts, + 'cabinet_settled_two_seconds': stable(frames, parent, result['simulation_time_s'], 2., + checks['max_linear_speed_m_s'], checks['max_angular_speed_rad_s']), + 'cabinet_translation_within_limit': max(displacements) <= checks['max_parent_translation_m'], + 'props_outside_reserved_sweep': prop_clear, + 'cabinet_inside_reserved_volume': cabinet_contained, + 'no_door_prop_contacts': not forbidden, + 'source_file_hash_matches_lock': sha(source_file) == selection['source_sha256'], + 'native_joint_attributes_preserved': all(source_joint.get(key) == prepared_joint.get(key) for key in joint_keys), + 'native_rigid_masses_preserved': len(source_masses) == 2 and source_masses == prepared_masses, + 'one_joint_binding': len(result['body_bindings']['cabinet']['joints']) == 1, + } + return {'schema': 'simscene.cabinet_layout_example_check.v1', 'run': str(run), + 'passed': (inputs['passed'] and evidence['passed'] and evidence['partial'] is False and + core['passed'] and all(supplemental.values())), + 'input_integrity': inputs, 'evidence_integrity': evidence, 'core_verification': core, + 'supplemental': supplemental, 'max_parent_translation_m': max(displacements), + 'native_dof_range_rad': [min(record['native_position'] for record in records if finite(record.get('native_position'))), + max(record['native_position'] for record in records if finite(record.get('native_position')))], + 'scope': 'One frozen layout and recorded run; not a general asset or structural certification.'} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--run', required=True) + parser.add_argument('--output', required=True, help='new JSON report path') + args = parser.parse_args() + report = verify(args.run) + with Path(args.output).open('x', encoding='utf8') as stream: + json.dump(report, stream, indent=2, allow_nan=False) + stream.write('\n') + print(json.dumps({'passed': report['passed'], 'output': args.output}, indent=2)) + return 0 if report['passed'] else 1 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/examples/automatic_cabinet_layout/recipe.json b/examples/automatic_cabinet_layout/recipe.json new file mode 100644 index 0000000..59008e3 --- /dev/null +++ b/examples/automatic_cabinet_layout/recipe.json @@ -0,0 +1,441 @@ +{ + "description": "Editable workbench, prepared native USDCraft cabinet, and three rigid props placed by a fixed scene_synthesizer plan.", + "source_run_id": "63d4a482dc0547458384a8eb8e91bf7c", + "source_run_lock_sha256": "d0fb328a93b653fde73c84278c96960ff9d34d694443e692087360bcd319c9e4", + "operations": [ + { + "op": "add", + "id": "floor", + "object": { + "kind": "box", + "size": [ + 7.0, + 7.0, + 0.1 + ], + "position": [ + 0.0, + 0.0, + -0.05 + ], + "color": [ + 0.16, + 0.19, + 0.22 + ], + "collision": true + } + }, + { + "op": "add", + "id": "table", + "object": { + "kind": "box", + "size": [ + 2.6, + 1.5, + 0.08 + ], + "position": [ + 0.0, + 0.0, + 0.79 + ], + "color": [ + 0.48, + 0.32, + 0.2 + ], + "support_surfaces": { + "worktop": { + "min_xy": [ + -1.28, + -0.73 + ], + "max_xy": [ + 1.28, + 0.73 + ], + "z_m": 0.04 + } + }, + "collision": true + } + }, + { + "op": "add", + "id": "cabinet", + "object": { + "kind": "asset", + "dynamic": true, + "position": [ + -0.7, + 0.2589999995995313, + 0.8320000029802322 + ], + "mechanism": { + "commands": [ + { + "joint_id": "main", + "trigger": { + "type": "at_step", + "physics_step": 0 + }, + "target_position": 1.3962634015954636, + "position_unit": "rad", + "stiffness": 400.0, + "damping": 12.0, + "max_effort": 22.0 + }, + { + "joint_id": "main", + "trigger": { + "type": "at_step", + "physics_step": 240 + }, + "target_position": 0.0, + "position_unit": "rad", + "stiffness": 400.0, + "damping": 12.0, + "max_effort": 22.0 + } + ] + }, + "asset_role": "cabinet" + } + }, + { + "op": "add", + "id": "box", + "object": { + "kind": "asset", + "dynamic": true, + "position": [ + 0.5940649325976486, + 0.2040442321891242, + 0.8874879157630889 + ], + "orientation_wxyz": [ + 0.7071067811865476, + 0.7071067811865476, + 0.0, + 0.0 + ], + "asset_role": "box" + } + }, + { + "op": "add", + "id": "book_a", + "object": { + "kind": "asset", + "dynamic": true, + "position": [ + 0.25885443006261455, + 0.3787859622261313, + 0.8755482700515315 + ], + "orientation_wxyz": [ + 0.7071067811865476, + 0.7071067811865476, + 0.0, + 0.0 + ], + "asset_role": "book_a" + } + }, + { + "op": "add", + "id": "book_b", + "object": { + "kind": "asset", + "dynamic": true, + "position": [ + 0.798020155100152, + -0.36695188849847077, + 0.8755482659645374 + ], + "orientation_wxyz": [ + 0.6532814824381883, + 0.6532814824381883, + 0.2705980500730985, + 0.2705980500730985 + ], + "asset_role": "book_a" + } + }, + { + "op": "add", + "id": "sky", + "object": { + "kind": "light", + "light": { + "type": "dome" + }, + "intensity": 500.0 + } + }, + { + "op": "add", + "id": "key", + "object": { + "kind": "light", + "light": { + "type": "sphere", + "radius_m": 0.4 + }, + "intensity": 2000.0, + "position": [ + 0.0, + -2.5, + 4.5 + ] + } + }, + { + "op": "add", + "id": "overview", + "object": { + "kind": "camera", + "position": [ + 2.35, + -3.8, + 2.7 + ], + "record_fps": 30, + "preview_fps": 1, + "camera": { + "resolution": [ + 1920, + 1080 + ], + "focal_length_mm": 45.0, + "horizontal_aperture_mm": 36.0, + "focus_distance_m": 4.8, + "clipping_range_m": [ + 0.01, + 100.0 + ] + }, + "orientation_wxyz": [ + 0.7892491473713551, + 0.5475675619401452, + 0.15843890467573032, + 0.2283695732133975 + ] + } + }, + { + "op": "add", + "id": "leg_lf", + "object": { + "kind": "box", + "size": [ + 0.09, + 0.09, + 0.75 + ], + "position": [ + -1.12, + -0.57, + 0.375 + ], + "color": [ + 0.16, + 0.15, + 0.14 + ] + } + }, + { + "op": "add", + "id": "leg_lb", + "object": { + "kind": "box", + "size": [ + 0.09, + 0.09, + 0.75 + ], + "position": [ + -1.12, + 0.57, + 0.375 + ], + "color": [ + 0.16, + 0.15, + 0.14 + ] + } + }, + { + "op": "add", + "id": "leg_rf", + "object": { + "kind": "box", + "size": [ + 0.09, + 0.09, + 0.75 + ], + "position": [ + 1.12, + -0.57, + 0.375 + ], + "color": [ + 0.16, + 0.15, + 0.14 + ] + } + }, + { + "op": "add", + "id": "leg_rb", + "object": { + "kind": "box", + "size": [ + 0.09, + 0.09, + 0.75 + ], + "position": [ + 1.12, + 0.57, + 0.375 + ], + "color": [ + 0.16, + 0.15, + 0.14 + ] + } + }, + { + "op": "add", + "id": "detail", + "object": { + "kind": "camera", + "position": [ + 1.15, + -1.35, + 1.55 + ], + "orientation_wxyz": [ + 0.8229543905415312, + 0.5298565641295101, + 0.11094044795234974, + 0.1723087622421428 + ], + "record_fps": 30, + "preview_fps": 1, + "camera": { + "resolution": [ + 1920, + 1080 + ], + "focal_length_mm": 35.0, + "horizontal_aperture_mm": 36.0, + "focus_distance_m": 1.8, + "clipping_range_m": [ + 0.01, + 100.0 + ] + }, + "camera_path": [ + { + "time_s": 0.0, + "position": [ + 1.15, + -1.35, + 1.55 + ], + "target": [ + 0.55, + 0.02, + 0.87 + ] + }, + { + "time_s": 2.2, + "position": [ + 1.15, + -1.35, + 1.55 + ], + "target": [ + 0.55, + 0.02, + 0.87 + ] + }, + { + "time_s": 3.8, + "position": [ + -0.2, + -1.55, + 1.72 + ], + "target": [ + -0.7, + 0.2, + 1.05 + ] + }, + { + "time_s": 10.0, + "position": [ + -0.2, + -1.55, + 1.72 + ], + "target": [ + -0.7, + 0.2, + 1.05 + ] + } + ] + } + }, + { + "op": "set_presentation", + "presentation": { + "profile": "technical_showcase_1080p", + "capture": { + "resolution": [ + 1920, + 1080 + ], + "fps": 30, + "anti_aliasing": "dlaa", + "renderer": "RealTimePathTracing", + "depth_of_field": false, + "motion_blur": false, + "exposure_mode": "manual", + "exposure_ev": 0 + }, + "budget": { + "max_cameras": 2, + "max_recording_bytes": 4294967296, + "min_free_bytes": 4294967296 + }, + "diagnostics": { + "png_seconds": 0.1, + "keyframe_interval_s": 2 + } + } + }, + { + "op": "set_observation", + "observation": { + "sample_interval_steps": 1, + "strict_start": true, + "record_contact_pairs": true + } + } + ], + "schema": "simscene.scene_recipe.v2" +} diff --git a/examples/automatic_cabinet_layout/supplemental-checks.json b/examples/automatic_cabinet_layout/supplemental-checks.json new file mode 100644 index 0000000..0d81ccd --- /dev/null +++ b/examples/automatic_cabinet_layout/supplemental-checks.json @@ -0,0 +1,30 @@ +{ + "schema": "demo.supplemental_checks.v1", + "reserved_volume": { + "min": [ + -1.3, + -0.75, + 0.83 + ], + "max": [ + -0.1, + 0.75, + 1.75 + ] + }, + "cabinet_parent": "/World/cabinet/Asset/Native/Links/cabinet_carcass", + "cabinet_child": "/World/cabinet/Asset/Native/Links/flap_door", + "support_actor": "/World/table", + "rigid_objects": [ + "box", + "book_a", + "book_b" + ], + "max_parent_translation_m": 0.05, + "last_seconds_for_settling": 2.0, + "max_linear_speed_m_s": 0.03, + "max_angular_speed_rad_s": 0.3, + "require_native_dof_every_sample": true, + "forbid_door_prop_contacts": true, + "scope": "separate frozen requirements; actual outcome not yet observed" +} diff --git a/pyproject.toml b/pyproject.toml index a2c6dc9..1d01cc9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "rosclaw-simscene" -version = "0.2.0.dev1" +version = "0.2.0.dev2" requires-python = ">=3.10" description = "Agent-oriented simulation scene tools" readme = "README.md" diff --git a/skills/build-scene/references/measured-layout.md b/skills/build-scene/references/measured-layout.md index 8ab7ad6..9d73e17 100644 --- a/skills/build-scene/references/measured-layout.md +++ b/skills/build-scene/references/measured-layout.md @@ -24,6 +24,25 @@ orientation before measuring. `avoid_ids`, `clearance_m`, and world metre `keepout_bounds:[{min:[x,y,z],max:[x,y,z]}]` reject reserved-space intrusion. This is geometric placement, not a dynamic stability proof. +For repeatable sampled placement of 1–8 existing props, call +`scene_plan_layout(scene_id, ids, support, support_surface, seed, clearance_m, +gap_m, avoid_ids, keepout_bounds)`. Omit `support_surface` for a primitive box +top. It requires an isolated `scene_synthesizer==1.15.0` environment available +to the MCP server through `SIMSCENE_LAYOUT_PYTHON`; configure it separately +without changing Isaac's Python. Imported props, obstacles and supports require +verified local prepared bindings; imported supports must be static prepared +fixtures with colliders. A primitive support for dynamic props requires +`collision:true`. Compounds with attached visuals are not supported. Record the +seed, backend/dependency versions, source pins and returned `plan_sha256`; the +same versions do not pin every native library or guarantee cross-machine output. +The tool does not edit the scene: apply +all returned operations in one `scene_apply` at `base_revision`; replan after a +revision conflict. Measured render-box proxies preserve the supplied USD and +orientation, and explicit obstacles/keepouts are projected in XY regardless +of height. The planner cannot infer door sweeps or certify collision geometry, +stability or motion; inspect and conservatively reserve working space, then +run and verify an actual case. + `arrange_grid` uses `ids`, `support`, optional `support_surface`, `columns`, `gap_m` (between cells), `offset_xy`, optional `vertical_gap_m`, and the same clearance fields. Row/column dimensions come from measured footprints. diff --git a/src/simscene/acquisition/plans.py b/src/simscene/acquisition/plans.py index aac488d..16bf73c 100644 --- a/src/simscene/acquisition/plans.py +++ b/src/simscene/acquisition/plans.py @@ -21,7 +21,7 @@ def make_plan(ref, profile_id='visual_prop_v1', parameters=None, target=None, bu ref = AssetRef.from_dict(ref) if isinstance(ref, dict) else ref if not isinstance(ref, AssetRef): raise ValueError('asset_ref must be a valid AssetRef') ref.validate_selection() - record = record or resolve_asset(ref, index_directory=config['index_directory']) + record = record or resolve_asset(ref, index_directory=config['index_directory'], registry_path=config.get('registry_path')) if record.ref != ref: raise ValueError('resolved selection does not match ref') budgets = dict(budgets or {}) allowed = {'download_bytes', 'unpacked_bytes', 'staging_bytes'} diff --git a/src/simscene/catalog/providers/hf_manifest.py b/src/simscene/catalog/providers/hf_manifest.py index 5e2fce9..226863e 100644 --- a/src/simscene/catalog/providers/hf_manifest.py +++ b/src/simscene/catalog/providers/hf_manifest.py @@ -60,6 +60,10 @@ def url(self,path): def metadata_url(self): return self.url(self.entry.path) + def snapshot_identity(self, payload): + """Identify the source bytes and any subclass-specific projection.""" + return self.entry.revision+':'+hashlib.sha256(payload).hexdigest() + def rows(self,payload): if self.entry.format=='csv': text=payload.decode('utf-8-sig');yield from enumerate(csv.DictReader(io.StringIO(text)),1) @@ -83,7 +87,7 @@ def refresh(self): except (ValueError,TypeError,KeyError,UnicodeError,csv.Error): raise MetadataError('manifest metadata schema changed; previous index preserved') from None if not records:raise MetadataError('manifest metadata is empty') - identity=self.entry.revision+':'+hashlib.sha256(payload).hexdigest() + identity=self.snapshot_identity(payload) self.store.replace_index(self.source_id,records,identity) return {'source_id':self.source_id,'snapshot':identity,'records':len(records),'metadata_bytes':len(payload),'model_bytes':0, 'text_index':'fts5' if self.store.fts else 'bounded_text_fallback'} @@ -121,7 +125,7 @@ def _record(self,row): def search(self,request): self.check_deadline();start=len(self.ledger) if self.snapshot=='index_not_refreshed':self.refresh() - records=self.store.search(self.source_id,request.query,limit=100);self.check_deadline() + records=self.store.search(self.source_id,request.query,limit=100,revision=self.entry.revision);self.check_deadline() count=sum(entry.get('bytes',0) for entry in self.ledger[start:] if entry.get('category')=='metadata') return ProviderPage(records,self.snapshot,bytes_read=count,warnings=(() if self.store.fts else ('fts5_unavailable',))) diff --git a/src/simscene/catalog/providers/simready_package.py b/src/simscene/catalog/providers/simready_package.py index 1494142..59dd23d 100644 --- a/src/simscene/catalog/providers/simready_package.py +++ b/src/simscene/catalog/providers/simready_package.py @@ -10,6 +10,9 @@ from ..network import MetadataError, fetch_metadata +USDCRAFT_PROJECTION_SUFFIX = ':usdcraft-structure-v2' + + class USDCraftProvider(HFManifestProvider): """Project the pinned native CSV; dependency completeness stays unknown.""" def __init__(self,store,source,**kwargs): @@ -17,6 +20,40 @@ def __init__(self,store,source,**kwargs): super().__init__(store,source,**kwargs) if self.entry.path!='manifest.csv' or self.entry.format!='csv':raise ValueError('USDCraft requires pinned manifest.csv') + @property + def snapshot(self): + value=super().snapshot + # Persist the projection version itself. Presence of fields cannot tell + # whether an older projector computed articulated contradictions safely. + return value if value.endswith(USDCRAFT_PROJECTION_SUFFIX) else 'index_not_refreshed' + + def snapshot_identity(self, payload): + # The projection and its records are published in one SQLite transaction. + return super().snapshot_identity(payload)+USDCRAFT_PROJECTION_SUFFIX + + def reproject(self, record): + # An older concurrently running server can still remember an old row + # after an atomic refresh. Recompute its derived facts on every new read. + row = record.provenance.get('original_metadata') if isinstance(record.provenance, dict) else None + result = self._record(row) + if result.ref != record.ref: + raise ValueError('USDCraft index row identity does not match its source metadata') + return result + + def search(self, request): + page = super().search(request) + if page.snapshot == 'index_not_refreshed': + raise MetadataError('USDCraft metadata index changed during search') + return ProviderPage(tuple(self.reproject(record) for record in page.items), page.snapshot, + bytes_read=page.bytes_read, warnings=page.warnings) + + def resolve(self, ref): + if ref.source_id != self.source_id: + raise ValueError('wrong USDCraft manifest source') + ref.validate_selection(huggingface=True) + return self.reproject(self.store.get(ref, require_snapshot_prefix=self.entry.revision+':', + require_snapshot_suffix=USDCRAFT_PROJECTION_SUFFIX)) + def _record(self,row): required={'object_id','path','group','category','title','physics_type','part_count','joint_count','joint_types','has_textures','physx_sha256'} if not isinstance(row,dict) or not required<=set(row):raise ValueError('USDCraft manifest schema changed') @@ -25,19 +62,33 @@ def _record(self,row): joints=int(row['joint_count']);parts=int(row['part_count']) if joints<0 or parts<1 or row['has_textures'] not in {'true','false'} or row['physics_type'] not in {'rigid','articulated','static','static_rigid'}: raise ValueError('invalid declared native physics metadata') + if not isinstance(row['joint_types'],str):raise ValueError('invalid declared native joint types') + joint_types=row['joint_types'].split('|') if row['joint_types'] else [] + unique_types=set(joint_types) + coherent=(unique_types <= {'revolute','continuous','prismatic'} and len(unique_types)==len(joint_types) + and ((row['physics_type']=='articulated' and 0 remaining: + exceeded.set() + kill_group() + break + finally: + pipe.close() + + def write(): + try: + remaining = memoryview(payload) + while remaining: + remaining = remaining[os.write(process.stdin.fileno(), remaining):] + except (BrokenPipeError, OSError): + pass + finally: + process.stdin.close() + + threads = [threading.Thread(target=read, args=(process.stdout, streams[0]), daemon=True), + threading.Thread(target=read, args=(process.stderr, streams[1]), daemon=True), + threading.Thread(target=write, daemon=True)] + for thread in threads: + thread.start() + try: + process.wait(timeout=max(0, deadline - time.monotonic())) + for thread in threads: + thread.join(timeout=max(0, deadline - time.monotonic())) + if any(thread.is_alive() for thread in threads): + raise subprocess.TimeoutExpired(command, timeout) + except subprocess.TimeoutExpired: + kill_group() + process.wait() + for thread in threads: + thread.join(timeout=2) + raise + if exceeded.is_set(): + raise SceneError('scene_synthesizer backend output exceeds limit') + return process.returncode, bytes(streams[0]), bytes(streams[1]) + + +def _run_backend(request): + """Run a fixed local worker, not caller-provided code, in the chosen Python.""" + executable = os.environ.get('SIMSCENE_LAYOUT_PYTHON') or sys.executable + worker = Path(__file__).with_name('layout_synthesis_worker.py').resolve() + payload = json.dumps(request, allow_nan=False).encode() + if len(payload) > 1024 * 1024: + raise SceneError('scene_synthesizer request exceeds limit') + try: + code, stdout, stderr = _bounded_process([executable, '-I', str(worker)], payload) + except (OSError, subprocess.TimeoutExpired) as error: + raise SceneError('scene_synthesizer backend unavailable or timed out; configure ' + 'SIMSCENE_LAYOUT_PYTHON for an isolated 1.15.0 environment') from error + if code: + diagnostic = stderr.decode(errors='replace')[-1500:].strip() + raise SceneError('scene_synthesizer backend failed; configure SIMSCENE_LAYOUT_PYTHON ' + 'for an isolated 1.15.0 environment: ' + diagnostic) + try: + return json.loads(stdout) + except (ValueError, UnicodeError) as error: + raise SceneError('scene_synthesizer backend returned invalid JSON') from error + + +def plan_layout(scene, ids, support, *, support_surface=None, seed=0, clearance_m=.01, + gap_m=0., avoid_ids=None, keepout_bounds=None): + """Return ordinary checked ``place_on`` edits without modifying *scene*. + + Support and object positions use metres and Z-up. The optional backend + samples conservative render-AABB proxies; this is not a PhysX collision + or dynamic-stability certificate. + """ + if not isinstance(scene, dict) or not isinstance(scene.get('objects'), dict): + raise SceneError('layout requires a scene with objects') + revision = scene.get('revision') + if type(revision) is not int or revision < 0: + raise SceneError('layout requires a nonnegative scene revision') + world = scene.get('world', {}) + if not isinstance(world, dict) or world.get('units', 'm') != 'm' or world.get('up_axis', 'Z') != 'Z': + raise SceneError('layout requires a metre Z-up scene') + objects = scene['objects'] + if (not isinstance(ids, list) or not 1 <= len(ids) <= 8 or + not all(isinstance(name, str) and name in objects for name in ids) or len(ids) != len(set(ids))): + raise SceneError('layout requires 1..8 distinct existing object IDs') + if not isinstance(support, str) or support not in objects or support in ids: + raise SceneError('layout requires a distinct existing support') + if not isinstance(objects[support], dict) or any(not isinstance(objects[name], dict) for name in ids): + raise SceneError('layout objects must be scene object mappings') + if objects[support].get('dynamic') is True: + raise SceneError('layout support must be static') + if support_surface is not None and (not isinstance(support_surface, str) or not support_surface): + raise SceneError('support_surface must name an explicit support region') + if type(seed) is not int or not 0 <= seed < 2**32: + raise SceneError('seed must be an integer in [0, 2**32)') + clearance = _finite_number(clearance_m, 'clearance_m', 0, .5) + gap = _finite_number(gap_m, 'gap_m', 0, .1) + avoid = [] if avoid_ids is None else avoid_ids + if (not isinstance(avoid, list) or len(avoid) > 32 or + any(not isinstance(name, str) or name not in objects or name in ids or name == support for name in avoid) or + len(set(avoid)) != len(avoid)): + raise SceneError('avoid_ids must name distinct existing obstacles outside the placement and support') + keepouts = [] if keepout_bounds is None else keepout_bounds + if not isinstance(keepouts, list) or len(keepouts) > 32: + raise SceneError('keepout_bounds must contain at most 32 world-space bounds') + for box in keepouts: + if (not isinstance(box, dict) or set(box) != {'min', 'max'} or + not vector(box.get('min')) or not vector(box.get('max')) or + any(a >= b for a, b in zip(box['min'], box['max']))): + raise SceneError('invalid keepout bounds') + related = [support, *ids, *avoid] + for child in objects.values(): + if isinstance(child, dict) and isinstance(child.get('rigid_attachment'), dict) and child['rigid_attachment'].get('body') in related: + raise SceneError('layout of compounds with attached visuals is not supported; prepare a verified asset instead') + from .physics_binding import validate_asset_binding + source_pins = [] + manifests = {} + for name in related: + obj = objects[name] + if not isinstance(obj, dict): + raise SceneError('layout objects must be scene object mappings') + if obj.get('kind') != 'asset': + continue + if not obj.get('asset_binding'): + raise SceneError('layout imported assets require a verified prepared binding: ' + name) + try: + manifest = validate_asset_binding(obj['asset_binding'], require_dynamic=obj.get('dynamic') is True, + asset_path=obj.get('asset_path')) + except (OSError, ValueError, TypeError, KeyError, AttributeError) as error: + raise SceneError('layout prepared asset ' + name + ': ' + str(error)) from error + manifests[name] = manifest + source_pins.append({'id': name, 'status': 'verified_prepared', + 'manifest_sha256': obj['asset_binding']['manifest_sha256'], + 'profile_id': manifest.get('profile_id')}) + support_obj = objects[support] + dynamic_ids = [name for name in ids if objects[name].get('dynamic') is True] + + def primitive_has_collider(obj): + if obj.get('collision', obj.get('dynamic', False)) is not True: + return False + if obj.get('kind') == 'compound': + parts = obj.get('parts', []) + return isinstance(parts, list) and any(isinstance(part, dict) and part.get('collision', True) is True for part in parts) + return obj.get('kind') in ('box', 'sphere', 'cylinder', 'capsule') + + if support_obj.get('kind') == 'asset': + manifest = manifests[support] + if (manifest.get('profile_id') not in ('static_fixture_v1', 'container_v1') or + not any(entry.get('collider_relative_prim_paths') for entry in manifest.get('body_map', {}).values())): + raise SceneError('imported support requires a prepared static collision fixture') + # The manifest hash alone does not establish static physics. The common + # exporter opens the actual USD and checks authored units, actual + # colliders, dynamic schemas, executable graphs and dependency closure. + bounds(support_obj, scene, support) + # The generic exporter does not traverse instance proxies when checking + # static assets. Reject instances here until that whole graph is admitted. + from pxr import Usd + stage = Usd.Stage.Open(str(Path(support_obj['asset_path']).expanduser().resolve())) + if not stage or any(prim.IsInstance() or prim.IsInstanceable() for prim in stage.TraverseAll()): + raise SceneError('instanced imported support is not supported by the layout planner') + elif dynamic_ids and not primitive_has_collider(support_obj): + raise SceneError('dynamic layout objects require an enabled collision support') + for name in dynamic_ids: + obj = objects[name] + if obj.get('kind') != 'asset' and not primitive_has_collider(obj): + raise SceneError('dynamic layout object requires an enabled collision shape: ' + name) + item_exclusions, support_exclusions = obj.get('collision_exclusions', []), support_obj.get('collision_exclusions', []) + if not isinstance(item_exclusions, list) or not isinstance(support_exclusions, list): + raise SceneError('collision exclusions must be lists') + if support in item_exclusions or name in support_exclusions: + raise SceneError('layout support and dynamic object have collision exclusions: ' + name) + region, orientation, position = surface(objects[support], support_surface) + if any(objects[name].get('rigid_attachment') for name in ids): + raise SceneError('arrange physical parents rather than attached visuals') + center = [(region['min_xy'][i] + region['max_xy'][i]) / 2 for i in range(2)] + items = [] + for name in ids: + box = _local_box(bounds(objects[name], scene, name), orientation, position) + size = [box['max'][i] - box['min'][i] for i in range(3)] + if any(not math.isfinite(value) or value <= 0 for value in size): + raise SceneError('layout object requires finite positive measured bounds: ' + name) + items.append({'id': name, 'size_m': size}) + reserved = [dict(copy.deepcopy(rect), kind='excluded_support') for rect in region.get('exclude', [])] + for name in avoid: + if not isinstance(objects[name], dict): + raise SceneError('obstacle must be a scene object mapping') + local = _local_box(bounds(objects[name], scene, name), orientation, position) + reserved.append({'min_xy': local['min'][:2], 'max_xy': local['max'][:2], 'kind': 'obstacle'}) + for box in keepouts: + local = _local_box(box, orientation, position) + reserved.append({'min_xy': local['min'][:2], 'max_xy': local['max'][:2], 'kind': 'keepout'}) + request = {'schema': 'simscene.scene_synthesizer.request.v1', 'seed': seed, + 'support': {'min_xy': list(region['min_xy']), 'max_xy': list(region['max_xy'])}, + 'items': items, 'reserved_xy': reserved, 'clearance_m': clearance} + result = _run_backend(request) + backend = result.get('backend') if isinstance(result, dict) else None + dependencies = backend.get('dependency_versions') if isinstance(backend, dict) else None + native = backend.get('native_versions') if isinstance(backend, dict) else None + version_string = lambda value: isinstance(value, str) and 0 < len(value) <= 128 + if (not isinstance(result, dict) or result.get('schema') != 'simscene.scene_synthesizer.placements.v1' or + type(result.get('seed')) is not int or result['seed'] != seed or + not isinstance(backend, dict) or backend.get('name') != 'scene_synthesizer' or + backend.get('version') != '1.15.0' or not version_string(backend.get('python')) or + not version_string(backend.get('platform')) or not version_string(backend.get('geometry')) or + not isinstance(dependencies, dict) or not 7 <= len(dependencies) <= 512 or + not {'numpy', 'trimesh', 'python-fcl', 'shapely', 'rtree', 'scipy', 'networkx'} <= set(dependencies) or + not all(version_string(key) and version_string(value) for key, value in dependencies.items()) or + not isinstance(native, dict) or not version_string(native.get('geos')) or + not isinstance(result.get('placements'), list)): + raise SceneError('scene_synthesizer returned an invalid response or unexpected version') + selected = result['placements'] + if (len(selected) != len(ids) or any(not isinstance(row, dict) or set(row) != {'id', 'offset_xy'} for row in selected) or + [row.get('id') for row in selected] != ids or any(not vector(row.get('offset_xy'), 2) for row in selected)): + raise SceneError('scene_synthesizer returned missing, duplicate or invalid placements') + probe = copy.deepcopy(scene) + operations, placements = [], [] + footprints = [] + for row, item_spec in zip(selected, items): + name = row['id'] + xy = [center[i] + row['offset_xy'][i] for i in range(2)] + low = [xy[i] - item_spec['size_m'][i] / 2 for i in range(2)] + high = [xy[i] + item_spec['size_m'][i] / 2 for i in range(2)] + if any(low[i] < region['min_xy'][i] + clearance - 1e-7 or + high[i] > region['max_xy'][i] - clearance + 1e-7 for i in range(2)): + raise SceneError('placement exceeds support bounds or edge clearance') + for other in [*reserved, *footprints]: + if all(high[i] + clearance > other['min_xy'][i] + 1e-7 and + other['max_xy'][i] + clearance > low[i] + 1e-7 for i in range(2)): + reason = 'reserved area' if other.get('kind') in {'excluded_support', 'keepout'} else 'clearance' + raise SceneError('placement violates ' + reason) + footprints.append({'min_xy': low, 'max_xy': high, 'kind': 'placed'}) + op = {'op': 'place_on', 'id': name, 'support': support, 'offset_xy': list(row['offset_xy']), + 'gap_m': gap, 'clearance_m': clearance, 'avoid_ids': [*avoid, *(item['id'] for item in placements)], + 'keepout_bounds': copy.deepcopy(keepouts)} + if support_surface is not None: + op['support_surface'] = support_surface + # Re-evaluate real scene render bounds rather than trusting the worker. + place_on(probe, op) + item = probe['objects'][name] + placements.append({'id': name, 'position_m': copy.deepcopy(item['position']), + 'orientation_wxyz': copy.deepcopy(item.get('orientation_wxyz', [1, 0, 0, 0])), + 'support_id': support, 'support_surface': support_surface}) + operations.append(op) + problems = validate(probe) + if problems: + raise SceneError('proposed layout would not form a valid scene: ' + str(problems[:5])) + # A matching set of box dimensions is not a matching scene. Bind the plan + # to the actual objects, support, world, proposal and backend versions so a + # change to a source, physical property, support pose or gap is visible. + context = {'scene_id': scene.get('scene_id'), 'base_revision': revision, 'world': world, 'support_id': support, + 'support_surface': support_surface, 'gap_m': gap, + 'objects': {name: objects[name] for name in [support, *ids, *avoid]}, + 'keepout_bounds': keepouts, 'request': request, 'backend': result['backend'], + 'placements': selected} + identity = hashlib.sha256(json.dumps(context, sort_keys=True, separators=(',', ':'), + allow_nan=False).encode()).hexdigest() + return {'schema': 'simscene.layout_plan.v1', 'base_revision': revision, 'seed': seed, + 'plan_sha256': identity, 'backend': result['backend'], 'placements': placements, + 'operations': operations, 'source_pins': source_pins, 'physics_tested': False, + 'scope': ('Conservative rendered-AABB proxies, explicit support/obstacles and unchanged object orientations. ' + 'Source USD and physics are not modified; actual colliders, unlisted obstacles, door sweep ' + 'and dynamic stability require separate checks. Obstacles and keepouts are projected in XY ' + 'regardless of height. Prepared packages were checked at planning time; recheck ' + 'their integrity and the actual physics when applying and running.')} diff --git a/src/simscene/layout_synthesis_worker.py b/src/simscene/layout_synthesis_worker.py new file mode 100644 index 0000000..dd75589 --- /dev/null +++ b/src/simscene/layout_synthesis_worker.py @@ -0,0 +1,107 @@ +"""Private single-request scene_synthesizer process; uses box proxies only.""" +import contextlib +from importlib.metadata import distributions, version +import itertools +import json +import math +import platform +import sys + + +def _run(request): + # Imports stay inside the selected environment; Isaac and base MCP do not + # need this optional stack. Redirect third-party chatter away from JSON. + with contextlib.redirect_stdout(sys.stderr): + import numpy as np + import scene_synthesizer as synth + import shapely + from scene_synthesizer import assets + + actual_version = version('scene-synthesizer') + if actual_version != '1.15.0': + raise ValueError('scene_synthesizer 1.15.0 is required; found ' + actual_version) + if not isinstance(request, dict) or request.get('schema') != 'simscene.scene_synthesizer.request.v1': + raise ValueError('unsupported layout request') + seed = request['seed'] + if type(seed) is not int or not 0 <= seed < 2**32: + raise ValueError('invalid seed') + support = request['support'] + low, high = support['min_xy'], support['max_xy'] + center = [(low[i] + high[i]) / 2 for i in range(2)] + dimensions = [high[i] - low[i] for i in range(2)] + if any(not math.isfinite(value) or value <= 0 for value in dimensions): + raise ValueError('invalid support dimensions') + items, reserved, clearance = request['items'], request['reserved_xy'], request['clearance_m'] + if not isinstance(items, list) or not 1 <= len(items) <= 8 or not isinstance(reserved, list): + raise ValueError('invalid layout items or reserved regions') + + # Upstream 1.15.0's polygon sampler also uses numpy.random's global + # generator. This process handles exactly one request, so seeding both + # generators does not perturb the MCP server or another user's job. + np.random.seed(seed) + scene = synth.Scene(seed=seed) + scene.add_object(assets.BoxAsset(extents=[*dimensions, .05]), obj_id='worktop', + translation=[*center, -.025]) + surfaces = scene.label_support('surface', obj_ids='worktop', erosion_distance=0, min_area=0) + if len(surfaces) != 1: + raise ValueError('proxy support could not be resolved to one surface') + occupied = list(reserved) + placements = [] + for index, item in enumerate(items): + name, size = item['id'], item['size_m'] + if not isinstance(name, str) or len(size) != 3 or any(not math.isfinite(v) or v <= 0 for v in size): + raise ValueError('invalid object proxy') + asset = assets.BoxAsset(extents=size, origin=('center', 'center', 'bottom')) + + def valid(_asset, _support, transform): + if not np.allclose(transform[:3, :3], np.eye(3), atol=1e-8): + return False + xy = transform[:2, 3] + left = [xy[i] - size[i] / 2 for i in range(2)] + right = [xy[i] + size[i] / 2 for i in range(2)] + if any(left[i] < low[i] + clearance or right[i] > high[i] - clearance for i in range(2)): + return False + return not any(all(right[i] + clearance > other['min_xy'][i] and + other['max_xy'][i] + clearance > left[i] for i in range(2)) + for other in occupied) + + proxy_id = f'simscene_item_{index:02d}' + succeeded = scene.place_object(proxy_id, asset, support_id='surface', + obj_orientation_iterator=itertools.repeat(np.eye(4)), max_iter=500, + distance_above_support=.002, valid_placement_fn=valid) + transforms = scene.get_object_transforms() + if not succeeded or proxy_id not in transforms: + raise ValueError('no valid proxy placement found for ' + name) + transform = transforms[proxy_id] + if not np.allclose(transform[:3, :3], np.eye(3), atol=1e-8): + raise ValueError('unexpected proxy orientation for ' + name) + xy = [float(transform[i, 3]) for i in range(2)] + occupied.append({'min_xy': [xy[i] - size[i] / 2 for i in range(2)], + 'max_xy': [xy[i] + size[i] / 2 for i in range(2)]}) + placements.append({'id': name, 'offset_xy': [xy[i] - center[i] for i in range(2)]}) + versions = {} + for dist in distributions(): + name = dist.metadata.get('Name', '').lower().replace('_', '-') + if not name or name in versions and versions[name] != dist.version: + raise ValueError('invalid or conflicting backend distribution identity') + versions[name] = dist.version + if len(versions) > 512: + raise ValueError('layout environment has too many distributions; use an isolated environment') + return {'schema': 'simscene.scene_synthesizer.placements.v1', 'seed': seed, + 'backend': {'name': 'scene_synthesizer', 'version': actual_version, + 'dependency_versions': versions, 'python': platform.python_version(), + 'platform': platform.platform(), 'native_versions': {'geos': shapely.geos_version_string}, + 'geometry': 'render-bounds box proxies; original USD not imported'}, + 'placements': placements} + + +if __name__ == '__main__': + try: + data = sys.stdin.buffer.read(1024 * 1024 + 1) + if len(data) > 1024 * 1024: + raise ValueError('layout request exceeds size limit') + result = _run(json.loads(data)) + print(json.dumps(result, separators=(',', ':'), allow_nan=False)) + except (ValueError, TypeError, KeyError, ImportError, OSError, RuntimeError) as error: + print(f'{type(error).__name__}: {error}', file=sys.stderr) + sys.exit(2) diff --git a/src/simscene/mcp_server.py b/src/simscene/mcp_server.py index 5e24861..992e28f 100644 --- a/src/simscene/mcp_server.py +++ b/src/simscene/mcp_server.py @@ -4,6 +4,7 @@ import os from mcp.server.fastmcp import FastMCP, Image from mcp.types import ToolAnnotations +from pydantic import StrictFloat, StrictInt from .assets import USDSearch from .cache import AssetCache @@ -188,6 +189,28 @@ def scene_measure(scene_id: str, ids: list[str], include_overlap_candidates: boo from .placement import measure return measure(SceneStore().get(scene_id),ids,include_overlap_candidates) +@threaded_tool(annotations=_read_local) +def scene_plan_layout(scene_id: str, ids: list[str], support: str, support_surface: str | None = None, + seed: StrictInt = 0, clearance_m: StrictFloat = .01, gap_m: StrictFloat = 0., + avoid_ids: list[str] | None = None, keepout_bounds: list[dict] | None = None) -> dict: + """Propose editable place_on operations for up to eight existing objects on an explicit static support. + + Requires scene_synthesizer 1.15.0 in SIMSCENE_LAYOUT_PYTHON; it operates + on measured bounding-box proxies, without editing source USD or the scene. + Imported props, obstacles and supports require verified prepared bindings; + dynamic props require a colliding static support. Compounds with attached + visuals are not supported. + Apply all operations at the returned base_revision. Explicitly include any + obstacles and moving-mechanism keepouts. Actual colliders, joint sweeps and + dynamic stability require physical inspection and a new simulation. + """ + from .layout_synthesis import plan_layout + from .scene import SceneStore + plan = plan_layout(SceneStore().get(scene_id), ids, support, support_surface=support_surface, + seed=seed, clearance_m=clearance_m, gap_m=gap_m, avoid_ids=avoid_ids, + keepout_bounds=keepout_bounds) + return {**plan, 'scene_id': scene_id} + @threaded_tool(annotations=_read_local) def scene_plan_rope(scene_id: str, prefix: str, points: list[list[float]], radius_m: float = .005, max_segment_m: float = .025, linear_density_kg_m: float = .06, attachments: dict | None = None, physics: dict | None = None, self_collision: bool = True) -> dict: """Propose real colliding capsule links connected by passive spherical joints. points are a metric world polyline, including deliberate slack. Optional start/end attachments each use body and local_position_m. Apply returned ordinary operations after review. This is not a distance-only or animated rope; routing over a free pulley and actual tension transfer need physical trials and broken-end controls.""" diff --git a/tests/agent/test_catalog_mcp_contract.py b/tests/agent/test_catalog_mcp_contract.py index d572346..18d5faa 100644 --- a/tests/agent/test_catalog_mcp_contract.py +++ b/tests/agent/test_catalog_mcp_contract.py @@ -27,7 +27,7 @@ run_observe run_contacts run_verify_lock run_verify run_verify_passive_suite run_verify_evidence run_video_chunk scene_observe job_cancel simulation_pause simulation_resume'''.split()) -NEW_TOOLS = frozenset({'catalog_search', 'asset_plan', 'asset_prepare', 'catalog_discover', 'scene_compile_recipe', 'asset_generate'}) +NEW_TOOLS = frozenset({'catalog_search', 'asset_plan', 'asset_prepare', 'catalog_discover', 'scene_compile_recipe', 'asset_generate', 'scene_plan_layout'}) def nullable(kind, title): @@ -154,6 +154,8 @@ async def test_tools_sources_cached_plan_and_nonblocking_search(self): 'scene_id': {'title': 'Scene Id', 'type': 'string'}}, ['scene_id'])) self.assertTrue(tools['scene_get'].annotations.readOnlyHint) self.assertFalse(tools['scene_get'].annotations.openWorldHint) + self.assertTrue(tools['scene_plan_layout'].annotations.readOnlyHint) + self.assertFalse(tools['scene_plan_layout'].annotations.openWorldHint) self.assertTrue(tools['asset_search'].annotations.readOnlyHint) self.assertTrue(tools['asset_search'].annotations.openWorldHint) self.assertEqual(tools['job_status'].inputSchema['required'], ['job_id']) diff --git a/tests/agent/test_layout_mcp.py b/tests/agent/test_layout_mcp.py new file mode 100644 index 0000000..8686235 --- /dev/null +++ b/tests/agent/test_layout_mcp.py @@ -0,0 +1,76 @@ +"""Exercise the new proposal and revision-safe edit over the actual MCP transport.""" +import asyncio +import json +import os +import sys +import tempfile +from pathlib import Path + +from mcp import ClientSession, StdioServerParameters +from mcp.client.stdio import stdio_client + + +def test_proposal_does_not_edit_until_atomic_apply(): + async def exercise(root): + bootstrap = ''' +from simscene import layout_synthesis +from simscene.mcp_server import server +def backend(request): + return {"schema":"simscene.scene_synthesizer.placements.v1", "seed":request["seed"], + "backend":{"name":"scene_synthesizer", "version":"1.15.0", "python":"3.10", + "platform":"Linux-test", "native_versions":{"geos":"3.13.1"}, + "geometry":"render-bounds box proxies; original USD not imported", + "dependency_versions":{"numpy":"2", "trimesh":"5", "python-fcl":"0.7", + "shapely":"2", "rtree":"1", "scipy":"1", "networkx":"3"}}, + "placements":[{"id":item["id"], "offset_xy":[-.3 + .6 * i, 0.]} + for i,item in enumerate(request["items"])]} +layout_synthesis._run_backend = backend +server.run(transport="stdio") +''' + env = dict(os.environ, SIMSCENE_HOME=str(root)) + server = StdioServerParameters(command=sys.executable, args=['-c', bootstrap], env=env) + async with stdio_client(server) as (reader, writer): + async with ClientSession(reader, writer) as session: + await session.initialize() + tools = {tool.name: tool for tool in (await session.list_tools()).tools} + assert tools['scene_plan_layout'].annotations.readOnlyHint + assert not (await session.call_tool('scene_open', {'scene_id': 'layout_test'})).isError + objects = { + 'bench': {'kind': 'box', 'size': [2, 1, .1], 'position': [0, 0, .5], 'collision': True}, + 'a': {'kind': 'box', 'size': [.2, .2, .2], 'position': [3, 0, 1], 'dynamic': True}, + 'b': {'kind': 'box', 'size': [.2, .2, .2], 'position': [4, 0, 1], 'dynamic': True}, + } + setup = await session.call_tool('scene_apply', { + 'scene_id': 'layout_test', 'base_revision': 0, 'request_id': 'setup', + 'operations': [{'op': 'add', 'id': key, 'object': value} for key, value in objects.items()]}) + assert not setup.isError + for field, invalid in [('seed', True), ('seed', 1.0), ('seed', '9'), + ('clearance_m', False), ('clearance_m', '0.01'), + ('gap_m', False), ('gap_m', '0.05')]: + bad = await session.call_tool('scene_plan_layout', { + 'scene_id': 'layout_test', 'ids': ['a', 'b'], 'support': 'bench', field: invalid}) + assert bad.isError, (field, invalid) + result = await session.call_tool('scene_plan_layout', { + 'scene_id': 'layout_test', 'ids': ['a', 'b'], 'support': 'bench', 'seed': 9}) + assert not result.isError + plan = result.structuredContent or json.loads(result.content[0].text) + assert plan['scene_id'] == 'layout_test' and plan['base_revision'] == 1 + assert plan['physics_tested'] is False + before_result = await session.call_tool('scene_get', {'scene_id': 'layout_test'}) + before = before_result.structuredContent or json.loads(before_result.content[0].text) + assert before['objects']['a']['position'] == [3, 0, 1] + assert before['revision'] == 1 + applied = await session.call_tool('scene_apply', { + 'scene_id': 'layout_test', 'base_revision': plan['base_revision'], + 'request_id': 'apply_layout', 'operations': plan['operations']}) + assert not applied.isError + after_result = await session.call_tool('scene_get', {'scene_id': 'layout_test'}) + after = after_result.structuredContent or json.loads(after_result.content[0].text) + assert after['objects']['a']['position'] == plan['placements'][0]['position_m'] + assert after['revision'] == 2 + stale = await session.call_tool('scene_apply', { + 'scene_id': 'layout_test', 'base_revision': plan['base_revision'], + 'request_id': 'stale_layout', 'operations': plan['operations']}) + assert stale.isError and 'revision conflict' in stale.content[0].text + with tempfile.TemporaryDirectory() as directory: + asyncio.run(exercise(Path(directory))) diff --git a/tests/agent/test_package.py b/tests/agent/test_package.py index 3351860..166b557 100644 --- a/tests/agent/test_package.py +++ b/tests/agent/test_package.py @@ -39,7 +39,8 @@ async def check_independent_metadata(root,plugin): from simscene.recipes.registry import list_recipes assert list_recipes()['recipes'] assert resources.files('simscene.generation.templates').joinpath('guide_plate_v1.py').is_file() -assert metadata.version('rosclaw-simscene')=='0.2.0.dev1' +assert metadata.version('rosclaw-simscene')=='0.2.0.dev2' +assert resources.files('simscene').joinpath('layout_synthesis_worker.py').is_file() from simscene.preparation.glb_convert import predecoder_fingerprint from simscene.preparation.profiles import PreparationError try:predecoder_fingerprint(str(root/'missing-decoder')) @@ -55,7 +56,7 @@ async def check_independent_metadata(root,plugin): async with ClientSession(reader,writer) as session: await session.initialize() names={tool.name for tool in (await session.list_tools()).tools} - self.assertTrue({'catalog_search','asset_plan','asset_prepare','catalog_discover','asset_generate','scene_compile_recipe'}<=names) + self.assertTrue({'catalog_search','asset_plan','asset_prepare','catalog_discover','asset_generate','scene_compile_recipe','scene_plan_layout'}<=names) response=await session.read_resource('simscene://catalog/sources') self.assertTrue(json.loads(response.contents[0].text)['sources']) response=await session.call_tool('catalog_search',{'query':'Original package fixture','filters':{'source_ids':['abo-glb']},'limit':1}) @@ -74,7 +75,7 @@ async def check_independent_metadata(root,plugin): members=set(archive.namelist()) for name in ('simscene/catalog/data/sources.yaml','simscene/recipes/data/recipes.json', 'simscene/preparation/data/package-lock.json','simscene/generation/templates/guide_plate_v1.py', - 'simscene/worker/isaac_run.py','simscene/preparation/worker.py'): + 'simscene/worker/isaac_run.py','simscene/preparation/worker.py', 'simscene/layout_synthesis_worker.py'): self.assertIn(name,members) self.assertFalse(any('__pycache__' in name or 'node_modules/' in name or name.endswith('.pyc') for name in members)) for kind in ('portable','claude','deepseek'): @@ -91,7 +92,7 @@ async def check_independent_metadata(root,plugin): for notice in ('LICENSE','NOTICE','OPEN_SOURCE_NOTICES.md'): self.assertTrue((plugin/notice).is_file()) self.assertEqual((plugin/notice).read_bytes(),(ROOT/notice).read_bytes()) - info=json.loads((plugin/'server/build-info.json').read_text());self.assertEqual(info['python_version'],'0.2.0.dev1');self.assertEqual(info['plugin_version'],'0.2.0-dev.1') + info=json.loads((plugin/'server/build-info.json').read_text());self.assertEqual(info['python_version'],'0.2.0.dev2');self.assertEqual(info['plugin_version'],'0.2.0-dev.2') if kind=='portable': config=json.loads((plugin/'mcp.json').read_text());self.assertEqual(config['mcpServers']['simscene']['type'],'stdio') elif kind=='claude':self.assertTrue((plugin/'.claude-plugin/plugin.json').is_file()) diff --git a/tests/test_catalog_simready_package.py b/tests/test_catalog_simready_package.py index 0d6787b..c410722 100644 --- a/tests/test_catalog_simready_package.py +++ b/tests/test_catalog_simready_package.py @@ -1,11 +1,19 @@ +import csv +from dataclasses import replace import hashlib +import io import json from types import SimpleNamespace import tempfile import unittest from unittest.mock import patch from simscene.catalog.store import CatalogStore +from simscene.catalog import AssetRecord, AssetRef, SearchRequest, load_registry +from simscene.catalog.registry import Registry +from simscene.acquisition.plans import make_plan +from simscene.catalog.search import resolve_asset,search_assets from simscene.catalog.providers.simready_package import USDCraftProvider,SimReadyPackageProvider,package_record +from test_catalog_abo import metadata_server from test_catalog_hf_manifest import source,SHA @@ -34,6 +42,168 @@ def test_usdcraft_native_projection_does_not_assert_measured_physics_or_complete self.assertEqual(record.license['license'],'Apache-2.0') with self.assertRaises(ValueError):USDCraftProvider(CatalogStore(temporary),source('other/thirdparty')) + def test_usdcraft_structure_is_explicitly_declared_and_not_a_dof_or_runtime_claim(self): + with tempfile.TemporaryDirectory() as temporary: + provider=USDCraftProvider(CatalogStore(temporary),source('nvidia/USDCraft-10K','csv','manifest.csv','usdcraft')) + row=dict(native_row(),part_count='3',joint_count='2',joint_types='prismatic|revolute',has_textures='true') + record=provider._record(row) + self.assertEqual(record.physics.get('part_count'),{'value':3,'evidence':'declared'}) + self.assertEqual(record.physics.get('joint_count'),{'value':2,'evidence':'declared'}) + self.assertEqual(record.physics.get('joint_types'),{'value':['prismatic','revolute'],'evidence':'declared'}) + self.assertEqual(record.provenance.get('has_textures'),{'value':True,'evidence':'declared'}) + self.assertEqual(record.provenance['original_metadata']['joint_types'],'prismatic|revolute') + self.assertEqual(provider._record(native_row()).provenance.get('has_textures'),{'value':False,'evidence':'declared'}) + self.assertNotIn('dof_count',record.physics) + self.assertFalse(record.has_capability('openable')) + self.assertFalse(record.has_capability('runtime_verified')) + + def test_usdcraft_joint_type_capabilities_are_conservative_for_inconsistent_rows(self): + cases=( + ('revolute','1','articulated',True,False,True), + ('continuous','1','articulated',True,False,True), + ('prismatic','1','articulated',False,True,True), + ('prismatic|revolute','2','articulated',True,True,False), + ('continuous|prismatic|revolute','3','articulated',True,True,False), + ('','0','static_rigid',False,False,False), + ('mystery','1','articulated',None,None,None), + ('revolute|mystery','2','articulated',None,None,None), + ('revolute|','2','articulated',None,None,None), + ('revolute|revolute','2','articulated',None,None,None), + ('prismatic|revolute','1','articulated',None,None,None), + ('','1','articulated',None,None,None), + ('','2','static_rigid',None,None,None), + ('revolute','1','static_rigid',None,None,None), + ) + with tempfile.TemporaryDirectory() as temporary: + provider=USDCraftProvider(CatalogStore(temporary),source('nvidia/USDCraft-10K','csv','manifest.csv','usdcraft')) + for joint_types,count,physics_type,rotational,translational,single in cases: + with self.subTest(joint_types=joint_types,count=count,physics_type=physics_type): + row=dict(native_row(),joint_types=joint_types,joint_count=count,physics_type=physics_type) + record=provider._record(row) + for name,value in (('declared_rotational_joint',rotational),('declared_translational_joint',translational),('declared_single_joint',single)): + self.assertEqual(record.capabilities.get(name),{'value':value,'evidence':'unknown' if value is None else 'declared'}) + + def test_contradictory_physics_type_does_not_claim_articulation_status(self): + with tempfile.TemporaryDirectory() as temporary: + provider=USDCraftProvider(CatalogStore(temporary),source('nvidia/USDCraft-10K','csv','manifest.csv','usdcraft')) + for row in (dict(native_row(),physics_type='static_rigid',joint_count='1',joint_types='revolute'), + dict(native_row(),physics_type='articulated',joint_count='0',joint_types='')): + record=provider._record(row) + self.assertEqual(record.capabilities['articulated'],{'value':None,'evidence':'unknown'}) + self.assertEqual(record.provenance['original_metadata']['physics_type'],row['physics_type']) + + def test_old_structural_projection_is_refreshed_before_new_articulation_semantics(self): + row=dict(native_row(),physics_type='static_rigid',joint_count='1',joint_types='revolute') + output=io.StringIO(newline='');writer=csv.DictWriter(output,fieldnames=list(row));writer.writeheader();writer.writerow(row) + payload=output.getvalue().encode() + selected=load_registry().get('usdcraft');revision=selected.metadata_entries[0].revision + path=f'/datasets/nvidia/USDCraft-10K/resolve/{revision}/manifest.csv' + with tempfile.TemporaryDirectory() as directory, metadata_server({path:{'payload':payload}}) as (url,trace): + store=CatalogStore(directory);provider=USDCraftProvider(store,selected,base_url=url) + old=provider._record(row) + old.capabilities['articulated']={'value':False,'evidence':'declared'} + old_snapshot=revision+':'+('a'*64)+':usdcraft-structure-v1' + store.replace_index('usdcraft',[old],old_snapshot) + self.assertEqual(provider.snapshot,'index_not_refreshed') + with self.assertRaisesRegex(ValueError, 'stale'): + resolve_asset(old.ref,index_directory=directory) + with self.assertRaisesRegex(ValueError, 'stale'): + provider.resolve(old.ref) + refreshed=provider.refresh() + self.assertTrue(refreshed['snapshot'].endswith(':usdcraft-structure-v2')) + self.assertNotEqual(refreshed['snapshot'],old_snapshot) + self.assertEqual(store.get(old.ref).capabilities['articulated'],{'value':None,'evidence':'unknown'}) + self.assertEqual(resolve_asset(old.ref,index_directory=directory).capabilities['articulated'],{'value':None,'evidence':'unknown'}) + self.assertEqual(provider.resolve(old.ref).capabilities['articulated'],{'value':None,'evidence':'unknown'}) + # A still-running old process can overwrite a single row after the + # new snapshot commit. New reads must not trust its projection. + store.remember(old) + self.assertEqual(resolve_asset(old.ref,index_directory=directory).capabilities['articulated'],{'value':None,'evidence':'unknown'}) + page=provider.search(SearchRequest('cabinet',source_ids=('usdcraft',),limit=8)) + self.assertEqual(page.items[0].capabilities['articulated'],{'value':None,'evidence':'unknown'}) + self.assertEqual([entry['path'] for entry in trace],[path]) + + def test_usdcraft_custom_source_id_and_revision_use_configured_projection(self): + original=load_registry().get('usdcraft') + custom=replace(original,source_id='usdcraft-alias',metadata_entries=(replace(original.metadata_entries[0],revision='d'*40),)) + registry=Registry((custom,)) + with tempfile.TemporaryDirectory() as directory: + store=CatalogStore(directory);provider=USDCraftProvider(store,custom) + row=dict(native_row(),physics_type='static_rigid',joint_count='1',joint_types='revolute') + record=provider._record(row) + record.capabilities['articulated']={'value':False,'evidence':'declared'} + store.replace_index(custom.source_id,[record],provider.snapshot_identity(b'pinned-index')) + with patch('simscene.catalog.search.load_registry',return_value=registry): + resolved=resolve_asset(record.ref,index_directory=directory) + self.assertEqual(resolved.ref.revision,'d'*40) + self.assertEqual(resolved.capabilities['articulated'],{'value':None,'evidence':'unknown'}) + + def test_plan_uses_explicit_custom_registry_and_mixed_revisions_fail_closed(self): + from pathlib import Path + from test_asset_plans import config_fixture,runtime_fixture + original=load_registry().get('usdcraft') + source_d=replace(original,source_id='usdcraft-alias',metadata_entries=(replace(original.metadata_entries[0],revision='d'*40),)) + source_e=replace(source_d,metadata_entries=(replace(source_d.metadata_entries[0],revision='e'*40),)) + with tempfile.TemporaryDirectory() as directory: + store=CatalogStore(Path(directory)/'index') + old=USDCraftProvider(store,source_d);new=USDCraftProvider(store,source_e) + old_record=old._record(native_row());new_record=new._record(native_row()) + store.replace_index(source_e.source_id,[new_record],new.snapshot_identity(b'new-revision')) + store.remember(old_record) # an older process completed after the new commit + self.assertEqual(old.snapshot,'index_not_refreshed') + with self.assertRaisesRegex(ValueError,'stale'): + old.resolve(old_record.ref) + page=new.search(SearchRequest('cabinet',source_ids=(source_e.source_id,),limit=8)) + self.assertEqual([record.ref.revision for record in page.items],['e'*40]) + store.fts=False + fallback=new.search(SearchRequest('cabinet',source_ids=(source_e.source_id,),limit=8)) + self.assertEqual([record.ref.revision for record in fallback.items],['e'*40]) + registry_path=Path(directory)/'registry.json' + registry_path.write_text(json.dumps(Registry((source_e,)).to_dict())) + config=config_fixture(directory);config['registry_path']=str(registry_path) + plan=make_plan(new_record.ref,runtime=runtime_fixture(),config=config) + self.assertEqual(plan['asset_ref']['revision'],'e'*40) + + def test_usdcraft_filtered_search_refreshes_stale_projection_using_only_manifest(self): + rows=[dict(native_row(),object_id='hinge',joint_types='revolute'), + dict(native_row(),object_id='slider',joint_types='prismatic'), + dict(native_row(),object_id='mixed',joint_count='2',joint_types='prismatic|revolute'), + dict(native_row(),object_id='continuous',joint_types='continuous'), + dict(native_row(),object_id='unknown',joint_types='revolute|mystery',joint_count='2'), + dict(native_row(),object_id='static',physics_type='static_rigid',joint_types='revolute')] + output=io.StringIO(newline='');writer=csv.DictWriter(output,fieldnames=list(rows[0]));writer.writeheader();writer.writerows(rows) + payload=output.getvalue().encode() + selected=load_registry().get('usdcraft');revision=selected.metadata_entries[0].revision + index_path=f'/datasets/nvidia/USDCraft-10K/resolve/{revision}/manifest.csv' + with tempfile.TemporaryDirectory() as directory, metadata_server({index_path:{'payload':payload}}) as (url,trace): + store=CatalogStore(directory) + old=AssetRecord(AssetRef('usdcraft','hinge',revision),'Original hinged cabinet', + physics={'joint_count':{'value':1,'evidence':'declared'}}, + capabilities={'articulated':{'value':True,'evidence':'declared'}}) + store.replace_index('usdcraft',[old],revision+':'+('a'*64)) + provider=USDCraftProvider(store,selected,base_url=url) + request=SearchRequest('cabinet',source_ids=('usdcraft',),required_capabilities=('declared_rotational_joint',), + allow_unknown_constraints=True,limit=20) + page=search_assets(request,providers={'usdcraft':provider},index_directory=directory) + self.assertEqual(page.status,'ok') + self.assertEqual({item['ref']['asset_id'] for item in page.items},{'hinge','mixed','continuous'}) + self.assertEqual(page.budgets['metadata_bytes'],len(payload)) + self.assertEqual(page.budgets['model_bytes'],0) + self.assertLessEqual(len(json.dumps(page.to_dict()).encode()),12*1024) + detail_path=next(item['detail_ref'] for item in page.items if item['ref']['asset_id']=='hinge') + with open(detail_path,encoding='utf8') as stream: detail=json.load(stream) + self.assertEqual(detail['physics']['joint_types'],{'value':['revolute'],'evidence':'declared'}) + self.assertEqual(detail['provenance']['has_textures'],{'value':False,'evidence':'declared'}) + request=SearchRequest('cabinet',source_ids=('usdcraft',),required_capabilities=('declared_translational_joint',),limit=20) + warm=search_assets(request,providers={'usdcraft':provider},index_directory=directory) + self.assertEqual({item['ref']['asset_id'] for item in warm.items},{'slider','mixed'}) + self.assertEqual(warm.budgets['metadata_bytes'],0) + request=SearchRequest('cabinet',source_ids=('usdcraft',),required_capabilities=('declared_rotational_joint','declared_single_joint'),limit=20) + single=search_assets(request,providers={'usdcraft':provider},index_directory=directory) + self.assertEqual({item['ref']['asset_id'] for item in single.items},{'hinge','continuous'}) + self.assertEqual(single.budgets['metadata_bytes'],0) + self.assertEqual([entry['path'] for entry in trace],[index_path]) + def test_individual_package_license_hash_inventory_and_metadata_gaps(self): src=source('projectsim/simready-assets','json','valve/com.nvidia.simready.packaging.json','projectsim') descriptor,bom,raw,bom_raw=package();record=package_record(src,src.metadata_entries[0].path,descriptor,bom,packaging_bytes=raw,bom_bytes=bom_raw) diff --git a/tests/test_layout_synthesis.py b/tests/test_layout_synthesis.py new file mode 100644 index 0000000..3aab45a --- /dev/null +++ b/tests/test_layout_synthesis.py @@ -0,0 +1,326 @@ +"""The optional layout backend proposes checked, editable scene operations.""" +import copy +import hashlib +import json +import math +import os +import subprocess +import sys +from unittest.mock import patch + +import pytest + +from simscene.layout_synthesis import plan_layout +from simscene.placement import bounds +from simscene.scene import SceneError + + +def scene(): + q = math.sqrt(0.5) + return {'revision': 7, 'objects': { + 'bench': {'kind': 'box', 'size': [2.0, 1.0, 1.0], 'position': [1.0, 2.0, .5], 'collision': True, + 'orientation_wxyz': [q, 0, 0, q]}, + 'cup': {'kind': 'box', 'size': [.2, .2, .1], 'position': [4., 4., 4.], + 'orientation_wxyz': [1, 0, 0, 0], 'dynamic': True}, + 'box': {'kind': 'box', 'size': [.2, .2, .2], 'position': [5., 5., 5.], 'dynamic': True}, + }} + + +def response(positions, seed=9): + return {'schema': 'simscene.scene_synthesizer.placements.v1', 'seed': seed, + 'backend': {'name': 'scene_synthesizer', 'version': '1.15.0', 'python': '3.10.12', + 'platform': 'Linux-test', 'native_versions': {'geos': '3.13.1'}, + 'geometry': 'render-bounds box proxies; original USD not imported', + 'dependency_versions': {'numpy': '2.2.6', 'trimesh': '5.2.1', + 'python-fcl': '0.7.0', 'shapely': '2.1.2', 'rtree': '1.4.1', + 'scipy': '1.15.3', 'networkx': '3.4.2'}}, + 'placements': [{'id': name, 'offset_xy': offset} for name, offset in positions]} + + +def test_rotated_support_plan_is_editable_and_does_not_modify_scene(): + original = scene() + before = copy.deepcopy(original) + with patch('simscene.layout_synthesis._run_backend', return_value=response([ + ('cup', [-.4, 0]), ('box', [.4, 0])])): + plan = plan_layout(original, ['cup', 'box'], 'bench', seed=9, clearance_m=.03) + assert original == before + assert plan['base_revision'] == 7 and plan['physics_tested'] is False + assert [op['op'] for op in plan['operations']] == ['place_on', 'place_on'] + assert plan['placements'][0]['support_id'] == 'bench' + assert plan['placements'][0]['position_m'] == pytest.approx([1., 1.6, 1.05]) + assert plan['placements'][0]['orientation_wxyz'] == [1, 0, 0, 0] + assert plan['placements'][1]['position_m'] == pytest.approx([1., 2.4, 1.1]) + assert 'cup' in plan['operations'][1]['avoid_ids'] + + +def test_plan_identity_binds_source_and_scene_context(): + original = scene() + other_source = copy.deepcopy(original) + other_source['objects']['cup']['mass_kg'] = .5 + shifted_support = copy.deepcopy(original) + shifted_support['objects']['bench']['position'][0] += 3 + other_scene = copy.deepcopy(original) + other_scene['scene_id'] = 'other_scene' + response_data = response([('cup', [-.4, 0]), ('box', [.4, 0])]) + with patch('simscene.layout_synthesis._run_backend', return_value=response_data): + first = plan_layout(original, ['cup', 'box'], 'bench', seed=9) + again = plan_layout(copy.deepcopy(original), ['cup', 'box'], 'bench', seed=9) + other = plan_layout(other_source, ['cup', 'box'], 'bench', seed=9) + shifted = plan_layout(shifted_support, ['cup', 'box'], 'bench', seed=9) + renamed = plan_layout(other_scene, ['cup', 'box'], 'bench', seed=9) + gap = plan_layout(original, ['cup', 'box'], 'bench', seed=9, gap_m=.001) + assert first['plan_sha256'] == again['plan_sha256'] + assert len({p['plan_sha256'] for p in (first, other, shifted, renamed, gap)}) == 5 + + +def test_collision_and_reserved_space_are_rechecked_even_if_backend_claims_success(): + original = scene() + with patch('simscene.layout_synthesis._run_backend', return_value=response([ + ('cup', [0., 0.]), ('box', [0., 0.])])): + with pytest.raises(SceneError, match='clearance'): + plan_layout(original, ['cup', 'box'], 'bench', seed=9) + with patch('simscene.layout_synthesis._run_backend', return_value=response([ + ('cup', [0., 0.]), ('box', [.4, 0.])])): + with pytest.raises(SceneError, match='reserved'): + plan_layout(original, ['cup', 'box'], 'bench', seed=9, + keepout_bounds=[{'min': [.8, 1.8, .95], 'max': [1.2, 2.2, 1.3]}]) + assert original == scene() + + +@pytest.mark.parametrize('output', [ + response([('cup', [0, 0])]), + response([('cup', [0, 0]), ('cup', [.5, 0])]), + response([('cup', [float('nan'), 0]), ('box', [.5, 0])]), + response([('cup', [2., 0]), ('box', [.5, 0])]), + response([('cup', [0, 0]), ('box', [.5, 0])], seed=10), +]) +def test_untrusted_backend_output_fails_closed(output): + with patch('simscene.layout_synthesis._run_backend', return_value=output): + with pytest.raises(SceneError): + plan_layout(scene(), ['cup', 'box'], 'bench', seed=9) + + +@pytest.mark.parametrize('ids, support, seed', [ + ([], 'bench', 9), (['cup', 'cup'], 'bench', 9), (['cup', 'missing'], 'bench', 9), + (['cup'], 'cup', 9), (['cup'], 'bench', -1), (['cup'], 'bench', True), +]) +def test_invalid_request_never_runs_backend(ids, support, seed): + with patch('simscene.layout_synthesis._run_backend') as backend: + with pytest.raises(SceneError): + plan_layout(scene(), ids, support, seed=seed) + backend.assert_not_called() + + +def test_tilted_support_and_unavailable_runtime_are_reported(): + original = scene() + original['objects']['bench']['orientation_wxyz'] = [math.sqrt(.5), math.sqrt(.5), 0, 0] + with patch('simscene.layout_synthesis._run_backend') as backend: + with pytest.raises(SceneError, match='horizontal'): + plan_layout(original, ['cup'], 'bench', seed=9) + backend.assert_not_called() + with patch('simscene.layout_synthesis._run_backend', side_effect=SceneError('backend unavailable')): + with pytest.raises(SceneError, match='backend unavailable'): + plan_layout(scene(), ['cup'], 'bench', seed=9) + + +@pytest.mark.parametrize('target', ['stdout', 'stderr']) +def test_worker_output_is_capped_while_it_is_running(target): + from simscene.layout_synthesis import _bounded_process + command = [sys.executable, '-c', + 'import os,time; os.write(' + ('1' if target == 'stdout' else '2') + ', b"x"*100000); time.sleep(2)'] + with pytest.raises(SceneError, match='output exceeds limit'): + _bounded_process(command, b'{}', timeout=3, limit=1024) + + +def test_bounded_worker_receives_complete_large_input(): + from simscene.layout_synthesis import _bounded_process + payload = b'x' * 200_000 + code, stdout, stderr = _bounded_process([sys.executable, '-c', + 'import sys; print(len(sys.stdin.buffer.read()))'], payload, timeout=3) + assert code == 0 and int(stdout) == len(payload) and not stderr + + +@pytest.mark.skipif(not hasattr(os, 'fork'), reason='requires POSIX process groups') +def test_worker_descendant_cannot_hold_output_pipes_past_deadline(): + from simscene.layout_synthesis import _bounded_process + command = [sys.executable, '-c', + 'import os,time; pid=os.fork()\n' + 'if pid: print("{}", flush=True); os._exit(0)\n' + 'time.sleep(2); os.write(1, b"trailing")'] + with pytest.raises(subprocess.TimeoutExpired): + _bounded_process(command, b'{}', timeout=.25) + + +def prepared_package(tmp_path, *, support=False, native_dynamic=False): + from pxr import Gf, Usd, UsdGeom, UsdPhysics + tmp_path.mkdir() + asset = tmp_path / 'main.usda' + stage = Usd.Stage.CreateNew(str(asset)) + UsdGeom.SetStageMetersPerUnit(stage, 1.) + UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z) + root = UsdGeom.Xform.Define(stage, '/Asset') + stage.SetDefaultPrim(root.GetPrim()) + cube = UsdGeom.Cube.Define(stage, '/Asset/Part') + cube.CreateSizeAttr(.2) + cube.AddTranslateOp().Set(Gf.Vec3d(.3, 0, .1)) + if support: + UsdPhysics.CollisionAPI.Apply(cube.GetPrim()).CreateCollisionEnabledAttr(True) + if native_dynamic: + UsdPhysics.RigidBodyAPI.Apply(root.GetPrim()) + stage.GetRootLayer().Save() + manifest = {'schema': 'simscene.prepared_asset.v1', 'schema_version': 1, + 'main': 'main.usda', 'default_prim': '/Asset', + 'profile_id': 'static_fixture_v1' if support else 'visual_prop_v1', + 'files': [{'path': 'main.usda', 'sha256': hashlib.sha256(asset.read_bytes()).hexdigest(), + 'size_bytes': asset.stat().st_size}], + 'body_map': {'main': {'role': 'static', 'relative_prim_path': 'Part', + 'collider_relative_prim_paths': ['Part']}} if support else {}} + manifest_path = tmp_path / 'manifest.json' + manifest_path.write_text(json.dumps(manifest)) + binding = {'manifest_path': str(manifest_path), 'manifest_sha256': hashlib.sha256(manifest_path.read_bytes()).hexdigest()} + return {'kind': 'asset', 'asset_path': str(asset), 'asset_binding': binding, 'position': [4., 4., 4.]} + + +def test_imported_usd_root_offset_is_preserved(tmp_path): + prepared = prepared_package(tmp_path / 'offset') + asset = tmp_path / 'offset' / 'main.usda' + original = scene() + original['objects']['cup'] = prepared + before = asset.read_bytes() + with patch('simscene.layout_synthesis._run_backend', return_value=response([('cup', [0., 0.])])): + plan = plan_layout(original, ['cup'], 'bench', seed=9) + placed = copy.deepcopy(original) + placed['objects']['cup']['position'] = plan['placements'][0]['position_m'] + box = bounds(placed['objects']['cup'], placed, 'cup') + assert [(box['min'][i] + box['max'][i]) / 2 for i in (0, 1)] == pytest.approx([1., 2.]) + assert box['min'][2] == pytest.approx(1.) + assert placed['objects']['cup']['asset_path'] == str(asset) and asset.read_bytes() == before + assert plan['source_pins'] == [{'id': 'cup', 'status': 'verified_prepared', + 'manifest_sha256': prepared['asset_binding']['manifest_sha256'], + 'profile_id': 'visual_prop_v1'}] + + +def test_assets_require_verified_local_preparation_and_support_physics(tmp_path): + original = scene() + for missing_object in ('cup', 'bench'): + candidate = copy.deepcopy(original) + candidate['objects'][missing_object] = {'kind': 'asset', 'asset_path': '/missing.usda', + 'position': [0., 0., 0.], 'support_surfaces': {'top': {'min_xy': [-1, -1], 'max_xy': [1, 1], 'z_m': .5}}} + with patch('simscene.layout_synthesis._run_backend') as backend: + with pytest.raises(SceneError, match='prepared'): + plan_layout(candidate, ['cup'], 'bench', support_surface='top' if missing_object == 'bench' else None, seed=9) + backend.assert_not_called() + candidate = scene() + candidate['objects']['bench'] = prepared_package(tmp_path / 'bad_support', support=True, native_dynamic=True) + candidate['objects']['bench']['support_surfaces'] = {'top': {'min_xy': [-1, -1], 'max_xy': [1, 1], 'z_m': .5}} + with patch('simscene.layout_synthesis._run_backend') as backend: + with pytest.raises(SceneError, match='dynamic or articulated physics'): + plan_layout(candidate, ['cup'], 'bench', support_surface='top', seed=9) + backend.assert_not_called() + + +def test_instanced_imported_support_is_rejected_before_hidden_physics_can_be_missed(tmp_path): + from pxr import Usd, UsdGeom, UsdPhysics + package = tmp_path / 'instanced' + prepared = prepared_package(package, support=True) + prototype_path = package / 'prototype.usda' + prototype = Usd.Stage.CreateNew(str(prototype_path)) + root = UsdGeom.Xform.Define(prototype, '/Template') + prototype.SetDefaultPrim(root.GetPrim()) + moving = UsdGeom.Xform.Define(prototype, '/Template/Moving') + UsdPhysics.RigidBodyAPI.Apply(moving.GetPrim()) + UsdPhysics.CollisionAPI.Apply(UsdGeom.Cube.Define(prototype, '/Template/Moving/Shape').GetPrim()) + prototype.GetRootLayer().Save() + asset_path = package / 'main.usda' + stage = Usd.Stage.Open(str(asset_path)) + instance = UsdGeom.Xform.Define(stage, '/Asset/Inst').GetPrim() + instance.GetReferences().AddReference('./prototype.usda', '/Template') + instance.SetInstanceable(True) + stage.GetRootLayer().Save() + manifest_path = package / 'manifest.json' + manifest = json.loads(manifest_path.read_text()) + manifest['files'] = [{'path': p.name, 'sha256': hashlib.sha256(p.read_bytes()).hexdigest(), + 'size_bytes': p.stat().st_size} for p in (asset_path, prototype_path)] + manifest_path.write_text(json.dumps(manifest)) + prepared['asset_binding']['manifest_sha256'] = hashlib.sha256(manifest_path.read_bytes()).hexdigest() + prepared['support_surfaces'] = {'top': {'min_xy': [-1, -1], 'max_xy': [1, 1], 'z_m': .5}} + original = scene() + original['objects']['bench'] = prepared + with patch('simscene.layout_synthesis._run_backend') as backend: + with pytest.raises(SceneError, match='instanc'): + plan_layout(original, ['cup'], 'bench', support_surface='top', seed=9) + backend.assert_not_called() + + +def test_dynamic_props_require_a_colliding_support(): + original = scene() + original['objects']['bench']['collision'] = False + with patch('simscene.layout_synthesis._run_backend') as backend: + with pytest.raises(SceneError, match='collision'): + plan_layout(original, ['cup'], 'bench', seed=9) + backend.assert_not_called() + + +@pytest.mark.parametrize('mutation', ['support_excludes', 'item_excludes', 'item_no_collider', 'compound_without_colliders']) +def test_declared_support_contacts_cannot_be_disabled(mutation): + original = scene() + if mutation == 'support_excludes': + original['objects']['bench']['collision_exclusions'] = ['cup'] + elif mutation == 'item_excludes': + original['objects']['cup']['collision_exclusions'] = ['bench'] + elif mutation == 'item_no_collider': + original['objects']['cup']['collision'] = False + else: + original['objects']['bench'] = {'kind': 'compound', 'collision': True, 'position': [0, 0, .5], + 'parts': [{'kind': 'box', 'size': [2, 1, 1], 'collision': False}], + 'support_surfaces': {'top': {'min_xy': [-1, -.5], 'max_xy': [1, .5], 'z_m': .5}}} + with patch('simscene.layout_synthesis._run_backend') as backend: + with pytest.raises(SceneError, match='collis'): + plan_layout(original, ['cup'], 'bench', support_surface='top' if mutation == 'compound_without_colliders' else None, seed=9) + backend.assert_not_called() + + +def test_compounds_with_attached_visuals_are_rejected_before_loading_sources(): + original = scene() + original['objects']['cup'] = {'kind': 'compound', 'position': [0, 0, 1], 'parts': []} + original['objects']['attached'] = {'kind': 'asset', 'asset_path': '/missing.usda', + 'rigid_attachment': {'body': 'cup'}, 'asset_physics': 'visual_only'} + with patch('simscene.layout_synthesis._run_backend') as backend: + with pytest.raises(SceneError, match='attached visuals'): + plan_layout(original, ['cup'], 'bench', seed=9) + backend.assert_not_called() + + +def test_changed_prepared_source_and_partial_backend_provenance_fail_closed(tmp_path): + original = scene() + original['objects']['cup'] = prepared_package(tmp_path / 'prop') + result = response([('cup', [0., 0.])]) + with patch('simscene.layout_synthesis._run_backend', return_value=result): + plan_layout(original, ['cup'], 'bench', seed=9) + with open(original['objects']['cup']['asset_path'], 'a') as stream: + stream.write('\n# changed without changing geometry\n') + with patch('simscene.layout_synthesis._run_backend') as backend: + with pytest.raises(SceneError, match='missing or changed'): + plan_layout(original, ['cup'], 'bench', seed=9) + backend.assert_not_called() + incomplete = response([('cup', [0., 0.])]) + del incomplete['backend']['dependency_versions'] + with patch('simscene.layout_synthesis._run_backend', return_value=incomplete): + with pytest.raises(SceneError, match='invalid response'): + plan_layout(scene(), ['cup'], 'bench', seed=9) + + +@pytest.mark.skipif(not os.environ.get('SIMSCENE_LAYOUT_PYTHON'), reason='optional pinned layout backend not configured') +def test_real_backend_is_repeatable_across_processes_and_rejects_impossible_layout(): + original = scene() + first = plan_layout(original, ['cup', 'box'], 'bench', seed=100) + again = plan_layout(original, ['cup', 'box'], 'bench', seed=100) + different = plan_layout(original, ['cup', 'box'], 'bench', seed=101) + assert first == again + assert first['placements'] != different['placements'] + assert first['backend']['version'] == '1.15.0' + original['objects']['bench']['size'] = [.1, .1, 1.] + before = copy.deepcopy(original) + with pytest.raises(SceneError, match='no valid proxy placement'): + plan_layout(original, ['cup'], 'bench', seed=100) + assert original == before diff --git a/tests/test_packaging_contract.py b/tests/test_packaging_contract.py index dc7bffd..df38651 100644 --- a/tests/test_packaging_contract.py +++ b/tests/test_packaging_contract.py @@ -10,7 +10,7 @@ class PackagingContractTests(unittest.TestCase): def test_version_mapping_has_one_project_source(self): - self.assertEqual((PYTHON_VERSION,PACKAGE_VERSION),('0.2.0.dev1','0.2.0-dev.1')) + self.assertEqual((PYTHON_VERSION,PACKAGE_VERSION),('0.2.0.dev2','0.2.0-dev.2')) with tempfile.TemporaryDirectory() as temporary: root=Path(temporary) for python,plugin in [('0.3.0.dev12','0.3.0-dev.12'),('0.3.0','0.3.0')]: From 59f7285787cd2b25fd9df1eaae7b49b91e158e1a Mon Sep 17 00:00:00 2001 From: shaoxiang <519517384@qq.com> Date: Mon, 16 Nov 2026 19:33:50 +0800 Subject: [PATCH 02/20] Add articulated asset and generator workflows --- README.md | 16 +- docs/asset-catalog.md | 57 ++ docs/assets/SOURCES.md | 7 +- docs/usdcraft-sdk.md | 124 ++++ docs/validation/catalog-capabilities.md | 14 +- examples/artvip_door/README.md | 70 ++ examples/artvip_door/assets.lock.json | 193 +++++ examples/artvip_door/case.json | 39 + examples/artvip_door/check.py | 81 +++ examples/artvip_door/recipe.json | 178 +++++ examples/artvip_door/supplement.json | 19 + examples/usdcraft_sdk_guide/README.md | 67 ++ examples/usdcraft_sdk_guide/assets.lock.json | 237 +++++++ examples/usdcraft_sdk_guide/case.json | 52 ++ examples/usdcraft_sdk_guide/check_pair.py | 165 +++++ examples/usdcraft_sdk_guide/recipe-long.json | 176 +++++ examples/usdcraft_sdk_guide/recipe-short.json | 176 +++++ examples/usdcraft_two_drawer/README.md | 71 ++ examples/usdcraft_two_drawer/assets.lock.json | 116 +++ examples/usdcraft_two_drawer/case.json | 87 +++ .../usdcraft_two_drawer/recipe-control.json | 152 ++++ examples/usdcraft_two_drawer/recipe.json | 164 +++++ experiments/acquire_recipe_assets.py | 38 +- experiments/mobilitygen_jetbot/README.md | 140 ++++ .../mobilitygen_jetbot/asset-lock.json | 57 ++ experiments/mobilitygen_jetbot/asset_lock.py | 90 +++ .../mobilitygen_jetbot/audit_output.py | 103 +++ experiments/mobilitygen_jetbot/evaluate.py | 194 +++++ .../mobilitygen_jetbot/evidence_lock.py | 64 ++ .../mobilitygen_jetbot/fetch_assets.py | 105 +++ .../mobilitygen_jetbot/fixed_case.json | 41 ++ experiments/mobilitygen_jetbot/pair_check.py | 152 ++++ experiments/mobilitygen_jetbot/run_pair.py | 140 ++++ .../mobilitygen_jetbot/runtime-lock.json | 19 + .../mobilitygen_jetbot/test_contract.py | 69 ++ .../mobilitygen_jetbot/test_evaluate.py | 63 ++ experiments/mobilitygen_jetbot/test_fetch.py | 49 ++ .../mobilitygen_jetbot/test_new_guards.py | 50 ++ experiments/mobilitygen_jetbot/test_pair.py | 60 ++ .../mobilitygen_jetbot/test_reaudit.py | 28 + .../mobilitygen_jetbot/test_redirect.py | 64 ++ .../test_review_regressions.py | 206 ++++++ experiments/mobilitygen_jetbot/test_sixty.py | 48 ++ experiments/mobilitygen_jetbot/tool-lock.json | 17 + experiments/mobilitygen_jetbot/worker.py | 393 +++++++++++ plugins/build.py | 21 +- .../build-scene/references/native-assets.md | 32 +- skills/build-scene/references/recipes.md | 23 +- src/simscene/acquisition/dispatch.py | 14 +- src/simscene/acquisition/plans.py | 2 +- src/simscene/catalog/audit.py | 4 +- src/simscene/catalog/config.py | 4 +- src/simscene/catalog/data/sources.yaml | 33 + src/simscene/catalog/providers/artvip.py | 153 ++++ src/simscene/catalog/providers/factory.py | 3 + src/simscene/catalog/registry.py | 6 +- src/simscene/catalog/search.py | 5 + src/simscene/cli.py | 19 +- src/simscene/generation/jobs.py | 131 +++- .../templates/usdcraft_sdk_guide_plate_v1.py | 40 ++ .../generation/usdcraft_backend_worker.py | 237 +++++++ src/simscene/generation/usdcraft_sdk.py | 229 ++++++ src/simscene/generation/worker.py | 18 +- src/simscene/jobs.py | 4 +- src/simscene/mcp_server.py | 4 +- src/simscene/physics_binding.py | 106 ++- src/simscene/preparation/articulation.py | 124 +++- src/simscene/preparation/articulation_v2.py | 420 +++++++++++ src/simscene/preparation/contracts.py | 19 +- src/simscene/preparation/native_repairs.py | 284 ++++++++ src/simscene/preparation/profiles.py | 21 +- src/simscene/preparation/usd_layers.py | 41 +- src/simscene/recipes/io.py | 24 +- src/simscene/scene.py | 28 +- src/simscene/usd_export.py | 6 +- .../articulated_asset_two_joint.py | 513 ++++++++++++++ .../articulated_asset_two_joint_pair.py | 229 ++++++ src/simscene/verification/case_runner.py | 11 +- src/simscene/worker/initial_state.py | 10 +- src/simscene/worker/isaac_run.py | 4 +- src/simscene/worker/mechanism.py | 176 ++++- src/simscene/worker/mechanism_v2.py | 242 +++++++ tests/agent/test_package.py | 19 +- tests/test_articulated_asset_two_joint.py | 473 +++++++++++++ .../test_articulated_asset_two_joint_pair.py | 179 +++++ tests/test_articulation_v2.py | 323 +++++++++ tests/test_catalog_artvip.py | 225 ++++++ tests/test_catalog_audit.py | 3 +- tests/test_catalog_registry.py | 3 +- tests/test_generation_reconnect_runtime.py | 112 +++ tests/test_jobs.py | 11 + tests/test_mechanism_two_dof.py | 667 ++++++++++++++++++ tests/test_native_repairs.py | 391 ++++++++++ tests/test_preparation_articulation.py | 16 +- tests/test_preparation_articulation_v2.py | 118 ++++ tests/test_recipe_io.py | 76 ++ tests/test_two_joint_dispatch.py | 30 + tests/test_usdcraft_sdk_example.py | 59 ++ tests/test_usdcraft_sdk_generation.py | 201 ++++++ tests/test_usdcraft_sdk_hardening.py | 146 ++++ tests/test_usdcraft_two_drawer_example.py | 32 + 101 files changed, 10633 insertions(+), 142 deletions(-) create mode 100644 docs/usdcraft-sdk.md create mode 100644 examples/artvip_door/README.md create mode 100644 examples/artvip_door/assets.lock.json create mode 100644 examples/artvip_door/case.json create mode 100644 examples/artvip_door/check.py create mode 100644 examples/artvip_door/recipe.json create mode 100644 examples/artvip_door/supplement.json create mode 100644 examples/usdcraft_sdk_guide/README.md create mode 100644 examples/usdcraft_sdk_guide/assets.lock.json create mode 100644 examples/usdcraft_sdk_guide/case.json create mode 100644 examples/usdcraft_sdk_guide/check_pair.py create mode 100644 examples/usdcraft_sdk_guide/recipe-long.json create mode 100644 examples/usdcraft_sdk_guide/recipe-short.json create mode 100644 examples/usdcraft_two_drawer/README.md create mode 100644 examples/usdcraft_two_drawer/assets.lock.json create mode 100644 examples/usdcraft_two_drawer/case.json create mode 100644 examples/usdcraft_two_drawer/recipe-control.json create mode 100644 examples/usdcraft_two_drawer/recipe.json create mode 100644 experiments/mobilitygen_jetbot/README.md create mode 100644 experiments/mobilitygen_jetbot/asset-lock.json create mode 100644 experiments/mobilitygen_jetbot/asset_lock.py create mode 100644 experiments/mobilitygen_jetbot/audit_output.py create mode 100644 experiments/mobilitygen_jetbot/evaluate.py create mode 100644 experiments/mobilitygen_jetbot/evidence_lock.py create mode 100644 experiments/mobilitygen_jetbot/fetch_assets.py create mode 100644 experiments/mobilitygen_jetbot/fixed_case.json create mode 100644 experiments/mobilitygen_jetbot/pair_check.py create mode 100644 experiments/mobilitygen_jetbot/run_pair.py create mode 100644 experiments/mobilitygen_jetbot/runtime-lock.json create mode 100644 experiments/mobilitygen_jetbot/test_contract.py create mode 100644 experiments/mobilitygen_jetbot/test_evaluate.py create mode 100644 experiments/mobilitygen_jetbot/test_fetch.py create mode 100644 experiments/mobilitygen_jetbot/test_new_guards.py create mode 100644 experiments/mobilitygen_jetbot/test_pair.py create mode 100644 experiments/mobilitygen_jetbot/test_reaudit.py create mode 100644 experiments/mobilitygen_jetbot/test_redirect.py create mode 100644 experiments/mobilitygen_jetbot/test_review_regressions.py create mode 100644 experiments/mobilitygen_jetbot/test_sixty.py create mode 100644 experiments/mobilitygen_jetbot/tool-lock.json create mode 100644 experiments/mobilitygen_jetbot/worker.py create mode 100644 src/simscene/catalog/providers/artvip.py create mode 100644 src/simscene/generation/templates/usdcraft_sdk_guide_plate_v1.py create mode 100644 src/simscene/generation/usdcraft_backend_worker.py create mode 100644 src/simscene/generation/usdcraft_sdk.py create mode 100644 src/simscene/preparation/articulation_v2.py create mode 100644 src/simscene/preparation/native_repairs.py create mode 100644 src/simscene/verification/articulated_asset_two_joint.py create mode 100644 src/simscene/verification/articulated_asset_two_joint_pair.py create mode 100644 src/simscene/worker/mechanism_v2.py create mode 100644 tests/test_articulated_asset_two_joint.py create mode 100644 tests/test_articulated_asset_two_joint_pair.py create mode 100644 tests/test_articulation_v2.py create mode 100644 tests/test_catalog_artvip.py create mode 100644 tests/test_generation_reconnect_runtime.py create mode 100644 tests/test_mechanism_two_dof.py create mode 100644 tests/test_native_repairs.py create mode 100644 tests/test_preparation_articulation_v2.py create mode 100644 tests/test_two_joint_dispatch.py create mode 100644 tests/test_usdcraft_sdk_example.py create mode 100644 tests/test_usdcraft_sdk_generation.py create mode 100644 tests/test_usdcraft_sdk_hardening.py create mode 100644 tests/test_usdcraft_two_drawer_example.py diff --git a/README.md b/README.md index 56187e0..e3a6c89 100644 --- a/README.md +++ b/README.md @@ -91,8 +91,8 @@ simscene recipe list Search retrieves metadata; selecting and preparing a model is a separate step. Default sources are NVIDIA USD Search, ABO and GSO. Explicit optional providers -cover a reviewed native USD manifest, a selected BOM package, configured HDRI -IDs and Central metadata locators. Asset licenses, dependency completeness and +cover a reviewed native USD manifest, one curated ArtVIP door, a selected BOM +package, configured HDRI IDs and Central metadata locators. Asset licenses, dependency completeness and physical suitability are checked individually. Source admission does not certify every model. @@ -110,7 +110,14 @@ describe setup and reuse. Existing asset and simulation tools remain compatible. This development branch also offers [optional automatic measured layout](docs/scene-layout.md) for existing props on an explicitly measured support. It proposes editable placements; the original USD and separate physical verification remain intact. -The pinned v0.2.0-dev.1 release above predates this tool. +The branch additionally supports an isolated [USDCraft SDK guide-plate generator](docs/usdcraft-sdk.md) +and a narrowly admitted two-joint native asset profile. The pinned v0.2.0-dev.1 +release above predates these capabilities. + +An independent [MobilityGen Jetbot experiment](experiments/mobilitygen_jetbot/README.md) +provides one fixed-route physical test and a zero-command control. It is not yet +connected to SimScene scene or simulation jobs, and does not establish general +robot planning or obstacle avoidance. ## Connect your agent @@ -153,6 +160,9 @@ Try a prompt such as: | Multi-source kinetic gallery | [Editable recipe](examples/kinetic_asset_gallery/README.md) · [66-second film](docs/media/kinetic-asset-gallery-1080p30.mp4) | | Cross-catalog gravity cell | [Locked assets, physical case and reproduction](examples/catalog_gravity_cell/README.md) | | Automatic cabinet layout (development branch) | [Editable recipe, source lock and physical checks](examples/automatic_cabinet_layout/README.md) | +| ArtVIP door (development branch) | [Selected asset, explicit physics assumptions and drive checks](examples/artvip_door/README.md) | +| USDCraft two-drawer cabinet (development branch) | [Two native joints, editable recipe and drive control](examples/usdcraft_two_drawer/README.md) | +| Generated USDCraft guide (development branch) | [Two sizes, editable recipe and physical support comparison](examples/usdcraft_sdk_guide/README.md) | | Three-level chain reaction | [Editable recipe and reproduction steps](examples/three_level_chain/README.md) · [Film](docs/media/chain-workshop-1080p30.mp4) | | Precision sorting workshop | [Scene recipe](examples/precision_sorting_corner/README.md) · [Film](docs/media/precision-workshop-1080p30.mp4) | | Maintenance workbench | [Scene recipe](examples/maintenance_workbench/README.md) · [Film](docs/media/maintenance-workbench-1080p30.mp4) | diff --git a/docs/asset-catalog.md b/docs/asset-catalog.md index c747bcc..5a2e730 100644 --- a/docs/asset-catalog.md +++ b/docs/asset-catalog.md @@ -63,6 +63,51 @@ first. Restart older SimScene servers sharing that index after upgrading; they may still present their previous projection. Preparation still inspects the selected native USD and rejects unsupported graphs or physics. +For selected sources with two actual independent scalar joints, the experimental +`articulated_prop_v2` profile preserves a native three-link tree, its collision +geometry and finite limits. Static source declarations are not enough to prove +independence: the worker also checks the actual PhysX joint-to-DOF mapping, and +the dedicated verifier compares native readings with recorded link frames. +Coupled, geared, mimic and tendon mechanisms, arbitrary link counts, and +unsupported drives or repairs remain outside this profile. The reproducible +[two-drawer example](../examples/usdcraft_two_drawer/README.md) demonstrates two +prismatic axes; two-hinge and mixed-axis models need their own runtime tests. + +ArtVIP is an explicitly selected, experimental source. The current registry +contains **only one curated object directory**, `small_furniture/door/door002`; +it is not a search index for all objects in the upstream dataset: + +```bash +simscene catalog search 'door' --source artvip +``` + +The first search reads the selected directory's Hugging Face tree metadata at +the fixed revision, without downloading the USD, textures, previews, or code. +Its one root USD must have an unambiguous path and LFS SHA-256. The root's size +is known, but the total dependency size is unknown until acquisition. A plan +can be ready to fetch while the physical profile remains unverified. Selected +preparation retrieves and checks the USD dependency closure under the normal +transfer budgets; it does not download the repository. In one cold acquisition +this particular root and its three dependencies totaled 68,676 bytes. + +The [pinned ArtVIP dataset card](https://huggingface.co/datasets/X-Humanoid/ArtVIP/blob/d22f2095bc9db29fdd4b60f4a3c4f8177e1f5e9e/README.md) +declares Apache-2.0. The record retains the card URL and its SHA-256; a separate +per-object license notice was not established, and an unreviewed revision does +not inherit this declaration. Preserve attribution and applicable notices. The +chosen door's native USD has one revolute joint and a world fixed joint, but its +rigid links lack explicit masses and its native drive uses acceleration with +unbounded effort. Its seven colliders have source physics-material densities of +700 or 7,900 kg/m³. The original source is therefore not admitted by the +preserving single-joint profile. The opt-in `repair_explicit` recipe for this +particular door adds experimental body masses and neutralizes the unsupported +drive **in a derived package**; its body masses override those original material +density contributions. It lists each affected collider, material and density. +The original source closure remains unchanged in the package. This is an +experiment, not a measurement of the manufactured object or a preservation of +its original drive behavior. See the [door example](../examples/artvip_door/README.md). +Neither dataset membership nor a metadata result establishes a compatible +profile, successful simulation, or physical behavior for other objects. + ABO is a community conversion of Amazon Berkeley Objects; preserve its source identity and CC-BY notices. NVIDIA search indexes upstream libraries with different terms: an asset's license can remain unknown even when search works. @@ -128,6 +173,18 @@ and its closure. Missing dependencies cannot qualify as complete. Failed requests retain their consumed transfer bytes. Repair publishes a new package while reusing verified files and preserving the old package. +For an explicitly repaired native articulation, the recipe must identify every +missing body mass and any incompatible drive to neutralize. A new body mass +must also explicitly identify each effective source physics-material density it +overrides. Authored descendant mass or density, inherited body density, unsafe +units and unsupported graph structures are rejected instead of silently +overridden. Reports and run readbacks link these assumptions to the prepared +manifest. Scene validation checks the file closure and recorded attribution; +scene export and execution additionally replay the source graph and compare its +collider geometry, transforms, joint attributes and physics materials. This +checks consistency with the pinned package, not the authenticity of a +caller-supplied pin. + Reusing a request ID returns its original job, including a failed job. Use a new request ID for a deliberate retry. Jobs persist independently of the MCP process. An uncertain interrupted launch is reported without automatically diff --git a/docs/assets/SOURCES.md b/docs/assets/SOURCES.md index b753ee0..49951a8 100644 --- a/docs/assets/SOURCES.md +++ b/docs/assets/SOURCES.md @@ -10,6 +10,7 @@ Source admission and asset physics are separate. Enabled means an adapter passed | [abo-glb](https://huggingface.co/datasets/codepawl/abo-glb) | enabled | yes | GLB | single_file | CC-BY-4.0; per-asset review required | 2026-11-08 | 1 | | [gso-glb](https://huggingface.co/datasets/codepawl/scanned-objects-glb) | enabled | yes | GLB | single_file | CC-BY-4.0; per-asset review required | 2026-11-08 | 1 | | [usdcraft](https://huggingface.co/datasets/nvidia/USDCraft-10K) | enabled | no | USD | dependency_closure | Apache-2.0; per-asset review required | 2026-11-08 | 1 | +| [artvip](https://huggingface.co/datasets/X-Humanoid/ArtVIP) | audited | no | USD | dependency_closure | Apache-2.0; per-asset review required | 2026-11-16 | 0 | | [polyhaven](https://polyhaven.com) | enabled | no | HDRI / material maps (selected IDs) | asset_package | CC0-1.0; per-asset review required | 2026-11-08 | 1 | | [simready-central](https://nvidia-simready-central.hf.space) | audited | no | USD locators (metadata only) | dependency_closure | unknown; per-asset review required | 2026-11-08 | 0 | | [projectsim-public](https://huggingface.co/datasets/projectsim/simready-assets) | audited | no | USD | asset_package | unknown; per-asset review required | 2026-11-08 | 1 | @@ -17,7 +18,7 @@ Source admission and asset physics are separate. Enabled means an adapter passed ## Lifecycle inventory - **enabled**: nvidia-usd-search, abo-glb, gso-glb, usdcraft, polyhaven -- **audited**: simready-central, projectsim-public +- **audited**: artvip, simready-central, projectsim-public - **candidate**: (none) - **quarantined**: (none) - **reference_only**: (none) @@ -75,6 +76,10 @@ Selected asset: `ds_R021_02` at `92f4e908415d7532a02661d6502ab49dc3aa33f9`. Observed target: physx, 6.2.0-rc.14+release.52805.02189a84.gl, 0.25.11, linux-x86_64. +### artvip + +No locally executed example is recorded. + ### polyhaven Selected asset: `studio_small_03` at `77caaff5b801972cfe022fd3d0f2ff4b946721ba211da0a59f366bf6e48473ab`. diff --git a/docs/usdcraft-sdk.md b/docs/usdcraft-sdk.md new file mode 100644 index 0000000..f3230e5 --- /dev/null +++ b/docs/usdcraft-sdk.md @@ -0,0 +1,124 @@ +# Optional USDCraft SDK guide-plate generation + +`usdcraft_sdk_guide_plate_v1` creates a metric guide plate with the +project's shipped USDCraft SDK template. This backend is optional and uses a +separate Python installation; the existing Sand3D recipes and runtime keep +their original configuration. It accepts only numeric dimensions, not Python +programs, arbitrary model paths, or downloaded scripts. + +## Runtime setup + +Prepare an editable checkout of the official +[USDCraft repository](https://github.com/NVlabs/USDCraft) at the reviewed +commit `46fec187bdce40845c30863a56143047edc4a263`, and install it in an +independent Python 3.12 environment. Its `pyproject.toml` specifies Python +`>=3.12,<3.13`, `usd-core>=26.5,<27`, and the other SDK dependencies; installation +may be substantial. Do not point the probe at an unreviewed replacement. +For example, after checking out the reviewed commit: + +```sh +python3.12 -m venv /absolute/path/to/usdcraft-venv +/absolute/path/to/usdcraft-venv/bin/python -m pip install -e /absolute/path/to/USDCraft + +simscene generate probe --backend usdcraft-sdk \ + --python /absolute/path/to/usdcraft-venv/bin/python \ + --checkout /absolute/path/to/clean-USDCraft-checkout \ + --output /absolute/path/to/new-usdcraft-runtime.json +``` + +The checkout must have no added files or directories, including Git-ignored +files, except `.git`, an optional root `.venv`, and Python `__pycache__` +directories. A separate clean checkout can be selected with `--checkout`; when +omitted, the probe looks for the editable installation's local source path. The +output path must be new. Add the following key to the existing SimScene V2 +JSON configuration, or to the file selected by `SIMSCENE_V2_CONFIG`: + +```json +{"usdcraft_generation_runtime": "/absolute/path/to/new-usdcraft-runtime.json"} +``` + +The probe records the Python executable hash, SDK checkout path and commit, +the full committed checkout's source hash, USD version, and versions of +selected dependencies. Each committed file, including code and resources, is +compared to its Git blob rather than trusting Git's index or status flags. +Unexpected files and package import origins that shadow the reviewed checkout +are rejected. The observed runtime is checked before and after generation. +Dependency versions are recorded, but dependency package contents are not +individually hashed. A changed runtime requires a new probe and a new generation +identity. + +The backend starts Python with `-S`, so `.pth` files and `sitecustomize` do not +run at startup. Dependencies must be directly importable from the selected +virtual environment's site-packages without startup hooks. A fresh private +bytecode cache prevents use of checkout `__pycache__` files. Generation has a +private job cache and temporary directory, a 180-second timeout, and process +resource limits; cancellation or timeout stops the SDK process group. Python, +third-party packages and local job storage remain trusted: dependency import +can execute code. These controls are not a filesystem or network sandbox. + +## Generate and prepare + +An MCP call can start a durable job: + +```json +{ + "recipe_id": "usdcraft_sdk_guide_plate_v1", + "parameters": {"length_m": 0.5, "width_m": 0.18, "thickness_m": 0.015}, + "request_id": "guide-plate-05" +} +``` + +Call `asset_generate` with those fields and poll `job_status` using its returned +job ID. Reuse the request ID when reconnecting to the same request. Alternatively, +save the `parameters` object to `dimensions.json` and use: + +```sh +simscene generate start usdcraft_sdk_guide_plate_v1 \ + --parameters dimensions.json --request-id guide-plate-05 +simscene generate status JOB_ID +``` + +Dimensions are in meters. The allowed ranges are length 0.05–2, width 0.02–0.8, +and thickness 0.002–0.08; thickness must be smaller than both other dimensions. +Defaults are 0.5, 0.18, and 0.015 respectively. The completed result provides +`asset_ref` for the ordinary `asset_plan` then `asset_prepare` flow. Select an +explicit preparation profile and physics policy, inspect the plan, and poll +the preparation job. See [asset catalog and preparation](asset-catalog.md). +The `sdk_report_path` and `sdk_report_sha256` in each generation result identify +that job's own check/compile evidence. The generated manifest freezes the +contract version, template hash, parameters, observed toolchain, exported USD +hash, and stable check results. Repeated identical generation reuses the same +published manifest without rewriting it. + +The native USD contains a rigid body, mass and collider. The template assumes +650 kg/m³ for mass calculation; this is a modeling assumption, not measured +material evidence. A preparation policy can replace that source physics. For +example, `static_fixture_v1` with `source_physics_policy: replace_visual_only` +and `collision_method: box_proxy` creates an explicit static approximation. +Generation and preparation do not themselves demonstrate physical behavior; +run and assess a separate frozen Isaac simulation for the intended use. + +## License and validation scope + +The project-authored template and reviewed USDCraft repository are identified +as Apache-2.0. Retain the pinned upstream [LICENSE](https://github.com/NVlabs/USDCraft/blob/46fec187bdce40845c30863a56143047edc4a263/LICENSE), +[NOTICE](https://github.com/NVlabs/USDCraft/blob/46fec187bdce40845c30863a56143047edc4a263/NOTICE), +and [third-party notices](https://github.com/NVlabs/USDCraft/blob/46fec187bdce40845c30863a56143047edc4a263/THIRD_PARTY_NOTICES.md) +with redistributed material as applicable. + +On 2026-11-16, the adapter was exercised with USDCraft 1.0.0 at the above +commit, Python 3.12.13 and `usd-core` 26.5. SDK check and compile, closed USD +inspection, and identical-input repeat generation passed for 0.5 m and 0.7 m +plates. In a frozen Isaac Sim 6.2 CPU test, a CCD-enabled ball fell beyond the +short static box proxy and settled on the longer proxy. The example was also +regenerated and prepared in a new directory, then both scenes were run and +checked again. See the [editable example](../examples/usdcraft_sdk_guide/README.md). +These checks cover only those dimensions, preparation and use; they do not +establish a general physics guarantee. + +Version 3 USDCraft SDK generation intents can be exported and rebuilt with the +normal portable prepared-role recipe workflow. Before launching regeneration, +the selected backend, trusted template and frozen runtime intent must match the +lock. The new preparation must reproduce the locked source file; its physics +case is frozen and checked anew. Earlier experimental generation contracts are +retained as existing prepared assets but are not silently promoted to v3. diff --git a/docs/validation/catalog-capabilities.md b/docs/validation/catalog-capabilities.md index 2d91869..dc43326 100644 --- a/docs/validation/catalog-capabilities.md +++ b/docs/validation/catalog-capabilities.md @@ -13,9 +13,12 @@ not been tested. | ABO / notebook rigid body | Three clean drops; missing-support control; four separately observed ramp/baffle/receiver instances; cold rebuild and warm edit | `B01DN8TB5U`, pinned revision, experimental 150 mm scale and 0.12 kg mass; actual imported geometry | | GSO / scanned product rigid body | Canonical search/plan/durable preparation; 600-step drop; missing-support control; native textured rendering | Selected fondant box, 120 mm longest extent, experimental 0.12 kg; standard GLB variant | | USDCraft / native hinge | Preserved native two-link articulation; driven forward/reverse actual DOF and frame readback; separate passive contact and collider-disabled control | `ds_R021_02`; metre/Z-up single-DOF only; native limits, mass, collision and friction retained | +| USDCraft / two native sliders | Preserved three-link native tree; independently scheduled lower and upper drawers, per-step PhysX DOF and body-frame measurements, and a same-case missing-second-drive control | Only `ds_R022_02`; the second axis is held while the first moves. This is a scheduled-drive experiment, not a passive contact-triggered mechanism. See [example](../../examples/usdcraft_two_drawer/README.md) | +| ArtVIP / native hinge | Selected source closure, derived preparation, 600-step driven run and same-case no-drive control; native DOF readback at all 601 samples | Only `door002`; original material densities are overridden by explicit experimental body masses, and its unbounded acceleration drive is neutralized. See [example](../../examples/artvip_door/README.md) | | Poly Haven / HDRI | Selected 1k EXR size/MD5/SHA256; warm restore; normal light-only USD preparation and actual two-camera rendering | `studio_small_03`; no geometry, physical body or invented bounds; provider searches configured IDs | | ProjectSim / BOM package | Pinned descriptor/BOM acquisition; normal visual preparation; native shader smoke; source and prepared eviction/restore | `industrial_pipe_valve`; visual-only, optional vendor metadata stale, no conformance or articulated support claim | | Sand3D / guide and open receiver | Actual isolated generation, normal preparation, changed-dimension runs, opening passage and closed-top control | Shipped templates only; explicit measured collision approximations, rather than automatic mechanical understanding | +| USDCraft SDK / guide plate | Reviewed isolated SDK generation and repeated identical output; two static preparations; CCD falling-ball comparison and new-directory regenerate/prepare/rerun | One shipped template at 0.5 m and 0.7 m, with explicitly replaced source physics and box proxies; see [example](../../examples/usdcraft_sdk_guide/README.md) | ## Profile compatibility @@ -24,7 +27,8 @@ not been tested. | `visual_prop_v1` | GLB or native USD visual geometry | Data-only source closure; explicit source-physics policy; no dynamic-body claim | | `static_fixture_v1` | Measured static support or guide | Explicit verified proxy/support regions; no automatic load certification | | `rigid_prop_v1` | One imported moving rigid body | Canonical units/axis, experimental mass and bounded measured convex-hull error | -| `articulated_prop_v1` | Existing native hinge/slider | Canonical metre/Z-up, two links and one admitted revolute/prismatic DOF; no joint synthesis or unsafe inertia scaling | +| `articulated_prop_v1` | Existing native hinge/slider | Canonical metre/kilogram/Z-up, two links and one admitted revolute/prismatic DOF; optional explicit source-density/mass/drive assumptions are separately recorded; no joint synthesis or unsafe inertia scaling | +| `articulated_prop_v2` | Existing two-coordinate articulation | Three rigid links in an acyclic tree with two distinct, finite-limit revolute/prismatic joints; preserve valid source physics only. It rejects unsupported coupling, gear, tendon and mimic structures; runtime verifies the actual DOF-to-joint mapping. Only the two-slider example has been physically validated so far. | | `container_v1` | Upward open receiver | Explicit source-matched floor/four-wall proxy and passage geometry; no sealed single hull | | `environment_v1` | Selected HDRI | Light-only self-contained package; no body, dimensions or bounds | @@ -43,8 +47,12 @@ experimental resizing produced the accepted notebook; the tolerance was not relaxed. Source mass declarations and recipe assumptions are distinct from manufacturer measurements. -Native articulation admission rejects missing mass, unsupported graph topology, -time-sampled motion and unsupported joint/inertia scaling. The selected hinge +Native articulation admission normally rejects missing mass, unsupported graph +topology, time-sampled motion and unsupported joint/inertia scaling. An +explicit repair recipe can fill a missing body mass and neutralize an +unsupported drive; when its mass overrides bound source-material density, +every affected source binding must be declared and the change remains visible +in the prepared manifest and runtime mass readings. The selected USDCraft hinge preparation also excludes executable action/Python graph logic; material shader node graphs remain supported. Cached prepared stages face the same playback admission check. diff --git a/examples/artvip_door/README.md b/examples/artvip_door/README.md new file mode 100644 index 0000000..a3aa81b --- /dev/null +++ b/examples/artvip_door/README.md @@ -0,0 +1,70 @@ +# ArtVIP door with explicitly prepared physics + +This small editable example selects one pinned ArtVIP door, prepares a local +derived USD, drives its single native hinge open and closed, and checks the +actual joint and body observations. It does not download the ArtVIP dataset. +The selected USD and three dependencies totaled 68,676 bytes in the measured +cold acquisition. Search reads metadata only; the exact transfer depends on +the selected revision and cache. + +The original links have no authored total mass. Their seven colliders do have +source physics-material densities, so this example's experimental 12 kg frame +and 8 kg door **override those density contributions**. The source's +acceleration drive has unbounded effort; this recipe neutralizes it and uses +separate bounded scheduled force commands. These are experimental assumptions, +not manufacturer values, and do not preserve the original drive behavior. +The package retains the unmodified source, complete repair report, and a +per-collider list of the source densities affected. A different object or +revision needs a new inspection, recipe and physical test. + +One 600-step Isaac Sim 6.2.0-rc.14 trial passed the frozen driven case with +native DOF and body-frame readings at every step. A separate otherwise identical +trial removed the drive commands: it completed the physics steps, the door +stayed near its initial angle, and the driven case failed for the expected +missing motion and commands. This tests a scheduled drive and a no-drive +counterfactual; it does not establish passive contact triggering or certify +other ArtVIP assets. The [pinned dataset card](https://huggingface.co/datasets/X-Humanoid/ArtVIP/blob/d22f2095bc9db29fdd4b60f4a3c4f8177e1f5e9e/README.md) +declares Apache-2.0; a separate object-specific notice has not been established. +Preserve source attribution and applicable notices. Model payloads are not +included in this repository. + +## Rebuild on a simulation host + +Install this development version of SimScene, USD Python bindings and FFmpeg; +configure a compatible Isaac Sim runtime and run `simscene asset probe`. Use +new, writable directories outside the checkout. `SIMSCENE_V2_CONFIG` should +identify your local index, prepared cache and probe record, as described in +[asset preparation](../../docs/asset-catalog.md). + +```bash +export SIMSCENE_HOME=/your/artvip-example/state +export SIMSCENE_CACHE=/your/artvip-example/cache +export SIMSCENE_V2_CONFIG=/your/artvip-example/v2.json +export SIMSCENE_ISAAC_PYTHON=/your/isaac-sim/python.sh + +simscene catalog search door --source artvip +python3 experiments/acquire_recipe_assets.py examples/artvip_door/assets.lock.json \ + --cache "$SIMSCENE_CACHE" --catalog-output /your/artvip-example/bindings.json +python3 experiments/apply_scene_recipe.py examples/artvip_door/recipe.json \ + --scene-id artvip_door --asset-catalog /your/artvip-example/bindings.json \ + --asset-lock examples/artvip_door/assets.lock.json \ + --save-directory /your/artvip-example/applied +python3 experiments/freeze_recipe_case.py examples/artvip_door/case.json \ + --bindings /your/artvip-example/bindings.json \ + --asset-lock examples/artvip_door/assets.lock.json \ + --output /your/artvip-example/frozen-case.json +simscene run --scene artvip_door --steps 600 --seed 42 \ + --case /your/artvip-example/frozen-case.json +python3 examples/artvip_door/check.py \ + --run /your/artvip-example/state/runs/RUN_ID --output /your/artvip-example/check.json +``` + +Replace `RUN_ID` with the returned run ID. The included recipe uses one +640×360, 2 fps diagnostic camera; the separate 1080p30 source recording was +captured from a new run and has its own frame table. The checker verifies the +frozen case, run and evidence locks, source-to-derived physics graph, mass +provenance, 601 native joint readings, and fixed-parent stability. A successful +prepare or a generated video alone is not a physical verdict. For a no-drive +control, retain the same prepared package and scene, remove the two mechanism +commands, and require the positive driven case to fail because the scheduled +motion did not occur; inspect the actual recorded motion and inputs as well. diff --git a/examples/artvip_door/assets.lock.json b/examples/artvip_door/assets.lock.json new file mode 100644 index 0000000..317c34b --- /dev/null +++ b/examples/artvip_door/assets.lock.json @@ -0,0 +1,193 @@ +{ + "schema": "simscene.selected_assets.v2", + "assets": { + "door": { + "provider": "prepared", + "source_ref": { + "source_id": "artvip", + "asset_id": "Articulated_objects/small_furniture/door/door002", + "revision": "d22f2095bc9db29fdd4b60f4a3c4f8177e1f5e9e", + "variant_id": null + }, + "profile_id": "articulated_prop_v1", + "profile_version": 1, + "parameters": { + "ccd": false, + "collision_method": "preserve", + "dynamic_friction": 0.5, + "native_physics_repairs": { + "missing_masses_kg": { + "E_door_1/E_body_6": 12.0, + "E_door_1/E_door1_2": 8.0 + }, + "neutralize_drives": { + "E_door_1/E_door1_2/RevoluteJoint_door_middle": 50.0 + }, + "material_density_overrides": { + "E_door_1/E_body_6/E_panel20_10/P_eced188c719e2e00": { + "material_path": "PhysicsMaterial", + "density_kg_m3": 700.0 + }, + "E_door_1/E_body_6/E_window_frame12_7/P_7580db7e7b403a00": { + "material_path": "PhysicsMaterial_01", + "density_kg_m3": 7900.0 + }, + "E_door_1/E_body_6/E_window_frame12_9/P_e42822adf04ffe00": { + "material_path": "PhysicsMaterial_01", + "density_kg_m3": 7900.0 + }, + "E_door_1/E_body_6/E_window_frame13_8/P_db5bd455d5db6e00": { + "material_path": "PhysicsMaterial_01", + "density_kg_m3": 7900.0 + }, + "E_door_1/E_door1_2/E_group_3/P_f65a290ec023fe00": { + "material_path": "PhysicsMaterial", + "density_kg_m3": 700.0 + }, + "E_door_1/E_door1_2/E_handle1_5/P_c834d8cb1dad7e00": { + "material_path": "PhysicsMaterial_01", + "density_kg_m3": 7900.0 + }, + "E_door_1/E_door1_2/E_handle_4/P_8a55312ec217fe00": { + "material_path": "PhysicsMaterial_01", + "density_kg_m3": 7900.0 + } + }, + "reason": "ArtVIP body masses are not authored, but seven colliders bind source materials with densities 700 or 7900 kg/m3. Experimental body masses of 12 kg and 8 kg override those source material density contributions. The source acceleration drive with unbounded effort is neutralized in the derived layer; neither these masses nor the replacement drive are manufacturer data." + }, + "proxy_tolerance_m": 0.002, + "restitution": 0.05, + "scale_mode": "preserve", + "source_physics_policy": "repair_explicit", + "static_friction": 0.6 + }, + "target": { + "engine": "physx", + "isaac_version": "6.2.0-rc.14+release.52805.02189a84.gl", + "platform": "linux-x86_64", + "usd_version": "0.25.11" + }, + "toolchain": { + "backend": "openusd", + "version": "0.25.11" + }, + "source_sha256": "a5e596ad9be87033a4f9e02056d1b3baf125355ef0495a5c63b92d9004cec2be", + "source_closure_sha256": "66675ce1b8ec2ee38804a7b861154efc8b378aeee9541a10426ab2965f9416dd", + "source_files": [ + { + "path": "Articulated_objects/small_furniture/door/door002/model_door.usd", + "size_bytes": 22536, + "sha256": "a5e596ad9be87033a4f9e02056d1b3baf125355ef0495a5c63b92d9004cec2be" + }, + { + "path": "Articulated_objects/small_furniture/door/door002/resource/img/b9325bad55ced78e3fe2c90f6fea0e43.png", + "size_bytes": 31121, + "sha256": "a31ce3cc5c29347023445e286f66357182b4daa7cf7095b8215aa3c2e434c0f9" + }, + { + "path": "Articulated_objects/small_furniture/door/door002/resource/material.usd", + "size_bytes": 2064, + "sha256": "afd74327d5b177a393f9d8691ebe8d7f8244377808b3a7d6fd7a1af776dc3302" + }, + { + "path": "Articulated_objects/small_furniture/door/door002/resource/v_0/link_0.usd", + "size_bytes": 12955, + "sha256": "a9799c221703fab3dede8c6233eb3d3f530f465dcdf29661c2cd74ec4aae2765" + } + ], + "previous_preparation": { + "prepared_id": "f5ab23edadcf0162df7311cea81bef63a264c46f85404c2bc97c707fa4365a5c", + "manifest_sha256": "41c95e85b5c4e16168179c1eb0d1dee6a83f2907ee8974d6f46324ebbfd35967", + "source_manifest_sha256": "63a3fa2e35811336305214025f2888e348e522cf798b691408d2a1719e800a31", + "scope": "informational; rebuild may change absolute provenance; no physics verdict reused" + }, + "source_record": { + "ref": { + "asset_id": "Articulated_objects/small_furniture/door/door002", + "revision": "d22f2095bc9db29fdd4b60f4a3c4f8177e1f5e9e", + "source_id": "artvip", + "variant_id": null + }, + "title": "door002", + "format": "usd", + "entry_path": "Articulated_objects/small_furniture/door/door002/model_door.usd", + "license": { + "basis": "pinned_ArtVIP_dataset_card", + "card_sha256": "3193c5d74ef7f1d4777fe0ff77d3f9f2f4c436969ea1802726da177897003f63", + "card_url": "https://huggingface.co/datasets/X-Humanoid/ArtVIP/resolve/d22f2095bc9db29fdd4b60f4a3c4f8177e1f5e9e/README.md", + "evidence": "declared", + "license": "Apache-2.0", + "notices_required": true, + "status": "known" + }, + "availability": { + "acquisition": { + "dependency_mode": "inspect_selected_usd_closure", + "files": [ + { + "path": "Articulated_objects/small_furniture/door/door002/model_door.usd", + "sha256": "a5e596ad9be87033a4f9e02056d1b3baf125355ef0495a5c63b92d9004cec2be", + "size": 22536 + } + ], + "files_complete": false, + "kind": "hf_usd_package", + "package_path": "Articulated_objects/small_furniture/door/door002", + "path": "Articulated_objects/small_furniture/door/door002/model_door.usd", + "repository": "X-Humanoid/ArtVIP", + "revision": "d22f2095bc9db29fdd4b60f4a3c4f8177e1f5e9e" + }, + "estimated_download_bytes": null, + "files_complete": false, + "granularity": "dependency_closure", + "status": "declared" + }, + "provenance": { + "license_scope": "dataset-card declaration; per-object notice not independently established", + "metadata_revision": "d22f2095bc9db29fdd4b60f4a3c4f8177e1f5e9e", + "repository": "X-Humanoid/ArtVIP", + "root_tree_entry": { + "lastCommit": { + "date": "2026-05-26T14:05:21.000Z", + "id": "e039a36ccd41c790b0a90db84be802cfa22a7e10", + "title": "Update ArtVIP-v1.3" + }, + "lfs": { + "oid": "a5e596ad9be87033a4f9e02056d1b3baf125355ef0495a5c63b92d9004cec2be", + "pointerSize": 130, + "size": 22536 + }, + "oid": "244a2443e92b723c2f8c49ca4e032b86c0259eda", + "path": "Articulated_objects/small_furniture/door/door002/model_door.usd", + "securityFileStatus": { + "avScan": { + "message": "", + "status": "safe", + "version": "1.5.2/28012" + }, + "pickleImportScan": { + "pickleImports": [], + "status": "unscanned", + "version": "0.0.0" + }, + "protectAiScan": { + "status": "unscanned" + }, + "status": "safe", + "virusTotalScan": { + "message": "File not scanned in VirusTotal", + "reportLink": "https://www.virustotal.com/gui/file/a5e596ad9be87033a4f9e02056d1b3baf125355ef0495a5c63b92d9004cec2be?utm_source=huggingface", + "status": "unscanned" + } + }, + "size": 22536, + "type": "file", + "xetHash": "d0d6516f52cc10f0b4539551614ad074d7392d8b688bdcd4e9da6012de662eb7" + }, + "selected_object_directory": "Articulated_objects/small_furniture/door/door002", + "structure_and_runtime": "unknown until selected USD is inspected and tested" + } + } + } + } +} diff --git a/examples/artvip_door/case.json b/examples/artvip_door/case.json new file mode 100644 index 0000000..2e3eed7 --- /dev/null +++ b/examples/artvip_door/case.json @@ -0,0 +1,39 @@ +{ + "schema": "simscene.articulated_asset_smoke.v1", + "schema_version": 1, + "mode": "driven", + "objects": { + "door": { + "joint_path": "/World/door/Asset/Native/E_door_1/E_door1_2/RevoluteJoint_door_middle", + "parent_body": "/World/door/Asset/Native/E_door_1/E_body_6", + "child_body": "/World/door/Asset/Native/E_door_1/E_door1_2", + "position_unit": "rad", + "limits": [ + -1.3962634015954636, + 1.3962634015954636 + ], + "joint_id": "main", + "initial_position": 0.0, + "min_travel": 0.6, + "limit_tolerance": 0.04, + "anchor_tolerance_m": 0.01, + "prepared_manifest_sha256": "${door.manifest_sha256}", + "source_ref": "${door.source_ref}", + "waypoints": [ + { + "command_step": 0, + "target_position": 0.8, + "by_step": 240, + "tolerance": 0.08 + }, + { + "command_step": 300, + "target_position": 0.0, + "by_step": 570, + "tolerance": 0.08 + } + ] + } + }, + "physical_model_note": "ArtVIP door002; source body total masses are unauthored but seven collider materials carry source densities. The explicit experimental 12 kg/8 kg body masses override those densities; source acceleration drive is neutralized. Supplemental acceptance SHA-256: a5f34c0501aee8e0fbbce24fc33be9776a60ba9c726038fa042ee124b6054bbf" +} diff --git a/examples/artvip_door/check.py b/examples/artvip_door/check.py new file mode 100644 index 0000000..8c106bc --- /dev/null +++ b/examples/artvip_door/check.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +"""Check a new ArtVIP door run without changing its physics or evidence.""" +import argparse +import hashlib +import json +import math +from pathlib import Path + +from simscene.physics_binding import validate_asset_binding +from simscene.preparation.articulation import verify_source_graph +from simscene.recipes.cases import freeze_case +from simscene.verification.articulated_asset_smoke import verify_run + +HERE=Path(__file__).resolve().parent + + +def sha(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def check(run): + run=Path(run).resolve() + result=json.loads((run/'result.json').read_text()) + spec=json.loads((run/'spec.json').read_text()) + frozen=json.loads((run/'acceptance-case.json').read_text()) + template=json.loads((HERE/'case.json').read_text()) + lock=json.loads((HERE/'assets.lock.json').read_text()) + supplement=json.loads((HERE/'supplement.json').read_text()) + obj=spec['objects']['door'] + binding={'asset_path':obj['asset_path'],'asset_binding':obj['asset_binding']} + expected=freeze_case(template,{'door':binding},lock['assets'])['case'] + core=verify_run(run) + manifest=validate_asset_binding(obj['asset_binding'],require_dynamic=True,asset_path=obj['asset_path']) + package=Path(obj['asset_binding']['manifest_path']).parent + source_graph=verify_source_graph(package,manifest) + frames=[result['initial_observation']]+result['samples'] + records=[frame['mechanisms']['door']['joints']['main'] for frame in frames] + def finite(value):return type(value) in (int,float) and math.isfinite(value) + native=all(finite(r.get('native_position')) and finite(r.get('native_velocity')) + and r.get('native_measurement_source')=='PhysX_articulation_tensor_DOF_readback_SI' + and abs(r['native_position']-r['position'])<=supplement['max_native_frame_disagreement_rad'] + for r in records) + mapped=result['body_bindings']['door'];parent=mapped['joints']['main']['parent_body'] + parent_start=frames[0]['positions'][parent] + parent_drift=max(math.dist(parent_start,frame['positions'][parent]) for frame in frames) + properties=result['mechanism_configuration']['mass_properties_by_prim_path'] + mass_checks=[] + for local_id,expected_mass in supplement['mass_kg'].items(): + body=mapped['bodies'][local_id]['motion_body'];mass=properties[body] + mass_checks.append(abs(mass['mass_kg']-expected_mass)<1e-5 + and mass.get('mass_provenance')=='explicit_experimental_assumption_overrides_source_material_density' + and mass.get('native_repairs_ref',{}).get('manifest_sha256')==obj['asset_binding']['manifest_sha256']) + checks={'frozen_case_matches_template':frozen==expected, + 'supplement_hash_pinned_in_case':sha(HERE/'supplement.json') in frozen['physical_model_note'], + 'core_physical_and_integrity_checks':core['passed'], + 'source_graph_and_collision_replayed':source_graph, + 'source_sha256_matches_example':manifest['source_sha256']==supplement['source_sha256'], + 'source_material_overrides_explicit':len(manifest['physics_repairs']['material_density_overrides'])==supplement['source_material_density_override_count'], + 'all_native_dof_readings_present_and_consistent':native, + 'parent_drift_within_limit':parent_drift<=supplement['max_fixed_parent_translation_m'], + 'cooked_masses_and_assumptions_match':all(mass_checks), + 'complete_physics_steps':result['actual_physics_steps']==supplement['physics_steps']} + return {'schema':'simscene.artvip_door_example_check.v1','run':str(run),'checks':checks, + 'passed':all(checks.values()),'core_verification':core,'native_sample_count':len(records), + 'observed_joint_range_rad':[min(r['position'] for r in records),max(r['position'] for r in records)], + 'max_fixed_parent_translation_m':parent_drift, + 'scope':'One selected object, one scheduled drive, and explicitly experimental derived physics; not a general dataset certification.'} + + +def main(): + parser=argparse.ArgumentParser(description=__doc__) + parser.add_argument('--run',required=True);parser.add_argument('--output',required=True) + args=parser.parse_args();report=check(args.run) + output=Path(args.output);output.parent.mkdir(parents=True,exist_ok=True) + with output.open('x',encoding='utf8') as stream: + json.dump(report,stream,indent=2,allow_nan=False);stream.write('\n') + print(json.dumps({'passed':report['passed'],'checks':report['checks'],'report':str(output)},indent=2)) + return 0 if report['passed'] else 1 + + +if __name__=='__main__':raise SystemExit(main()) diff --git a/examples/artvip_door/recipe.json b/examples/artvip_door/recipe.json new file mode 100644 index 0000000..d82ab72 --- /dev/null +++ b/examples/artvip_door/recipe.json @@ -0,0 +1,178 @@ +{ + "description": "Editable ArtVIP door and a measured scheduled drive, exported from the paired physical trial.", + "source_run_id": "1081ffaa561c4beead99464d3289ce2b", + "source_run_lock_sha256": "a31016c7fef37ccb2f0a557df7c99df49a9f0dba0258e68a0316e5fe38a42be6", + "operations": [ + { + "op": "add", + "id": "door", + "object": { + "kind": "asset", + "dynamic": true, + "position": [ + 0.0, + 0.0, + 0.0 + ], + "mechanism": { + "commands": [ + { + "joint_id": "main", + "trigger": { + "type": "at_step", + "physics_step": 0 + }, + "target_position": 0.8, + "position_unit": "rad", + "stiffness": 800.0, + "damping": 50.0, + "max_effort": 160.0 + }, + { + "joint_id": "main", + "trigger": { + "type": "at_step", + "physics_step": 300 + }, + "target_position": 0.0, + "position_unit": "rad", + "stiffness": 800.0, + "damping": 50.0, + "max_effort": 160.0 + } + ] + }, + "asset_role": "door" + } + }, + { + "op": "add", + "id": "floor", + "object": { + "kind": "box", + "size": [ + 8.0, + 8.0, + 0.1 + ], + "position": [ + 0.0, + 0.0, + -0.05 + ], + "dynamic": false, + "collision": true, + "color": [ + 0.25, + 0.28, + 0.31 + ] + } + }, + { + "op": "add", + "id": "wall", + "object": { + "kind": "box", + "size": [ + 20.0, + 0.12, + 5.0 + ], + "position": [ + 0.0, + 2.0, + 2.5 + ], + "dynamic": false, + "collision": false, + "color": [ + 0.21, + 0.25, + 0.3 + ] + } + }, + { + "op": "add", + "id": "sky", + "object": { + "kind": "light", + "light": { + "type": "dome" + }, + "intensity": 500.0 + } + }, + { + "op": "add", + "id": "key", + "object": { + "kind": "light", + "light": { + "type": "sphere", + "radius_m": 0.7 + }, + "position": [ + 1.0, + -3.0, + 4.5 + ], + "intensity": 2500.0 + } + }, + { + "op": "add", + "id": "overview", + "object": { + "kind": "camera", + "position": [ + 3.0, + -5.0, + 2.4 + ], + "record_fps": 2, + "preview_fps": 1, + "camera": { + "resolution": [ + 640, + 360 + ], + "focal_length_mm": 28.0, + "horizontal_aperture_mm": 36.0, + "focus_distance_m": 5.8, + "clipping_range_m": [ + 0.01, + 100.0 + ] + }, + "orientation_wxyz": [ + 0.7315803619922879, + 0.6273249849986092, + 0.17375896165613133, + 0.20263602934303418 + ] + } + }, + { + "op": "set_presentation", + "presentation": { + "profile": "preview", + "budget": { + "max_cameras": 1, + "max_recording_bytes": 1073741824, + "min_free_bytes": 2147483648 + } + } + }, + { + "op": "set_observation", + "observation": { + "sample_interval_steps": 1, + "strict_start": true, + "record_contact_pairs": true + } + } + ], + "schema": "simscene.scene_recipe.v2" +} diff --git a/examples/artvip_door/supplement.json b/examples/artvip_door/supplement.json new file mode 100644 index 0000000..5e3a6ac --- /dev/null +++ b/examples/artvip_door/supplement.json @@ -0,0 +1,19 @@ +{ + "schema": "artvip.paired_trial_expectations.v2", + "source_sha256": "a5e596ad9be87033a4f9e02056d1b3baf125355ef0495a5c63b92d9004cec2be", + "intervention": "remove only mechanism.commands", + "physics_steps": 600, + "physics_dt_s": 0.016666666666666666, + "max_control_absolute_motion_rad": 0.05, + "minimum_driven_motion_rad": 0.6, + "max_native_frame_disagreement_rad": 0.015, + "require_native_dof_each_sample": true, + "require_no_control_command_events": true, + "max_fixed_parent_translation_m": 0.01, + "mass_kg": { + "link0": 12.0, + "link1": 8.0 + }, + "source_material_density_override_count": 7, + "scope": "experimental body mass overrides source density contributions, and source drive is neutralized; scheduled drives do not imply contact causality" +} diff --git a/examples/usdcraft_sdk_guide/README.md b/examples/usdcraft_sdk_guide/README.md new file mode 100644 index 0000000..38911de --- /dev/null +++ b/examples/usdcraft_sdk_guide/README.md @@ -0,0 +1,67 @@ +# Generated guide-plate support comparison + +This example uses the optional USDCraft SDK backend to generate two instances +of the same guide-plate template: 0.5 m and 0.7 m long. Both retain the same +width and thickness. They are independently prepared as static fixtures with +explicit measured box collision proxies; their original generated rigid-body +physics is replaced in the derived preparation. A 40 mm ball is released at +the same position in each scene. It falls beyond the short plate and settles +on the floor; the long plate reaches underneath it and supports it. + +The frozen case checks complete 360-step, 60 Hz observations, input and +output integrity, the selected generated-source hashes, CCD on the ball and +scene, the expected separate direct contact callbacks, settling, and a 2 mm +upper bound on reported penetration. Contact callbacks cannot exclude contacts +or penetration that the physics engine does not report. The generator's +assumed material density and the static box proxy are experimental; this is not +a strength or real-world safety test. + +The matched physical test used Isaac Sim 6.2.0-rc.14 and CPU PhysX. One run of +each size passed; a separate new-directory regeneration and preparation is +also exercised by the commands below. Changing dimensions, supports, material +or runtime requires a new frozen case and actual simulation. The generated USD +is not included in the repository. + +## Rebuild and verify + +Set up and probe the isolated, reviewed SDK runtime as described in +[USDCraft SDK generation](../../docs/usdcraft-sdk.md). The lock fixes the +reviewed SDK commit, template hash, parameters, source-file hashes and the +recorded toolchain. A different runtime must be checked and explicitly +requalified rather than silently relabeling the old result. Also configure the +ordinary Isaac preparation runtime, FFmpeg and USD bindings. Use new directories +outside the checkout: + +```bash +export SIMSCENE_HOME=/your/generated-guide/state +export SIMSCENE_CACHE=/your/generated-guide/cache +export SIMSCENE_V2_CONFIG=/your/generated-guide/v2.json +export SIMSCENE_ISAAC_PYTHON=/your/isaac-sim/python.sh +export SIMSCENE_PHYSICS_DEVICE=cpu + +python3 experiments/acquire_recipe_assets.py examples/usdcraft_sdk_guide/assets.lock.json \ + --cache "$SIMSCENE_CACHE" --catalog-output /your/generated-guide/bindings.json +python3 experiments/apply_scene_recipe.py examples/usdcraft_sdk_guide/recipe-short.json \ + --scene-id sdk_guide_short --asset-catalog /your/generated-guide/bindings.json \ + --asset-lock examples/usdcraft_sdk_guide/assets.lock.json \ + --save-directory /your/generated-guide/applied-short +python3 experiments/apply_scene_recipe.py examples/usdcraft_sdk_guide/recipe-long.json \ + --scene-id sdk_guide_long --asset-catalog /your/generated-guide/bindings.json \ + --asset-lock examples/usdcraft_sdk_guide/assets.lock.json \ + --save-directory /your/generated-guide/applied-long +python3 experiments/freeze_recipe_case.py examples/usdcraft_sdk_guide/case.json \ + --bindings /your/generated-guide/bindings.json \ + --asset-lock examples/usdcraft_sdk_guide/assets.lock.json \ + --output /your/generated-guide/frozen-case.json +simscene run --scene sdk_guide_short --steps 360 --seed 17 --case /your/generated-guide/frozen-case.json +simscene run --scene sdk_guide_long --steps 360 --seed 17 --case /your/generated-guide/frozen-case.json +python3 examples/usdcraft_sdk_guide/check_pair.py \ + --short-run "$SIMSCENE_HOME/runs/SHORT_RUN_ID" \ + --long-run "$SIMSCENE_HOME/runs/LONG_RUN_ID" \ + --case /your/generated-guide/frozen-case.json --output /your/generated-guide/check.json +``` + +Replace both IDs with the returned run IDs. The checker requires the example +case freshly bound to the two rebuilt assets and checks the input/evidence +locks for both runs. It cannot turn a preview, SDK compilation or an old +result into a physical pass. diff --git a/examples/usdcraft_sdk_guide/assets.lock.json b/examples/usdcraft_sdk_guide/assets.lock.json new file mode 100644 index 0000000..43eb764 --- /dev/null +++ b/examples/usdcraft_sdk_guide/assets.lock.json @@ -0,0 +1,237 @@ +{ + "schema": "simscene.selected_assets.v2", + "assets": { + "short": { + "provider": "prepared", + "source_ref": { + "source_id": "local-usdcraft-sdk", + "asset_id": "usdcraft_sdk_guide_plate_v1", + "revision": "c01db7f67cd99176b023c87ebb30be2eccb09ab93e37951e8a521287ea400ec7", + "variant_id": null + }, + "profile_id": "static_fixture_v1", + "profile_version": 1, + "parameters": { + "ccd": false, + "collision_method": "box_proxy", + "dynamic_friction": 0.5, + "proxy_tolerance_m": 0.002, + "restitution": 0.05, + "scale_mode": "preserve", + "source_physics_policy": "replace_visual_only", + "static_friction": 0.6, + "static_proxy": { + "orientation_wxyz": [ + 1.0, + 0.0, + 0.0, + 0.0 + ], + "position_m": [ + 0.0, + 0.0, + 0.0075 + ], + "size_m": [ + 0.5, + 0.18, + 0.015 + ] + }, + "support_surfaces": { + "top": { + "max_xy": [ + 0.24, + 0.08 + ], + "min_xy": [ + -0.24, + -0.08 + ], + "z_m": 0.015 + } + } + }, + "target": { + "engine": "physx", + "isaac_version": "6.2.0-rc.14+release.52805.02189a84.gl", + "platform": "linux-x86_64", + "usd_version": "0.25.11" + }, + "toolchain": { + "backend": "openusd", + "version": "0.25.11" + }, + "source_sha256": "894e85edbdeccbbe6777284dc5864618b1ff944bdb10c330fcb3f60c456a1257", + "source_closure_sha256": "38c33b2907b18281f00f415ec660e6a570c6291e8bb9dd67e11bb39a73775fcc", + "source_files": [ + { + "path": "source.usda", + "size_bytes": 4355, + "sha256": "894e85edbdeccbbe6777284dc5864618b1ff944bdb10c330fcb3f60c456a1257" + } + ], + "previous_preparation": { + "prepared_id": "80ddd5f8270b3263d66e0e69dd7c852bf33328f8cd2768ec9bdf1b43cd1aef89", + "manifest_sha256": "bb2cf274ca88cc95baab7a66b7b4bd6e4ce0f7904acdae3a39bcdcb65c1755e0", + "source_manifest_sha256": "e972c973c93346bc72907b25723e3c476858a13d94e76167f0059a828ce5b9b5", + "scope": "informational; rebuild may change absolute provenance; no physics verdict reused" + }, + "generation": { + "generator": "usdcraft_sdk", + "recipe_id": "usdcraft_sdk_guide_plate_v1", + "parameters": { + "length_m": 0.5, + "width_m": 0.18, + "thickness_m": 0.015 + }, + "seed": 0, + "reviewed_commit": "46fec187bdce40845c30863a56143047edc4a263", + "template_sha256": "c2adbfbb84567e7189b0f32a99141bc834ec312c8585570ded9b445872093768", + "toolchain_intent": { + "dependencies": { + "networkx": "3.6.1", + "numpy": "2.4.6", + "pydantic": "2.13.4", + "scipy": "1.18.0", + "trimesh": "4.12.2", + "usd-core": "26.5", + "usdcraft": "1.0.0" + }, + "python_executable_sha256": "038e0280abc7a8e7d45f8a64c6b5309dcebd3b09146ed3b62ca927963e4a93d6", + "python_version": [ + 3, + 12, + 13 + ], + "source_clean": true, + "source_tree_sha256": "4e2c03fca4b37b68b3d4c7e7aeb1e3eb18c0ccee036260a8336f40588304d24c", + "usd_version": [ + 0, + 26, + 5 + ], + "usdcraft_commit": "46fec187bdce40845c30863a56143047edc4a263", + "usdcraft_version": "1.0.0" + }, + "generation_contract_version": 3 + } + }, + "long": { + "provider": "prepared", + "source_ref": { + "source_id": "local-usdcraft-sdk", + "asset_id": "usdcraft_sdk_guide_plate_v1", + "revision": "c2f13662c8d11c797bebaa186c810101a3bb7de62f00df9bfe72cd90a8ce44b8", + "variant_id": null + }, + "profile_id": "static_fixture_v1", + "profile_version": 1, + "parameters": { + "ccd": false, + "collision_method": "box_proxy", + "dynamic_friction": 0.5, + "proxy_tolerance_m": 0.002, + "restitution": 0.05, + "scale_mode": "preserve", + "source_physics_policy": "replace_visual_only", + "static_friction": 0.6, + "static_proxy": { + "orientation_wxyz": [ + 1.0, + 0.0, + 0.0, + 0.0 + ], + "position_m": [ + 0.0, + 0.0, + 0.0075 + ], + "size_m": [ + 0.7, + 0.18, + 0.015 + ] + }, + "support_surfaces": { + "top": { + "max_xy": [ + 0.33999999999999997, + 0.08 + ], + "min_xy": [ + -0.33999999999999997, + -0.08 + ], + "z_m": 0.015 + } + } + }, + "target": { + "engine": "physx", + "isaac_version": "6.2.0-rc.14+release.52805.02189a84.gl", + "platform": "linux-x86_64", + "usd_version": "0.25.11" + }, + "toolchain": { + "backend": "openusd", + "version": "0.25.11" + }, + "source_sha256": "1d680272bc0277488e1da40b84a3bd2b32e88c4cc4888218886c14c84b97d395", + "source_closure_sha256": "f2e65d69bd58940715b8f60e41a9d55954f9781681f157708fe1b4f18cd11e0b", + "source_files": [ + { + "path": "source.usda", + "size_bytes": 4355, + "sha256": "1d680272bc0277488e1da40b84a3bd2b32e88c4cc4888218886c14c84b97d395" + } + ], + "previous_preparation": { + "prepared_id": "f309dd2e58f12082f4602011d74e9187135554fee3f00b226cdde168d905a461", + "manifest_sha256": "092a9b0e50f651741662926b0ed3ef476893d07e43e45f470b154379ab4c6085", + "source_manifest_sha256": "0a255add96a1a8fdc8e02f94237513f56d56d00a2e61a2cb20c5379cff61ee86", + "scope": "informational; rebuild may change absolute provenance; no physics verdict reused" + }, + "generation": { + "generator": "usdcraft_sdk", + "recipe_id": "usdcraft_sdk_guide_plate_v1", + "parameters": { + "length_m": 0.7, + "width_m": 0.18, + "thickness_m": 0.015 + }, + "seed": 0, + "reviewed_commit": "46fec187bdce40845c30863a56143047edc4a263", + "template_sha256": "c2adbfbb84567e7189b0f32a99141bc834ec312c8585570ded9b445872093768", + "toolchain_intent": { + "dependencies": { + "networkx": "3.6.1", + "numpy": "2.4.6", + "pydantic": "2.13.4", + "scipy": "1.18.0", + "trimesh": "4.12.2", + "usd-core": "26.5", + "usdcraft": "1.0.0" + }, + "python_executable_sha256": "038e0280abc7a8e7d45f8a64c6b5309dcebd3b09146ed3b62ca927963e4a93d6", + "python_version": [ + 3, + 12, + 13 + ], + "source_clean": true, + "source_tree_sha256": "4e2c03fca4b37b68b3d4c7e7aeb1e3eb18c0ccee036260a8336f40588304d24c", + "usd_version": [ + 0, + 26, + 5 + ], + "usdcraft_commit": "46fec187bdce40845c30863a56143047edc4a263", + "usdcraft_version": "1.0.0" + }, + "generation_contract_version": 3 + } + } + } +} diff --git a/examples/usdcraft_sdk_guide/case.json b/examples/usdcraft_sdk_guide/case.json new file mode 100644 index 0000000..7b6ed21 --- /dev/null +++ b/examples/usdcraft_sdk_guide/case.json @@ -0,0 +1,52 @@ +{ + "schema": "simscene.generated_plate_support_pair.v1", + "steps": 360, + "physics_dt_s": 0.016666666666666666, + "physics_device": "cpu", + "seed": 17, + "assets": { + "short": { + "source_ref": "${short.source_ref}", + "source_sha256": "894e85edbdeccbbe6777284dc5864618b1ff944bdb10c330fcb3f60c456a1257", + "length_m": 0.5, + "manifest_sha256": "${short.manifest_sha256}" + }, + "long": { + "source_ref": "${long.source_ref}", + "source_sha256": "1d680272bc0277488e1da40b84a3bd2b32e88c4cc4888218886c14c84b97d395", + "length_m": 0.7, + "manifest_sha256": "${long.manifest_sha256}" + } + }, + "ball_center_initial_m": [ + 0.3, + 0.0, + 0.65 + ], + "ball_radius_m": 0.02, + "plate_origin_m": [ + 0.0, + 0.0, + 0.25 + ], + "settled_last_steps": 60, + "max_settled_z_range_m": 0.005, + "max_settled_xy_drift_m": 0.01, + "expected_final_ball_z_m": { + "short": [ + 0.015, + 0.03 + ], + "long": [ + 0.279, + 0.295 + ] + }, + "expected_contact": { + "short": "floor", + "long": "plate" + }, + "require_direct_contact_min_separation_m_at_most": 0.003, + "max_reported_penetration_m": 0.002, + "note": "Same ball and scene; only selected generated plate length and its prepared source change. Both use explicitly replaced static box proxies and a ball with CCD. Case is an experiment-specific external protocol, not an existing SimScene case type." +} diff --git a/examples/usdcraft_sdk_guide/check_pair.py b/examples/usdcraft_sdk_guide/check_pair.py new file mode 100644 index 0000000..a866e19 --- /dev/null +++ b/examples/usdcraft_sdk_guide/check_pair.py @@ -0,0 +1,165 @@ +#!/usr/bin/env python3 +"""Read-only paired check for the two generated-plate example runs.""" +import argparse +import copy +import hashlib +import json +import math +from pathlib import Path + +from simscene.evidence_integrity import verify as verify_evidence +from simscene.physics_binding import validate_asset_binding +from simscene.recipes.cases import freeze_case +from simscene.recipes.io import resolve_operations +from simscene.run_integrity import verify as verify_inputs + +HERE = Path(__file__).resolve().parent + + +def check(short_run, long_run, case_path): + case_path = Path(case_path).resolve() + case = json.loads(case_path.read_text()) + case_sha = hashlib.sha256(case_path.read_bytes()).hexdigest() + runs = {} + for name, directory in (('short', short_run), ('long', long_run)): + root = Path(directory).resolve() + runs[name] = {'root':root, 'lock':json.loads((root/'run-lock.json').read_text()), + 'spec':json.loads((root/'spec.json').read_text()), + 'result':json.loads((root/'result.json').read_text()), + 'inputs':verify_inputs(root), 'evidence':verify_evidence(root)} + checks = {'distinct_runs':runs['short']['root'] != runs['long']['root']} + lock = json.loads((HERE/'assets.lock.json').read_text()) + template = json.loads((HERE/'case.json').read_text()) + bindings = {name:{'asset_path':item['spec']['objects']['plate']['asset_path'], + 'asset_binding':item['spec']['objects']['plate']['asset_binding']} + for name,item in runs.items()} + expected = freeze_case(template,bindings,lock['assets'])['case'] + checks['case_matches_example_template_and_rebuilt_assets'] = case == expected + same = ('physics_dt_s','physics_device','requested_physics_steps','seed', + 'runtime_version','runtime_python_sha256','worker_code_sha256') + checks['same_runtime_and_physics'] = all(k in runs['short']['lock'] and k in runs['long']['lock'] + and runs['short']['lock'][k]==runs['long']['lock'][k] for k in same) + + def normalize(spec): + spec = copy.deepcopy(spec) + for key in ('scene_id','revision','requests'):spec.pop(key,None) + plate = spec['objects']['plate'] + plate.pop('asset_path');plate.pop('asset_binding') + return spec + checks['same_scene_except_selected_plate'] = normalize(runs['short']['spec']) == normalize(runs['long']['spec']) + details = {} + for name,item in runs.items(): + root,run_lock,spec,result = (item[key] for key in ('root','lock','spec','result')) + frozen = case['assets'][name] + recipe=json.loads((HERE/('recipe-'+name+'.json')).read_text()) + ops=resolve_operations(recipe,bindings,selections=lock['assets']) + expected_objects={op['id']:op['object'] for op in ops if op.get('op')=='add'} + expected_observation=next(op['observation'] for op in ops if op.get('op')=='set_observation') + expected_presentation=next(op['presentation'] for op in ops if op.get('op')=='set_presentation') + checks[name+'_scene_matches_example']=(spec['objects']==expected_objects + and spec.get('observation')==expected_observation and spec.get('presentation')==expected_presentation) + settings=result.get('physics_settings',{}) + checks[name+'_actual_physics_matches_case']=(run_lock.get('seed')==case['seed'] + and run_lock.get('requested_physics_steps')==case['steps'] + and run_lock.get('physics_device')==case['physics_device']=='cpu' + and abs(run_lock.get('physics_dt_s',0)-case['physics_dt_s'])<1e-12 + and result.get('seed')==case['seed'] and result.get('task_status') in ('unverified','completed') + and all(isinstance(settings.get(key),dict) and settings[key].get('requested_device')=='cpu' + and settings[key].get('request_matches_observation') is True + and settings[key].get('enable_gpu_dynamics') is False + and abs(settings[key].get('authored_time_steps_per_second',0)*case['physics_dt_s']-1)<1e-5 + for key in ('before_warmup','after_run'))) + checks[name+'_case_and_inputs_locked'] = (run_lock.get('acceptance_case_sha256') == case_sha + and hashlib.sha256((root/'acceptance-case.json').read_bytes()).hexdigest()==case_sha + and item['inputs']['passed'] is True and item['evidence']['passed'] is True + and item['evidence']['partial'] is False) + obj = spec['objects']['plate'] + manifest = validate_asset_binding(obj['asset_binding'],asset_path=obj['asset_path']) + checks[name+'_source_and_geometry_pinned'] = ( + obj['asset_binding']['manifest_sha256']==frozen['manifest_sha256'] + and Path(obj['asset_path']).resolve().is_relative_to(root) + and manifest['source_ref']==frozen['source_ref'] and manifest['source_sha256']==frozen['source_sha256'] + and manifest['parameters']['static_proxy']['size_m']==[frozen['length_m'],.18,.015] + and manifest['parameters']['source_physics_policy']=='replace_visual_only') + from pxr import Usd + stage=Usd.Stage.Open(str(root/'scene.usda')) + scene_ccd=stage.GetPrimAtPath('/World/PhysicsScene').GetAttribute('physxScene:enableCCD') + ball_ccd=stage.GetPrimAtPath('/World/ball').GetAttribute('physxRigidBody:enableCCD') + checks[name+'_ccd_enabled']=(spec['objects']['ball'].get('physics',{}).get('enable_ccd') is True + and bool(scene_ccd) and scene_ccd.Get() is True + and bool(ball_ccd) and ball_ccd.Get() is True) + frames = [result['initial_observation'],*result['samples']] + finite=lambda value:type(value) in (int,float) and math.isfinite(value) + absolute_step=result.get('run_zero_absolute_physics_step') + absolute_time=result.get('run_zero_absolute_simulation_time_s') + checks[name+'_complete_timeline'] = (result['partial'] is False and result['samples_truncated'] is False + and result['contacts_truncated'] is False and result['actual_physics_steps']==case['steps'] + and result.get('requested_physics_steps')==case['steps'] and result.get('observation_interval_steps')==1 + and type(absolute_step) is int and absolute_step>=0 and finite(absolute_time) + and finite(result.get('simulation_time_s')) + and abs(result['simulation_time_s']-case['steps']*case['physics_dt_s'])<1e-6 + and result.get('contact_geometry_incomplete') is False + and len(frames)==case['steps']+1 and all(type(row.get('physics_steps')) is int and row['physics_steps']==i + and finite(row.get('simulation_time_s')) + and abs(row['simulation_time_s']-i*case['physics_dt_s'])<1e-6 + and type(row.get('absolute_physics_step')) is int and row['absolute_physics_step']==absolute_step+i + and finite(row.get('absolute_simulation_time_s')) + and abs(row['absolute_simulation_time_s']-absolute_time-i*case['physics_dt_s'])<1e-5 + for i,row in enumerate(frames))) + positions=[frame.get('positions',{}).get('/World/ball') for frame in frames] + checks[name+'_all_ball_positions_finite'] = all(isinstance(position,list) and len(position)==3 + and all(finite(value) for value in position) for position in positions) + if not checks[name+'_complete_timeline'] or not checks[name+'_all_ball_positions_finite']: + return {'schema':'simscene.generated_plate_support_pair_report.v1','passed':False,'checks':checks, + 'scope':'Incomplete or malformed per-step physics evidence.'} + reset=result.get('initialization_reset',{}) + checks[name+'_initial_ball_matches_case']=(len(positions[0])==3 + and math.dist(positions[0],case['ball_center_initial_m'])<=1e-5 + and spec['objects']['ball'].get('size')==[2*case['ball_radius_m']]*3 + and spec['objects']['plate'].get('position')==case['plate_origin_m']) + checks[name+'_initial_state_measured']=(reset.get('applied') is True + and reset.get('phase')=='before_task_start' and reset.get('setters_during_task') is False + and reset.get('max_linear_speed_m_s',math.inf)<=1e-5 + and reset.get('max_angular_speed_rad_s',math.inf)<=1e-5 + and math.dist(frames[0]['linear_velocities_m_s']['/World/ball'],[0.,0.,0.])<=1e-5 + and math.dist(frames[0]['angular_velocities_rad_s']['/World/ball'],[0.,0.,0.])<=1e-5) + tail=positions[-case['settled_last_steps']-1:]; z=[p[2] for p in tail] + checks[name+'_ball_settled_at_expected_height']=(case['expected_final_ball_z_m'][name][0] <= z[-1] + <= case['expected_final_ball_z_m'][name][1] and max(z)-min(z)<=case['max_settled_z_range_m'] + and max(math.dist(p[:2],tail[0][:2]) for p in tail)<=case['max_settled_xy_drift_m']) + contacts={};valid_contacts=True + for frame in frames: + for pair in frame.get('contact_pairs',[]): + bodies=pair.get('body_ids',[]) + if not isinstance(bodies,list) or len(bodies)!=2 or not all(isinstance(value,str) for value in bodies): + valid_contacts=False;continue + if 'ball' not in bodies:continue + other=next((value for value in bodies if value!='ball'),None) + separation=pair.get('minimum_separation_m') + if other and type(separation) in (int,float) and math.isfinite(separation): + contacts[other]=min(contacts.get(other,math.inf),separation) + else:valid_contacts=False + target=case['expected_contact'][name] + checks[name+'_expected_contact_reported']=(valid_contacts and set(contacts)=={target} + and contacts[target]<=case['require_direct_contact_min_separation_m_at_most']) + checks[name+'_reported_penetration_within_limit']=(contacts.get(target,-math.inf)>=-case['max_reported_penetration_m']) + details[name]={'run':str(root),'final_ball_position_m':positions[-1], + 'last_second_z_range_m':max(z)-min(z),'minimum_reported_contact_separation_m':contacts, + 'physics_steps':result['actual_physics_steps']} + return {'schema':'simscene.generated_plate_support_pair_report.v1','passed':all(checks.values()), + 'checks':checks,'observations':details, + 'scope':'Two selected static proxies and one CCD ball; contact callbacks do not exclude unreported penetration.'} + + +def main(): + parser=argparse.ArgumentParser(description=__doc__) + parser.add_argument('--short-run',required=True);parser.add_argument('--long-run',required=True) + parser.add_argument('--case',required=True);parser.add_argument('--output',required=True) + args=parser.parse_args();report=check(args.short_run,args.long_run,args.case) + output=Path(args.output);output.parent.mkdir(parents=True,exist_ok=True) + with output.open('x',encoding='utf8') as f:json.dump(report,f,indent=2,allow_nan=False);f.write('\n') + print(json.dumps({'passed':report['passed'],'checks':report['checks'],'report':str(output)},indent=2)) + return 0 if report['passed'] else 1 + + +if __name__=='__main__':raise SystemExit(main()) diff --git a/examples/usdcraft_sdk_guide/recipe-long.json b/examples/usdcraft_sdk_guide/recipe-long.json new file mode 100644 index 0000000..ffce1a1 --- /dev/null +++ b/examples/usdcraft_sdk_guide/recipe-long.json @@ -0,0 +1,176 @@ +{ + "schema": "simscene.scene_recipe.v2", + "description": "Generated long plate, CCD ball and support test.", + "operations": [ + { + "op": "add", + "id": "plate", + "object": { + "kind": "asset", + "dynamic": false, + "position": [ + 0.0, + 0.0, + 0.25 + ], + "asset_role": "long" + } + }, + { + "op": "add", + "id": "ball", + "object": { + "kind": "sphere", + "size": [ + 0.04, + 0.04, + 0.04 + ], + "position": [ + 0.3, + 0.0, + 0.65 + ], + "dynamic": true, + "collision": true, + "mass_kg": 0.05, + "physics": { + "enable_ccd": true + }, + "color": [ + 0.9, + 0.3, + 0.1 + ] + } + }, + { + "op": "add", + "id": "floor", + "object": { + "kind": "box", + "size": [ + 2.0, + 2.0, + 0.1 + ], + "position": [ + 0.0, + 0.0, + -0.05 + ], + "dynamic": false, + "collision": true, + "color": [ + 0.25, + 0.28, + 0.3 + ] + } + }, + { + "op": "add", + "id": "pedestal", + "object": { + "kind": "box", + "size": [ + 0.1, + 0.14, + 0.25 + ], + "position": [ + -0.15, + 0.0, + 0.125 + ], + "dynamic": false, + "collision": true, + "color": [ + 0.35, + 0.4, + 0.45 + ] + } + }, + { + "op": "add", + "id": "sky", + "object": { + "kind": "light", + "light": { + "type": "dome" + }, + "intensity": 500.0 + } + }, + { + "op": "add", + "id": "key", + "object": { + "kind": "light", + "light": { + "type": "sphere", + "radius_m": 0.5 + }, + "position": [ + 1.0, + -1.5, + 2.0 + ], + "intensity": 1500.0 + } + }, + { + "op": "add", + "id": "overview", + "object": { + "kind": "camera", + "position": [ + 0.9, + -1.4, + 1.05 + ], + "record_fps": 2, + "preview_fps": 1, + "camera": { + "resolution": [ + 640, + 360 + ], + "focal_length_mm": 32.0, + "horizontal_aperture_mm": 36.0, + "focus_distance_m": 1.8, + "clipping_range_m": [ + 0.01, + 100.0 + ] + }, + "orientation_wxyz": [ + 0.8258143506823128, + 0.5086950395094699, + 0.12767432761618716, + 0.2072662081801167 + ] + } + }, + { + "op": "set_presentation", + "presentation": { + "profile": "preview", + "budget": { + "max_cameras": 1, + "max_recording_bytes": 1073741824, + "min_free_bytes": 2147483648 + } + } + }, + { + "op": "set_observation", + "observation": { + "sample_interval_steps": 1, + "strict_start": true, + "record_contact_pairs": true + } + } + ] +} diff --git a/examples/usdcraft_sdk_guide/recipe-short.json b/examples/usdcraft_sdk_guide/recipe-short.json new file mode 100644 index 0000000..e2463ff --- /dev/null +++ b/examples/usdcraft_sdk_guide/recipe-short.json @@ -0,0 +1,176 @@ +{ + "schema": "simscene.scene_recipe.v2", + "description": "Generated short plate, CCD ball and support test.", + "operations": [ + { + "op": "add", + "id": "plate", + "object": { + "kind": "asset", + "dynamic": false, + "position": [ + 0.0, + 0.0, + 0.25 + ], + "asset_role": "short" + } + }, + { + "op": "add", + "id": "ball", + "object": { + "kind": "sphere", + "size": [ + 0.04, + 0.04, + 0.04 + ], + "position": [ + 0.3, + 0.0, + 0.65 + ], + "dynamic": true, + "collision": true, + "mass_kg": 0.05, + "physics": { + "enable_ccd": true + }, + "color": [ + 0.9, + 0.3, + 0.1 + ] + } + }, + { + "op": "add", + "id": "floor", + "object": { + "kind": "box", + "size": [ + 2.0, + 2.0, + 0.1 + ], + "position": [ + 0.0, + 0.0, + -0.05 + ], + "dynamic": false, + "collision": true, + "color": [ + 0.25, + 0.28, + 0.3 + ] + } + }, + { + "op": "add", + "id": "pedestal", + "object": { + "kind": "box", + "size": [ + 0.1, + 0.14, + 0.25 + ], + "position": [ + -0.15, + 0.0, + 0.125 + ], + "dynamic": false, + "collision": true, + "color": [ + 0.35, + 0.4, + 0.45 + ] + } + }, + { + "op": "add", + "id": "sky", + "object": { + "kind": "light", + "light": { + "type": "dome" + }, + "intensity": 500.0 + } + }, + { + "op": "add", + "id": "key", + "object": { + "kind": "light", + "light": { + "type": "sphere", + "radius_m": 0.5 + }, + "position": [ + 1.0, + -1.5, + 2.0 + ], + "intensity": 1500.0 + } + }, + { + "op": "add", + "id": "overview", + "object": { + "kind": "camera", + "position": [ + 0.9, + -1.4, + 1.05 + ], + "record_fps": 2, + "preview_fps": 1, + "camera": { + "resolution": [ + 640, + 360 + ], + "focal_length_mm": 32.0, + "horizontal_aperture_mm": 36.0, + "focus_distance_m": 1.8, + "clipping_range_m": [ + 0.01, + 100.0 + ] + }, + "orientation_wxyz": [ + 0.8258143506823128, + 0.5086950395094699, + 0.12767432761618716, + 0.2072662081801167 + ] + } + }, + { + "op": "set_presentation", + "presentation": { + "profile": "preview", + "budget": { + "max_cameras": 1, + "max_recording_bytes": 1073741824, + "min_free_bytes": 2147483648 + } + } + }, + { + "op": "set_observation", + "observation": { + "sample_interval_steps": 1, + "strict_start": true, + "record_contact_pairs": true + } + } + ] +} diff --git a/examples/usdcraft_two_drawer/README.md b/examples/usdcraft_two_drawer/README.md new file mode 100644 index 0000000..75b37d8 --- /dev/null +++ b/examples/usdcraft_two_drawer/README.md @@ -0,0 +1,71 @@ +# Two independently observed USDCraft drawers + +This editable example selects only `ds_R022_02`, a USDCraft cabinet with three +native rigid links and two prismatic joints. The source USD's geometry, +collision shapes, masses, limits and friction are preserved. The experiment +adds scheduled force drives: the lower drawer reaches 0.25 m while the upper +one is held near closed, then the upper reaches 0.35 m while the lower is held. +A control removes only the upper drawer's second scheduled drive. Both runs use +the same frozen acceptance case. In the tested control the lower drawer still +moved, while the upper remained near 0.0011 m. + +The data records every physics step, including path-keyed native PhysX joint +position and velocity, link poses and cooked centers of mass. The verifier +checks the independent native and frame-derived measurements, joint limits, +locked rotations, scheduled command readback, and run and evidence locks. A +separate paired mode checks that the control removes only the second drive and +that the observed control motion changes as expected. This +example does not claim passive triggering, general two-joint support, or robot +interaction. A cabinet using a different graph, units, joint type or drive must +be inspected and physically tested separately. + +The tested source is the one-file dependency closure of 40,680 bytes at pinned +revision `92f4e908415d7532a02661d6502ab49dc3aa33f9`; the asset payload is not +included in this repository. The licensed source metadata and file hash are in +`assets.lock.json`. Preserve upstream attribution and notices. The two-slider +physical test used Isaac Sim 6.2.0-rc.14, PhysX CPU, 60 Hz and seed 42. A +640×360 2 fps diagnostic recording is distinct from physical acceptance. + +## Rebuild on a simulation host + +Install this development version, the documented USD Python bindings and +FFmpeg. Configure the compatible Isaac launcher and probe the preparation +runtime as described in [asset preparation](../../docs/asset-catalog.md). Use +new writable locations outside the checkout, and point `SIMSCENE_V2_CONFIG` to +your own configured index, preparation directory and probe result. + +```bash +export SIMSCENE_HOME=/your/two-drawer/state +export SIMSCENE_CACHE=/your/two-drawer/cache +export SIMSCENE_V2_CONFIG=/your/two-drawer/v2.json +export SIMSCENE_ISAAC_PYTHON=/your/isaac-sim/python.sh +export SIMSCENE_PHYSICS_DEVICE=cpu + +python3 experiments/acquire_recipe_assets.py examples/usdcraft_two_drawer/assets.lock.json \ + --cache "$SIMSCENE_CACHE" --catalog-output /your/two-drawer/bindings.json +python3 experiments/apply_scene_recipe.py examples/usdcraft_two_drawer/recipe.json \ + --scene-id two_drawer --asset-catalog /your/two-drawer/bindings.json \ + --asset-lock examples/usdcraft_two_drawer/assets.lock.json \ + --save-directory /your/two-drawer/applied +python3 experiments/apply_scene_recipe.py examples/usdcraft_two_drawer/recipe-control.json \ + --scene-id two_drawer_control --asset-catalog /your/two-drawer/bindings.json \ + --asset-lock examples/usdcraft_two_drawer/assets.lock.json \ + --save-directory /your/two-drawer/control-applied +python3 experiments/freeze_recipe_case.py examples/usdcraft_two_drawer/case.json \ + --bindings /your/two-drawer/bindings.json \ + --asset-lock examples/usdcraft_two_drawer/assets.lock.json \ + --output /your/two-drawer/frozen-case.json +simscene run --scene two_drawer --steps 600 --seed 42 --case /your/two-drawer/frozen-case.json +simscene run --scene two_drawer_control --steps 600 --seed 42 --case /your/two-drawer/frozen-case.json +simscene verify --run "$SIMSCENE_HOME/runs/POSITIVE_RUN_ID" +simscene verify --run "$SIMSCENE_HOME/runs/CONTROL_RUN_ID" \ + --mode missing_second_joint_drive --reference-run "$SIMSCENE_HOME/runs/POSITIVE_RUN_ID" +``` + +Replace both IDs with the returned run IDs. The control is expected to fail the +single-run *positive* verifier because the second command and motion are +intentionally absent. Paired mode requires matching frozen inputs, source and +runtime, checks both evidence locks, and confirms that the first stage still +works. An arbitrary failed run cannot pass it. MCP clients can use `run_verify` +with the control `job_id`, mode `missing_second_joint_drive` and the positive +`reference_job_id`. diff --git a/examples/usdcraft_two_drawer/assets.lock.json b/examples/usdcraft_two_drawer/assets.lock.json new file mode 100644 index 0000000..58f7538 --- /dev/null +++ b/examples/usdcraft_two_drawer/assets.lock.json @@ -0,0 +1,116 @@ +{ + "schema": "simscene.selected_assets.v2", + "assets": { + "cabinet": { + "provider": "prepared", + "source_ref": { + "source_id": "usdcraft", + "asset_id": "ds_R022_02", + "revision": "92f4e908415d7532a02661d6502ab49dc3aa33f9", + "variant_id": null + }, + "profile_id": "articulated_prop_v2", + "profile_version": 1, + "parameters": { + "ccd": false, + "collision_method": "preserve", + "dynamic_friction": 0.5, + "proxy_tolerance_m": 0.002, + "restitution": 0.05, + "scale_mode": "preserve", + "source_physics_policy": "preserve_valid", + "static_friction": 0.6 + }, + "target": { + "engine": "physx", + "isaac_version": "6.2.0-rc.14+release.52805.02189a84.gl", + "platform": "linux-x86_64", + "usd_version": "0.25.11" + }, + "toolchain": { + "backend": "openusd", + "version": "0.25.11" + }, + "source_sha256": "e5070e0690c183629f0d24d2465d5ff0b53b88cd71b3682200650e05e009c7d0", + "source_closure_sha256": "3934e7dd6491d60e8db89ef41622cc9755bedca50099b68d9bb425ac6043519c", + "source_files": [ + { + "path": "rigid/kitchen_dining/R022_kitchen_drawer_unit/02_two_drawer_wide_unit/physx/model.usdc", + "size_bytes": 40680, + "sha256": "e5070e0690c183629f0d24d2465d5ff0b53b88cd71b3682200650e05e009c7d0" + } + ], + "previous_preparation": { + "prepared_id": "604117a7eca56e8899599e8498affea3276c86568489f7130a5e3e09e3cae9f0", + "manifest_sha256": "6bca11b6f12bda8370607985a92fb137a4125581c11a0b9d6ea5e599f878366a", + "source_manifest_sha256": "08ad6fd8f3bb13a3ed2e7160e7dcdda91cad1ee1a42cd4f2540c298e14b77170", + "scope": "informational; rebuild may change absolute provenance; no physics verdict reused" + }, + "source_record": { + "ref": { + "asset_id": "ds_R022_02", + "revision": "92f4e908415d7532a02661d6502ab49dc3aa33f9", + "source_id": "usdcraft", + "variant_id": null + }, + "title": "Two-Drawer Wide Unit", + "format": "usd", + "entry_path": "rigid/kitchen_dining/R022_kitchen_drawer_unit/02_two_drawer_wide_unit/physx/model.usdc", + "license": { + "basis": "pinned_USDCraft_asset_distribution_card", + "evidence": "declared", + "license": "Apache-2.0", + "notices_required": true, + "status": "known" + }, + "availability": { + "acquisition": { + "dependency_mode": "inspect_selected_usd_closure", + "files": [ + { + "path": "rigid/kitchen_dining/R022_kitchen_drawer_unit/02_two_drawer_wide_unit/physx/model.usdc", + "sha256": "e5070e0690c183629f0d24d2465d5ff0b53b88cd71b3682200650e05e009c7d0", + "size": null + } + ], + "files_complete": false, + "kind": "hf_usd_package", + "package_path": "rigid/kitchen_dining/R022_kitchen_drawer_unit/02_two_drawer_wide_unit", + "path": "rigid/kitchen_dining/R022_kitchen_drawer_unit/02_two_drawer_wide_unit/physx/model.usdc", + "repository": "nvidia/USDCraft-10K", + "revision": "92f4e908415d7532a02661d6502ab49dc3aa33f9" + }, + "estimated_download_bytes": null, + "files_complete": false, + "granularity": "dependency_closure", + "status": "declared" + }, + "provenance": { + "has_textures": { + "evidence": "declared", + "value": false + }, + "license_scope": "USDCraft-generated native distribution; not a license rule for arbitrary owner packages", + "metadata_revision": "92f4e908415d7532a02661d6502ab49dc3aa33f9", + "original_metadata": { + "category": "Kitchen Drawer Unit", + "category_id": "R022", + "group": "kitchen_dining", + "has_textures": "false", + "joint_count": "2", + "joint_types": "prismatic", + "object_id": "ds_R022_02", + "part_count": "3", + "path": "rigid/kitchen_dining/R022_kitchen_drawer_unit/02_two_drawer_wide_unit", + "physics_type": "articulated", + "physx_sha256": "e5070e0690c183629f0d24d2465d5ff0b53b88cd71b3682200650e05e009c7d0", + "prompt": "Wide kitchen drawer unit, 90 x 60 x 87 cm, in matte graphite-painted wood with two large drawers and a marble-look stone top. Long brass bar handles sit on each drawer, with a flat plinth base and smooth drawer fronts. To store pots and utensils, the user grips a long brass bar handle and pulls a drawer out; each drawer slides out up to 50 cm on prismatic metal rails; every part is a rigid body, with no deformable, cloth, soft-volume or dynamic rod parts.", + "title": "Two-Drawer Wide Unit" + }, + "repository": "nvidia/USDCraft-10K", + "unit_axis_evidence": "dataset_card_declared_meters_Z_up" + } + } + } + } +} diff --git a/examples/usdcraft_two_drawer/case.json b/examples/usdcraft_two_drawer/case.json new file mode 100644 index 0000000..d4f2299 --- /dev/null +++ b/examples/usdcraft_two_drawer/case.json @@ -0,0 +1,87 @@ +{ + "schema": "simscene.articulated_asset_two_joint.v1", + "schema_version": 1, + "mode": "driven", + "physics_dt_s": 0.016666666666666666, + "physics_device": "cpu", + "objects": { + "cabinet": { + "prepared_manifest_sha256": "${cabinet.manifest_sha256}", + "source_ref": "${cabinet.source_ref}", + "joints": { + "joint0": { + "joint_path": "/World/cabinet/Asset/Native/Joints/slide_lower", + "parent_body": "/World/cabinet/Asset/Native/Links/carcass", + "child_body": "/World/cabinet/Asset/Native/Links/lower_drawer", + "type": "prismatic", + "axis": "X", + "limits": [ + 0.0, + 0.5 + ], + "position_unit": "m", + "initial_position": 0.0, + "initial_tolerance": 0.001, + "coordinate_tolerance": 0.001, + "velocity_tolerance": 0.005, + "anchor_tolerance_m": 0.001, + "angular_tolerance_rad": 0.001 + }, + "joint1": { + "joint_path": "/World/cabinet/Asset/Native/Joints/slide_upper", + "parent_body": "/World/cabinet/Asset/Native/Links/carcass", + "child_body": "/World/cabinet/Asset/Native/Links/upper_drawer", + "type": "prismatic", + "axis": "X", + "limits": [ + 0.0, + 0.5 + ], + "position_unit": "m", + "initial_position": 0.0, + "initial_tolerance": 0.001, + "coordinate_tolerance": 0.001, + "velocity_tolerance": 0.005, + "anchor_tolerance_m": 0.001, + "angular_tolerance_rad": 0.001 + } + }, + "phases": [ + { + "joint_id": "joint0", + "command_step": 0, + "by_step": 240, + "target_position": 0.25, + "target_tolerance": 0.01, + "min_travel": 0.2, + "other_target_position": 0.0, + "other_target_tolerance": 0.01, + "max_other_drift": 0.01, + "stiffness": 2000.0, + "damping": 100.0, + "max_effort": 400.0, + "hold_command": { + "stiffness": 2000.0, + "damping": 100.0, + "max_effort": 400.0 + } + }, + { + "joint_id": "joint1", + "command_step": 300, + "by_step": 540, + "target_position": 0.35, + "target_tolerance": 0.01, + "min_travel": 0.3, + "other_target_position": 0.25, + "other_target_tolerance": 0.01, + "max_other_drift": 0.01, + "stiffness": 2000.0, + "damping": 100.0, + "max_effort": 400.0, + "hold_command": null + } + ] + } + } +} diff --git a/examples/usdcraft_two_drawer/recipe-control.json b/examples/usdcraft_two_drawer/recipe-control.json new file mode 100644 index 0000000..c9c5475 --- /dev/null +++ b/examples/usdcraft_two_drawer/recipe-control.json @@ -0,0 +1,152 @@ +{ + "schema": "simscene.scene_recipe.v2", + "description": "Control: same two-drawer scene with the second phase drive removed.", + "operations": [ + { + "op": "add", + "id": "cabinet", + "object": { + "kind": "asset", + "dynamic": true, + "position": [ + 0.0, + 0.0, + 0.005 + ], + "mechanism": { + "commands": [ + { + "joint_id": "joint0", + "trigger": { + "type": "at_step", + "physics_step": 0 + }, + "target_position": 0.25, + "position_unit": "m", + "stiffness": 2000.0, + "damping": 100.0, + "max_effort": 400.0 + }, + { + "joint_id": "joint1", + "trigger": { + "type": "at_step", + "physics_step": 0 + }, + "target_position": 0.0, + "position_unit": "m", + "stiffness": 2000.0, + "damping": 100.0, + "max_effort": 400.0 + } + ] + }, + "asset_role": "cabinet" + } + }, + { + "op": "add", + "id": "floor", + "object": { + "kind": "box", + "size": [ + 4.0, + 4.0, + 0.1 + ], + "position": [ + 0, + 0, + -0.05 + ], + "dynamic": false, + "collision": true, + "color": [ + 0.28, + 0.3, + 0.32 + ] + } + }, + { + "op": "add", + "id": "sky", + "object": { + "kind": "light", + "light": { + "type": "dome" + }, + "intensity": 500.0 + } + }, + { + "op": "add", + "id": "key", + "object": { + "kind": "light", + "light": { + "type": "sphere", + "radius_m": 0.6 + }, + "position": [ + 1.0, + -2.0, + 3.0 + ], + "intensity": 2000.0 + } + }, + { + "op": "add", + "id": "overview", + "object": { + "kind": "camera", + "position": [ + 1.8, + -3.0, + 1.6 + ], + "record_fps": 2, + "preview_fps": 1, + "camera": { + "resolution": [ + 640, + 360 + ], + "focal_length_mm": 35.0, + "horizontal_aperture_mm": 36.0, + "focus_distance_m": 3.6, + "clipping_range_m": [ + 0.01, + 100.0 + ] + }, + "orientation_wxyz": [ + 0.7806294210093381, + 0.5651231457929304, + 0.15653004960585754, + 0.21622183218656643 + ] + } + }, + { + "op": "set_presentation", + "presentation": { + "profile": "preview", + "budget": { + "max_cameras": 1, + "max_recording_bytes": 1073741824, + "min_free_bytes": 2147483648 + } + } + }, + { + "op": "set_observation", + "observation": { + "sample_interval_steps": 1, + "strict_start": true, + "record_contact_pairs": true + } + } + ] +} diff --git a/examples/usdcraft_two_drawer/recipe.json b/examples/usdcraft_two_drawer/recipe.json new file mode 100644 index 0000000..e4929b3 --- /dev/null +++ b/examples/usdcraft_two_drawer/recipe.json @@ -0,0 +1,164 @@ +{ + "schema": "simscene.scene_recipe.v2", + "description": "USDCraft two independent drawers with separately observed scheduled drives.", + "operations": [ + { + "op": "add", + "id": "cabinet", + "object": { + "kind": "asset", + "dynamic": true, + "position": [ + 0.0, + 0.0, + 0.005 + ], + "mechanism": { + "commands": [ + { + "joint_id": "joint0", + "trigger": { + "type": "at_step", + "physics_step": 0 + }, + "target_position": 0.25, + "position_unit": "m", + "stiffness": 2000.0, + "damping": 100.0, + "max_effort": 400.0 + }, + { + "joint_id": "joint1", + "trigger": { + "type": "at_step", + "physics_step": 0 + }, + "target_position": 0.0, + "position_unit": "m", + "stiffness": 2000.0, + "damping": 100.0, + "max_effort": 400.0 + }, + { + "joint_id": "joint1", + "trigger": { + "type": "at_step", + "physics_step": 300 + }, + "target_position": 0.35, + "position_unit": "m", + "stiffness": 2000.0, + "damping": 100.0, + "max_effort": 400.0 + } + ] + }, + "asset_role": "cabinet" + } + }, + { + "op": "add", + "id": "floor", + "object": { + "kind": "box", + "size": [ + 4.0, + 4.0, + 0.1 + ], + "position": [ + 0, + 0, + -0.05 + ], + "dynamic": false, + "collision": true, + "color": [ + 0.28, + 0.3, + 0.32 + ] + } + }, + { + "op": "add", + "id": "sky", + "object": { + "kind": "light", + "light": { + "type": "dome" + }, + "intensity": 500.0 + } + }, + { + "op": "add", + "id": "key", + "object": { + "kind": "light", + "light": { + "type": "sphere", + "radius_m": 0.6 + }, + "position": [ + 1.0, + -2.0, + 3.0 + ], + "intensity": 2000.0 + } + }, + { + "op": "add", + "id": "overview", + "object": { + "kind": "camera", + "position": [ + 1.8, + -3.0, + 1.6 + ], + "record_fps": 2, + "preview_fps": 1, + "camera": { + "resolution": [ + 640, + 360 + ], + "focal_length_mm": 35.0, + "horizontal_aperture_mm": 36.0, + "focus_distance_m": 3.6, + "clipping_range_m": [ + 0.01, + 100.0 + ] + }, + "orientation_wxyz": [ + 0.7806294210093381, + 0.5651231457929304, + 0.15653004960585754, + 0.21622183218656643 + ] + } + }, + { + "op": "set_presentation", + "presentation": { + "profile": "preview", + "budget": { + "max_cameras": 1, + "max_recording_bytes": 1073741824, + "min_free_bytes": 2147483648 + } + } + }, + { + "op": "set_observation", + "observation": { + "sample_interval_steps": 1, + "strict_start": true, + "record_contact_pairs": true + } + } + ] +} diff --git a/experiments/acquire_recipe_assets.py b/experiments/acquire_recipe_assets.py index 16c74ed..4d3bad3 100644 --- a/experiments/acquire_recipe_assets.py +++ b/experiments/acquire_recipe_assets.py @@ -35,13 +35,45 @@ def _prepared(selection,config,limits,timeout,receipts): from simscene.recipes.io import validate_rebuilt ref=selection['source_ref'];record=None if 'generation' in selection: + import hashlib + from importlib.resources import files from simscene.generation import jobs as generation + from simscene.recipes.io import _generation_intent intent=selection['generation'] - if intent.get('generator')!='sand3d' or intent.get('seed')!=0: - raise ValueError('unsupported generated recipe; only reviewed trusted Sand3D templates supported') + if not isinstance(intent,dict):raise ValueError('invalid generated recipe intent') + generator=intent.get('generator') + if generator=='sand3d': + from simscene.generation.sand3d import COMMIT,parameters + expected_source='local-sand3d' + runtime_key='generation_runtime' + elif generator=='usdcraft_sdk' and intent.get('generation_contract_version')==3: + from simscene.generation.usdcraft_sdk import COMMIT,RECIPE,parameters + if intent.get('recipe_id')!=RECIPE:raise ValueError('unsupported trusted USDCraft SDK recipe') + expected_source='local-usdcraft-sdk' + runtime_key='usdcraft_generation_runtime' + else:raise ValueError('unsupported generated recipe backend or contract') + if (type(intent.get('seed')) is not int or intent['seed']!=0 or ref.get('source_id')!=expected_source + or ref.get('asset_id')!=intent.get('recipe_id')): + raise ValueError('generated recipe identity or seed differs from its pinned source') + # Compare trusted template, backend-specific normalization and the + # configured runtime before executing anything. A source lock cannot + # select a different backend merely by choosing its recipe ID. + recipe=intent['recipe_id'] + normalized=parameters(recipe,intent.get('parameters')) + runtime_path=config.get(runtime_key) + if not runtime_path or not Path(runtime_path).is_file() or Path(runtime_path).stat().st_size>65536: + raise ValueError('generation_runtime_unavailable: configure the pinned generation runtime') + runtime=json.loads(Path(runtime_path).read_text()) + template=files('simscene.generation').joinpath('templates/'+recipe+'.py').read_bytes() + identity={'recipe_id':recipe,'parameters':normalized,'seed':0,'toolchain':runtime, + 'template_sha256':hashlib.sha256(template).hexdigest()} + if generator=='usdcraft_sdk':identity['generation_contract_version']=3 + actual=_generation_intent(identity,{'generator':generator,'reviewed_commit':COMMIT}) + if actual!=intent:raise ValueError('configured generator runtime or trusted template differs from the portable lock') # No programs from the lock are executable. jobs.start validates the one # shipped recipe and requires an explicitly configured reviewed runtime. - receipt=generation.start(intent['recipe_id'],intent['parameters'],'recipe-generate-'+uuid.uuid4().hex,config=config) + receipt=generation.start(intent['recipe_id'],intent['parameters'],'recipe-generate-'+uuid.uuid4().hex, + config=config,expected_intent=intent) receipts.append(dict(receipt,role_phase='generation')) generated=wait_job(receipt,generation,config,timeout) ref=generated['result']['asset_ref'] diff --git a/experiments/mobilitygen_jetbot/README.md b/experiments/mobilitygen_jetbot/README.md new file mode 100644 index 0000000..3db2b90 --- /dev/null +++ b/experiments/mobilitygen_jetbot/README.md @@ -0,0 +1,140 @@ +# Experimental MobilityGen Jetbot probe + +This standalone tool runs a fixed Jetbot route and a matched zero-command +control. It is **not** connected to `scene_apply`, `simulation_start`, the +SimScene job registry, or a general robot motion API. It has been exercised +only on the specific Isaac Sim 6.2 RC build and single NVIDIA Jetbot asset +locked here. It does not establish obstacle avoidance, automatic mapping, +arbitrary robot compatibility, or physical-robot safety. + +The tool freezes its case and code, copies eight verified USD files into a new +output directory, and runs both modes through the existing per-user SimScene +GPU queue. The stage uses CPU PhysX; headless Isaac can still use a GPU. +Both simulations perform 30 settling steps and then exactly 600 task steps at +1/60 s. The positive follows a fixed straight 0.8 m route on an explicitly +defined flat occupancy map. Once the 0.08 m goal threshold is reached, it +holds zero wheel targets through the remaining steps. The control uses the +same setup and horizon with wheel targets always zero. +The scene explicitly authors `TGS` and `enableExternalForcesEveryIteration`; +the worker records USD readback after setup. This is not an independent +readback of the internal PhysX solver configuration. +The frozen case seeds Python's `random` and NumPy with `20261116`; the metadata +records both seeds. This does not claim that every Isaac or PhysX internal +source of nondeterminism is controlled. + +The case's `asset_relative_path` preserves the original probe's path as +provenance; this tool resolves the actual input from `--asset` and verifies +the copied files against `asset-lock.json`. + +The source Jetbot has two caster physics material relationships that USD +cannot resolve through their instance references. The worker explicitly +deinstances those two scene prims and restores their bindings to the existing +source-authored material; it records the changes. It also changes both source +wheel drives from unlimited effort to an experimental 1 N·m maximum in the +scene, then reads native PhysX drive type, maximum effort, stiffness and +damping before and after the task. Both native angular drive damping values +must be 1.0 within 0.00001; the source USD damping is about 0.017453294 in +its authored angular units. The source USD files are not modified. +These repairs and the drive-target adapter are part of this experiment, not +claims about the stock MobilityGen example. The effective PhysX caster +friction was not independently read back from a native tensor. + +Each sample includes the native chassis pose, center-of-mass linear and angular +velocity readbacks, wheel positions and velocity readbacks, +commanded and native-readback wheel velocity targets, physics-step callback +count, goal distance, map status and observed contact actor pairs. A paired +checker verifies the fixed route, native drive values, initial pose and raw +state agreement, step continuity, wall bounds, raw contact actors against +flags, the complete horizon and terminal zero targets. During the task, every +sliding 60-step window must contain at least one ground contact for each wheel; +this does not establish uninterrupted contact, force direction or no +penetration. The positive must progress at least 0.3 m along the fixed route +while a wheel target is nonzero and show sampled position changes on both +wheels. This is a timing association, not proof that the command caused the +motion. Short-angle changes are observational: inferring total rotation would +require the unverified assumption of no unobserved full turns between samples. + +The velocity fields are preserved as **raw readbacks**. Diagnostic experiments +found systematic differences between reported velocities and finite differences +of link/COM positions, orientations and wheel positions, including after the +solver change reduced those differences. The paired audit consequently reports +`native_velocity_consistency: not_verified`. Bounded or matching initial raw +readbacks do not prove the robot was stationary. Zero wheel targets, including +at the end of the run, do not establish that the wheels or chassis stopped. + +## Requirements and acquisition + +* A Linux Isaac Sim installation whose `VERSION` is exactly + `6.2.0-rc.14+release.52805.02189a84.gl`; selected installed MobilityGen, + controller and MDL source hashes, including the launcher itself, must also + match `runtime-lock.json`. + This pins selected files, not the entire simulator or all transitive MDL + dependencies. The local Isaac installation and binaries remain a trusted + boundary, not a fully authenticated environment. Other Isaac versions are + rejected pending their own tests. +* An exact local copy of the eight Jetbot files listed in `asset-lock.json`. + Do not add them to the repository. NVIDIA-provided assets and MDL files use + the [Isaac Sim Additional Software and Materials License](https://docs.isaacsim.omniverse.nvidia.com/latest/common/license-isaac-sim-additional.html), + not the Apache license of the example Python sources. +* The existing SimScene `src/simscene/worker/gpu_queue.py`. An alternative + location can be passed with `--queue-script`, but its hash must match the + pinned queue. A changed queue or tool file requires explicit requalification + and a new lock; the tool does not silently update either. + +If the asset is not already available, this optional command fetches only the +eight pinned objects to a **new directory outside the repository**. The total +is 31,942,504 bytes; the hard budget is 48 MB total and 35 MB per object. +Each URL, response, size and hash is checked and recorded in `fetch-log.jsonl`. +Failures leave their own evidence and require a fresh output directory. + +```bash +python3 experiments/mobilitygen_jetbot/fetch_assets.py --output /path/to/new-jetbot-assets +``` + +## Run and verify + +From the repository root, provide the local Isaac launcher, the root USD of the +locked asset, and a **new output path outside the repository**: + +```bash +python3 experiments/mobilitygen_jetbot/run_pair.py \ + --isaac-python /path/to/isaac-sim/python.sh \ + --asset /path/to/new-jetbot-assets/jetbot.usda \ + --output /path/to/new-jetbot-pair +``` + +Use `--queue-script /path/to/gpu_queue.py` if this tool is copied away from the +SimScene repository. `SIMSCENE_GPU` may select the Isaac device; the queue is +still the host's per-user cooperative lock. The launcher waits for each run; +it is not a durable detached job. Both modes are attempted even if one fails. +It never reuses an existing output path. `runs/positive/` and `runs/zero/` +retain logs, queue exit receipts, metadata, and partial telemetry on failure; +each run receives an evidence lock immediately after it exits, including +`result.json` and any missing files. A failed or incomplete run is marked +partial. `audit.json` records the pair verdict and evidence hashes. These +local SHA-256 locks detect later changes but are not signatures and do not +establish authenticity against an actor able to alter both data and locks. +`runtime/` and +`assets/` are snapshots of the locked inputs, not source edits. + +An independent read-only recheck can use the saved verifier and, if the Isaac +installation moved, a launcher at a new path with matching pinned files: + +```bash +python3 /path/to/new-jetbot-pair/runtime/audit_output.py /path/to/new-jetbot-pair \ + --isaac-python /path/to/isaac-sim/python.sh +``` + +## CPU checks + +```bash +cd experiments/mobilitygen_jetbot +python3 -m unittest -v test_contract test_evaluate test_sixty test_pair test_fetch \ + test_review_regressions test_new_guards test_redirect test_reaudit +``` + +The checks cover asset path/hash failures, runtime locks, native finite effort +and target readback, incomplete or discontinuous samples, collision flags, +terminal zeroing, paired input mismatches, evidence tampering, launcher +identity, and a redirect that must not contact its target. CPU +tests alone do not establish that an Isaac simulation ran successfully. diff --git a/experiments/mobilitygen_jetbot/asset-lock.json b/experiments/mobilitygen_jetbot/asset-lock.json new file mode 100644 index 0000000..115b7e7 --- /dev/null +++ b/experiments/mobilitygen_jetbot/asset-lock.json @@ -0,0 +1,57 @@ +{ + "asset": "jetbot.usda", + "files": [ + { + "bytes": 13508, + "path": "jetbot.usda", + "sha256": "d483e768ee585047e3179df4e05865a7584521d08fc20cfc15fe6a92b6ee42f5", + "url": "https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/Isaac/6.2/Isaac/Robots_Multiphysics/NVIDIA/Jetbot/jetbot.usda" + }, + { + "bytes": 12645, + "path": "payloads/base.usda", + "sha256": "4b98f56568a6620e829bc04505a146f884e63b2a1417050b9632c095fb4d8312", + "url": "https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/Isaac/6.2/Isaac/Robots_Multiphysics/NVIDIA/Jetbot/payloads/base.usda" + }, + { + "bytes": 6572, + "path": "payloads/Physics/physx.usda", + "sha256": "4001f5a8b0142baf800727510d91bfe407f99406eb282ef7ab286b7a18b76a70", + "url": "https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/Isaac/6.2/Isaac/Robots_Multiphysics/NVIDIA/Jetbot/payloads/Physics/physx.usda" + }, + { + "bytes": 307106, + "path": "payloads/instances.usda", + "sha256": "acfb9b01f6c28018926c5632ce04e47d509bfad8c19a2fdf4ab9d410610abe3a", + "url": "https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/Isaac/6.2/Isaac/Robots_Multiphysics/NVIDIA/Jetbot/payloads/instances.usda" + }, + { + "bytes": 4324, + "path": "payloads/robot.usda", + "sha256": "8e3cb0e8d46b29354a70e727a008bfbc8cfe82f8becf87b6333874f3b2ebc356", + "url": "https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/Isaac/6.2/Isaac/Robots_Multiphysics/NVIDIA/Jetbot/payloads/robot.usda" + }, + { + "bytes": 7689, + "path": "payloads/Physics/physics.usda", + "sha256": "1d18be0666499b8de9e26552e6f1c1f982a6ceecf5c110c70097902bf56697f4", + "url": "https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/Isaac/6.2/Isaac/Robots_Multiphysics/NVIDIA/Jetbot/payloads/Physics/physics.usda" + }, + { + "bytes": 146529, + "path": "payloads/materials.usda", + "sha256": "24156a1e9ccadb36abd0ced650b57604881e89d878fda2727ec7c515c79069b4", + "url": "https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/Isaac/6.2/Isaac/Robots_Multiphysics/NVIDIA/Jetbot/payloads/materials.usda" + }, + { + "bytes": 31444131, + "path": "payloads/geometries.usd", + "sha256": "be03d338e1c19883d98328d16ed5802736e7d96e6f65f6d162e0e6dc88a5d0f8", + "url": "https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/Isaac/6.2/Isaac/Robots_Multiphysics/NVIDIA/Jetbot/payloads/geometries.usd" + } + ], + "license": "NVIDIA Isaac Sim Additional Software and Materials License", + "license_url": "https://docs.isaacsim.omniverse.nvidia.com/latest/common/license-isaac-sim-additional.html", + "schema": "simscene.mobilitygen_jetbot.asset-lock.v1", + "total_bytes": 31942504 +} diff --git a/experiments/mobilitygen_jetbot/asset_lock.py b/experiments/mobilitygen_jetbot/asset_lock.py new file mode 100644 index 0000000..6be60c7 --- /dev/null +++ b/experiments/mobilitygen_jetbot/asset_lock.py @@ -0,0 +1,90 @@ +"""Verify and snapshot the exact selected Jetbot USD dependency files.""" +import hashlib +from pathlib import Path, PurePosixPath +import re +import shutil + + +def verify_runtime(isaac_python, lock): + launcher = Path(isaac_python).expanduser().resolve() + root = launcher.parent + if not launcher.is_file() or not (root / 'VERSION').is_file(): + raise ValueError('Isaac launcher or VERSION is missing') + if not isinstance(lock.get('launcher_sha256'), str) or sha256(launcher) != lock['launcher_sha256']: + raise ValueError('Isaac launcher differs from the tested launcher hash') + if (root / 'VERSION').read_text().strip() != lock.get('isaac_version'): + raise ValueError('Isaac version differs from the tested runtime') + files = lock.get('files') + if not isinstance(files, dict) or not files or len(files) > 100: + raise ValueError('invalid runtime source lock') + for name, expected in files.items(): + if (not isinstance(name, str) or not name or '\\' in name or name.startswith('/') or + any(part in ('', '.', '..') for part in name.split('/')) or + not isinstance(expected, str) or re.fullmatch('[0-9a-f]{64}', expected) is None): + raise ValueError('unsafe runtime dependency lock') + path = root.joinpath(*PurePosixPath(name).parts) + if not path.is_file() or not path.resolve().is_relative_to(root) or sha256(path) != expected: + raise ValueError('runtime dependency missing or changed: ' + name) + return root + + +def sha256(path): + digest = hashlib.sha256() + with Path(path).open('rb') as stream: + for chunk in iter(lambda: stream.read(1024 * 1024), b''): + digest.update(chunk) + return digest.hexdigest() + + +def verify_asset_files(asset_path, lock): + asset = Path(asset_path).expanduser().absolute() + if (not isinstance(lock, dict) or lock.get('asset') != asset.name or + asset.is_symlink() or not asset.is_file()): + raise ValueError('asset root is missing, symlinked, or differs from the lock') + base = asset.parent + base_real = base.resolve() + entries = lock.get('files') + if not isinstance(entries, list) or not entries or len(entries) > 50: + raise ValueError('invalid asset file list') + found = {} + total = 0 + for entry in entries: + name = entry.get('path') if isinstance(entry, dict) else None + if (not isinstance(name, str) or not name or '\\' in name or name.startswith('/') or + any(part in ('', '.', '..') for part in name.split('/'))): + raise ValueError('unsafe asset path') + relative = PurePosixPath(name) + if relative.is_absolute() or name in found: + raise ValueError('duplicate or absolute asset path') + size = entry.get('bytes') + digest = entry.get('sha256') + if (type(size) is not int or not 0 < size <= 35_000_000 or + not isinstance(digest, str) or re.fullmatch('[0-9a-f]{64}', digest) is None): + raise ValueError('invalid asset size or digest') + path = base.joinpath(*relative.parts) + cursor = base + for part in relative.parts: + cursor = cursor / part + if cursor.is_symlink(): + raise ValueError('symlink in locked asset path') + if (not path.is_file() or not path.resolve().is_relative_to(base_real) or + path.stat().st_size != size or sha256(path) != digest): + raise ValueError('locked asset missing or hash/size mismatch: ' + name) + found[name] = path + total += size + if total != lock.get('total_bytes') or total > 48_000_000 or lock['asset'] not in found: + raise ValueError('asset closure total or root differs from lock') + return found + + +def snapshot_assets(asset_path, lock, destination): + files = verify_asset_files(asset_path, lock) + destination = Path(destination) + destination.mkdir(parents=True, exist_ok=False) + for relative, source in files.items(): + target = destination.joinpath(*PurePosixPath(relative).parts) + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, target) + result = destination / lock['asset'] + verify_asset_files(result, lock) + return result diff --git a/experiments/mobilitygen_jetbot/audit_output.py b/experiments/mobilitygen_jetbot/audit_output.py new file mode 100644 index 0000000..6d4914b --- /dev/null +++ b/experiments/mobilitygen_jetbot/audit_output.py @@ -0,0 +1,103 @@ +"""Recheck one standalone pair and its frozen inputs without changing them.""" +import argparse +import json +from pathlib import Path +import sys + +from asset_lock import sha256, verify_asset_files, verify_runtime +from pair_check import check_pair +from evidence_lock import verify_evidence_lock + +TOOL_FILES = ('run_pair.py', 'fetch_assets.py', 'worker.py', 'evaluate.py', 'pair_check.py', 'asset_lock.py', 'evidence_lock.py', + 'audit_output.py', 'fixed_case.json', 'asset-lock.json', 'runtime-lock.json') + + +def _load_run(path): + return {'metadata': json.loads((path / 'metadata.json').read_text()), + 'rows': [json.loads(line) for line in (path / 'telemetry.jsonl').read_text().splitlines()], + 'process': json.loads((path / 'process-exit.json').read_text()), + 'result': json.loads((path / 'result.json').read_text()), + 'log': (path / 'worker.log').read_text(errors='replace')} + + +def audit_output(output, isaac_python=None): + root = Path(output).expanduser().resolve() + runtime = root / 'runtime' + manifest = json.loads((root / 'run-manifest.json').read_text()) + if manifest.get('schema') != 'simscene.mobilitygen_jetbot.run.v1': + raise ValueError('unsupported run manifest') + locks = manifest.get('evidence_locks') + if not isinstance(locks, dict) or set(locks) != {'positive', 'zero'}: + raise ValueError('evidence locks missing or incomplete') + statuses = {mode: verify_evidence_lock(root / 'runs' / mode, mode, locks[mode]) + for mode in ('positive', 'zero')} + if any(status['partial'] for status in statuses.values()): + return {'passed': False, 'partial': True, + 'errors': ['one or both runs contain partial evidence'], 'evidence_locks': statuses} + expected = manifest.get('runtime_files_sha256') + if not isinstance(expected, dict) or set(expected) != set(TOOL_FILES) | {'gpu_queue.py'}: + raise ValueError('frozen runtime file list differs from the contract') + for name, digest in expected.items(): + file = runtime / name + if file.is_symlink() or not file.is_file() or sha256(file) != digest: + raise ValueError('frozen runtime file changed: ' + name) + source_lock_path = runtime / 'tool-lock.json' + if not source_lock_path.is_file() or sha256(source_lock_path) != manifest.get('source_tool_lock_sha256'): + raise ValueError('tool lock changed or missing') + source_lock = json.loads(source_lock_path.read_text()) + if (source_lock.get('files_sha256') != {name: expected[name] for name in TOOL_FILES} or + source_lock.get('queue_sha256') != expected['gpu_queue.py']): + raise ValueError('runtime files do not match the frozen tool lock') + asset_lock = json.loads((runtime / 'asset-lock.json').read_text()) + verify_asset_files(root / 'assets' / asset_lock['asset'], asset_lock) + launcher = Path(isaac_python or manifest['isaac_python']).expanduser().resolve() + if not launcher.is_file() or sha256(launcher) != manifest['isaac_python_sha256']: + raise ValueError('Isaac launcher missing or changed') + runtime_lock = json.loads((runtime / 'runtime-lock.json').read_text()) + verify_runtime(launcher, runtime_lock) + case = json.loads((runtime / 'fixed_case.json').read_text()) + positive, control = _load_run(root / 'runs/positive'), _load_run(root / 'runs/zero') + for mode, item in [('positive', positive), ('zero', control)]: + metadata, receipt = item['metadata'], item['process'] + if receipt.get('schema') != 'simscene.process_exit.v1' or receipt.get('run_id') != mode: + raise ValueError('queue receipt missing or belongs to a different run') + if (metadata.get('case') != case or metadata.get('case_sha256') != expected['fixed_case.json'] or + metadata.get('script_sha256') != expected['worker.py'] or metadata.get('script_name') != 'worker.py' or + metadata.get('asset_sha256') != sha256(root / 'assets' / asset_lock['asset']) or + metadata.get('isaac_version') != runtime_lock['isaac_version']): + raise ValueError('run metadata differs from frozen inputs') + result = check_pair(positive, control) + for mode, item in [('positive', positive), ('zero', control)]: + expected_result = result['checks'][mode] + recorded = item['result'] + expected_keys = ('passed', 'errors', 'samples', 'displacement_m', 'peak_displacement_m', + 'max_step_displacement_m', 'final_goal_distance_m', + 'forward_progress_during_nonzero_targets_m', 'sampled_wheel_short_angle_changes_rad') + if (not isinstance(recorded, dict) or any(recorded.get(k) != expected_result.get(k) for k in expected_keys) + or recorded.get('terminal_status') != item['metadata'].get('terminal_status') + or (mode == 'positive' and recorded.get('first_arrival_step') != expected_result.get('first_arrival_step'))): + result['passed'] = False + result['errors'].append(mode + ' recorded result differs from recomputed evidence') + result.update(schema='simscene.mobilitygen_jetbot.pair-audit.v1', + scope='one fixed straight route, one Jetbot, one host; no safety or integration claim', + runs={mode: {name + '_sha256': sha256(root / 'runs' / mode / name) + for name in ('metadata.json', 'telemetry.jsonl', 'process-exit.json', 'worker.log')} + for mode in ('positive', 'zero')}) + return result + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('output', help='completed standalone pair directory') + parser.add_argument('--isaac-python', help='equivalent tested Isaac python.sh if installation moved') + args = parser.parse_args() + try: + result = audit_output(args.output, args.isaac_python) + except Exception as error: + result = {'passed': False, 'errors': [f'{type(error).__name__}: {error}']} + print(json.dumps(result, indent=2, sort_keys=True)) + return 0 if result['passed'] else 1 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/experiments/mobilitygen_jetbot/evaluate.py b/experiments/mobilitygen_jetbot/evaluate.py new file mode 100644 index 0000000..b82385c --- /dev/null +++ b/experiments/mobilitygen_jetbot/evaluate.py @@ -0,0 +1,194 @@ +"""Independent checks of the recorded fixed-route experiment, with fail-closed fields.""" +import json +import math +import sys + + +def evaluate_horizon(samples, mode): + result = evaluate(samples, mode) + errors = list(result.get('errors', [])) + if errors: + return result + if len(samples) != 601: + errors.append('fixed 600-step horizon is incomplete') + for item in samples: + readback = item.get('native_wheel_targets_rad_s') if isinstance(item, dict) else None + command = item.get('wheel_targets_rad_s') if isinstance(item, dict) else None + if not isinstance(readback, list) or len(readback) != 2 or not isinstance(command, list) or len(command) != 2 or any( + isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) + for value in readback): + errors.append('native target readback is malformed') + break + if any(abs(a - b) > 1e-5 for a, b in zip(readback, command)): + errors.append('native target readback differs from command') + break + if mode == 'positive': + first_arrival = next((i for i, item in enumerate(samples) if item.get('arrived') is True), None) + if first_arrival is None or any(abs(v) > 1e-9 for item in samples[first_arrival + 1:] + for v in item['wheel_targets_rad_s']): + errors.append('terminal state did not hold zero targets') + result['first_arrival_step'] = first_arrival + result.update(passed=not errors, errors=errors) + return result + + +def validate_drive_snapshot(snapshot): + errors = [] + if not isinstance(snapshot, dict) or snapshot.get('drive_type_codes') != [1, 1]: + errors.append('native wheel drive types must both be force') + for key in ('max_effort_nm', 'stiffness', 'damping'): + value = snapshot.get(key) if isinstance(snapshot, dict) else None + if not isinstance(value, list) or len(value) != 2 or any( + isinstance(x, bool) or not isinstance(x, (int, float)) or not math.isfinite(x) for x in value): + errors.append(f'native {key} missing, nonfinite or wrong shape') + continue + if key == 'max_effort_nm' and any(abs(x - 1.) > 1e-6 for x in value): + errors.append('native drive efforts differ from fixed 1 N m bound') + if key == 'stiffness' and any(abs(x) > 1e-6 for x in value): + errors.append('velocity drives must have zero stiffness') + if key == 'damping' and any(abs(x - 1.) > 1e-5 for x in value): + errors.append('native wheel damping differs from frozen 1.0 gain') + return errors + + +def evaluate(samples, mode): + errors = [] + if mode not in ("positive", "zero") or not isinstance(samples, list) or len(samples) < 2: + return {"passed": False, "errors": ["invalid mode or insufficient samples"]} + vectors = {"base_position_m": 3, "base_orientation_wxyz": 4, + "base_com_linear_velocity_m_s": 3, "base_angular_velocity_rad_s": 3, + "wheel_positions_rad": 2, "wheel_targets_rad_s": 2, "wheel_velocities_rad_s": 2} + flags = ("arrived", "obstacle_collision", "map_out_of_bounds", "map_collision", "ground_contact") + initial_callback = samples[0].get('physics_callback_count') if isinstance(samples[0], dict) else None + if type(initial_callback) is not int: + errors.append('missing initial physics callback count') + for index, item in enumerate(samples): + if not isinstance(item, dict) or item.get("step") != index: + errors.append(f"nonconsecutive or malformed sample {index}") + continue + if type(initial_callback) is not int or item.get('physics_callback_count') != initial_callback + index: + errors.append(f"physics callback discontinuity at {index}") + time_s = item.get('time_s') + if (isinstance(time_s, bool) or not isinstance(time_s, (int, float)) or not math.isfinite(time_s) + or abs(time_s - index / 60) > 1e-8): + errors.append(f'invalid physical time at {index}') + for key, size in vectors.items(): + value = item.get(key) + if not isinstance(value, list) or len(value) != size or any( + isinstance(x, bool) or not isinstance(x, (int, float)) or not math.isfinite(x) for x in value + ): + errors.append(f"invalid {key} at {index}") + for key in flags: + if type(item.get(key)) is not bool: + errors.append(f"missing or invalid {key} at {index}") + distance = item.get("goal_distance_m") + if isinstance(distance, bool) or not isinstance(distance, (int, float)) or not math.isfinite(distance): + errors.append(f"invalid goal distance at {index}") + pairs = item.get('contact_actor_pairs') + if (not isinstance(pairs, list) or any(not isinstance(pair, list) or len(pair) != 2 or + any(not isinstance(path, str) or not path.startswith('/World/') for path in pair) for pair in pairs)): + errors.append(f'invalid contact actor pairs at {index}') + continue + ground = False + obstacle = False + for pair in pairs: + robot = [path for path in pair if path == '/World/Jetbot' or path.startswith('/World/Jetbot/')] + if not robot: + errors.append(f'contact pair lacks robot actor at {index}') + continue + for path in pair: + if path in robot: + continue + if path == '/World/Ground' or path.startswith('/World/Ground/'): + ground = True + elif any(path == '/World/Wall' + side or path.startswith('/World/Wall' + side + '/') + for side in ('East', 'West', 'North', 'South')): + obstacle = True + else: + errors.append(f'unexpected non-robot contact actor at {index}') + if item.get('ground_contact') is not ground or item.get('obstacle_collision') is not obstacle: + errors.append(f'contact flags disagree with raw actors at {index}') + if errors: + return {"passed": False, "errors": errors} + for item in samples: + pos = item["base_position_m"] + measured_distance = math.hypot(0.8 - pos[0], pos[1]) + if abs(measured_distance - item["goal_distance_m"]) > 1e-5: + errors.append("goal distance does not agree with measured position") + break + if item['arrived'] is not (measured_distance <= .08): + errors.append('arrival flag disagrees with measured position') + break + if abs(math.sqrt(sum(x * x for x in item['base_orientation_wxyz'])) - 1.) > 1e-4: + errors.append('chassis quaternion is not normalized') + break + if any(x["obstacle_collision"] or x["map_out_of_bounds"] or x["map_collision"] for x in samples): + errors.append("obstacle collision or out of map") + task_contacts = samples[1:] + if not task_contacts or any(not any(row['ground_contact'] for row in task_contacts[start:start + 60]) + for start in range(max(1, len(task_contacts) - 59))): + errors.append('task has a one-second window without ground contact') + for side in ('left', 'right'): + wheel = '/World/Jetbot/' + side + '_wheel' + def wheel_touches_ground(row): + return any(any(p == wheel or p.startswith(wheel + '/') for p in pair) and + any(p == '/World/Ground' or p.startswith('/World/Ground/') for p in pair) + for pair in row['contact_actor_pairs']) + if not task_contacts or any(not any(wheel_touches_ground(row) for row in task_contacts[start:start + 60]) + for start in range(max(1, len(task_contacts) - 59))): + errors.append(side + ' wheel has a task window without ground contact') + if any(abs(row['base_position_m'][0]) >= 1.9 or abs(row['base_position_m'][1]) >= 1.9 + for row in samples): + errors.append('native chassis origin is outside the frozen inner wall boundary') + start, end = samples[0]["base_position_m"], samples[-1]["base_position_m"] + displacement = math.hypot(end[0] - start[0], end[1] - start[1]) + peak_displacement = max(math.hypot(x['base_position_m'][0] - start[0], + x['base_position_m'][1] - start[1]) for x in samples) + max_step_displacement = max(math.dist(a['base_position_m'], b['base_position_m']) + for a, b in zip(samples, samples[1:])) + if max_step_displacement > 1.0 / 60.0: + errors.append('position jumps exceed 1 m/s at the fixed 1/60 s step') + if any(abs(q) > 8.0 + 1e-5 for sample in samples for q in sample['wheel_targets_rad_s']): + errors.append('wheel target exceeds the frozen limit') + commanded_progress = None + sampled_wheel_changes = None + if mode == "positive": + if not samples[-1]["arrived"] or samples[-1]["goal_distance_m"] > 0.08 or displacement < 0.3: + errors.append("positive run did not physically reach the goal") + first_arrival = next((index for index, item in enumerate(samples) if item['arrived']), len(samples)) + driven_steps = sum(any(abs(q) > .01 for q in sample['wheel_targets_rad_s']) + for sample in samples[1:first_arrival + 1]) + if any(abs(q) > 1e-9 for q in samples[0]['wheel_targets_rad_s']) or driven_steps < 10: + errors.append('positive run lacks ten nonzero task drive steps before arrival') + commanded_progress = sum(samples[i]['base_position_m'][0] - samples[i - 1]['base_position_m'][0] + for i in range(1, min(first_arrival + 1, len(samples))) + if any(abs(q) > .01 for q in samples[i]['wheel_targets_rad_s'])) + if commanded_progress < .3: + errors.append('less than 0.3 m forward progress was observed during nonzero targets') + sampled_wheel_changes = [sum(abs(math.atan2(math.sin(samples[i]['wheel_positions_rad'][wheel] - + samples[i - 1]['wheel_positions_rad'][wheel]), + math.cos(samples[i]['wheel_positions_rad'][wheel] - + samples[i - 1]['wheel_positions_rad'][wheel]))) + for i in range(1, min(first_arrival + 1, len(samples)))) + for wheel in (0, 1)] + if any(change < .1 for change in sampled_wheel_changes): + errors.append('positive run lacks sampled position changes on both wheels') + else: + if any(abs(q) > 1e-9 for sample in samples for q in sample["wheel_targets_rad_s"]): + errors.append("zero control issued a nonzero wheel target") + if peak_displacement > 0.04 or any(sample["arrived"] for sample in samples): + errors.append("zero control moved or reached the goal") + return {"passed": not errors, "errors": errors, "samples": len(samples), + "displacement_m": displacement, "peak_displacement_m": peak_displacement, + "max_step_displacement_m": max_step_displacement, + "final_goal_distance_m": samples[-1]["goal_distance_m"], + "forward_progress_during_nonzero_targets_m": commanded_progress, + "sampled_wheel_short_angle_changes_rad": sampled_wheel_changes} + + +if __name__ == "__main__": + with open(sys.argv[1], encoding="utf8") as stream: + rows = [json.loads(line) for line in stream] + result = evaluate_horizon(rows, sys.argv[2]) + print(json.dumps(result, indent=2, sort_keys=True)) + raise SystemExit(0 if result["passed"] else 1) diff --git a/experiments/mobilitygen_jetbot/evidence_lock.py b/experiments/mobilitygen_jetbot/evidence_lock.py new file mode 100644 index 0000000..738d9df --- /dev/null +++ b/experiments/mobilitygen_jetbot/evidence_lock.py @@ -0,0 +1,64 @@ +"""Freeze and verify local run files; hashes do not provide authenticity.""" +import json +import os +from pathlib import Path +import tempfile + +from asset_lock import sha256 + +FILES = ('telemetry.jsonl', 'metadata.json', 'result.json', 'process-exit.json', 'worker.log') + + +def create_evidence_lock(root, mode, returncode): + root = Path(root) + if mode not in ('positive', 'zero') or (returncode is not None and type(returncode) is not int): + raise ValueError('invalid run mode or exit code') + files = {} + for name in FILES: + path = root / name + if path.is_symlink(): + raise ValueError('evidence file is a symlink: ' + name) + files[name] = {'bytes': path.stat().st_size, 'sha256': sha256(path)} if path.is_file() else None + record = {'schema': 'simscene.mobilitygen_jetbot.evidence-lock.v1', 'mode': mode, + 'returncode': returncode, 'partial': returncode != 0 or any(v is None for v in files.values()), + 'files': files} + target = root / 'evidence-lock.json' + with tempfile.NamedTemporaryFile(mode='w', encoding='utf8', dir=root, prefix='.evidence-lock-', delete=False) as f: + temporary = Path(f.name) + json.dump(record, f, indent=2, sort_keys=True) + f.write('\n'); f.flush(); os.fsync(f.fileno()) + try: + # Linking an already-fsynced temp file is atomic and never replaces evidence. + os.link(temporary, target) + finally: + temporary.unlink(missing_ok=True) + return sha256(target) + + +def verify_evidence_lock(root, mode, expected_digest): + root = Path(root) + target = root / 'evidence-lock.json' + if target.is_symlink() or not target.is_file() or sha256(target) != expected_digest: + raise ValueError('evidence lock missing or changed') + record = json.loads(target.read_text()) + files = record.get('files') + if (record.get('schema') != 'simscene.mobilitygen_jetbot.evidence-lock.v1' or + record.get('mode') != mode or type(record.get('partial')) is not bool or + not isinstance(files, dict) or set(files) != set(FILES)): + raise ValueError('invalid evidence lock') + code = record.get('returncode') + if code is not None and type(code) is not int: + raise ValueError('invalid locked process exit code') + if record['partial'] != (code != 0 or any(v is None for v in files.values())): + raise ValueError('inconsistent partial evidence status') + for name, expected in files.items(): + path = root / name + if path.is_symlink(): + raise ValueError('evidence file became a symlink: ' + name) + if expected is None: + if path.exists(): + raise ValueError('missing evidence appeared after locking: ' + name) + elif (not isinstance(expected, dict) or set(expected) != {'bytes', 'sha256'} or + not path.is_file() or path.stat().st_size != expected['bytes'] or sha256(path) != expected['sha256']): + raise ValueError('evidence missing or changed: ' + name) + return record diff --git a/experiments/mobilitygen_jetbot/fetch_assets.py b/experiments/mobilitygen_jetbot/fetch_assets.py new file mode 100644 index 0000000..9a6df52 --- /dev/null +++ b/experiments/mobilitygen_jetbot/fetch_assets.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python3 +"""Fetch only the eight pinned Jetbot files into a new directory.""" +import argparse +import hashlib +import json +from pathlib import Path, PurePosixPath +import sys +from urllib.request import HTTPRedirectHandler, Request, build_opener + +from asset_lock import sha256, verify_asset_files + +HERE = Path(__file__).resolve().parent +SOURCE = ('https://omniverse-content-production.s3-us-west-2.amazonaws.com/' + 'Assets/Isaac/6.2/Isaac/Robots_Multiphysics/NVIDIA/Jetbot/') + + +class _RejectRedirects(HTTPRedirectHandler): + def redirect_request(self, request, response, code, message, headers, new_url): + return None + + +def urlopen(request, timeout): + # Default urllib follows redirects before a content hash is available. + # Refuse them entirely so no cross-origin request can be issued. + return build_opener(_RejectRedirects()).open(request, timeout=timeout) + + +def fetch(destination): + destination = Path(destination).expanduser().absolute() + if destination.exists() or destination.is_symlink(): + raise ValueError('destination must be a new directory') + repository = next((parent for parent in HERE.parents if (parent / '.git').exists()), None) + if repository and destination.resolve().is_relative_to(repository): + raise ValueError('do not place NVIDIA assets in the source repository') + tool_lock = json.loads((HERE / 'tool-lock.json').read_text()) + if sha256(HERE / 'asset-lock.json') != tool_lock['files_sha256']['asset-lock.json']: + raise ValueError('asset lock differs from the frozen tool lock') + lock = json.loads((HERE / 'asset-lock.json').read_text()) + entries = lock.get('files') + if (not isinstance(entries, list) or len(entries) != 8 or + lock.get('total_bytes') != sum(item.get('bytes', -1) for item in entries) or + lock['total_bytes'] > 48_000_000): + raise ValueError('invalid asset budget or file list') + seen = set() + for item in entries: + rel = item.get('path') + if (not isinstance(rel, str) or not rel or '\\' in rel or rel.startswith('/') or + any(part in ('', '.', '..') for part in rel.split('/')) or rel in seen or + item.get('url') != SOURCE + rel or type(item.get('bytes')) is not int or + not 0 < item['bytes'] <= 35_000_000): + raise ValueError('unsafe or unexpected asset source') + seen.add(rel) + if lock.get('asset') not in seen: + raise ValueError('asset root not listed') + destination.mkdir(parents=True, exist_ok=False) + for item in entries: + record = {'path': item['path'], 'url': item['url'], 'status': 'error'} + try: + target = destination.joinpath(*PurePosixPath(item['path']).parts) + target.parent.mkdir(parents=True, exist_ok=True) + request = Request(item['url'], headers={'User-Agent': 'simscene-jetbot-probe/1'}) + with urlopen(request, timeout=30) as response: + length = response.headers.get('Content-Length') + if length is None or int(length) != item['bytes']: + raise ValueError(f'unexpected Content-Length: {length}') + digest, count = hashlib.sha256(), 0 + with target.open('xb') as output: + while True: + block = response.read(min(1024 * 1024, item['bytes'] - count + 1)) + if not block: + break + count += len(block) + if count > item['bytes']: + raise ValueError('response exceeds frozen size') + digest.update(block) + output.write(block) + if count != item['bytes'] or digest.hexdigest() != item['sha256']: + raise ValueError('download size or hash differs from lock') + record.update(status='ok', bytes=count, sha256=digest.hexdigest(), + etag=response.headers.get('ETag'), last_modified=response.headers.get('Last-Modified')) + except Exception as error: + record['error'] = f'{type(error).__name__}: {error}' + raise + finally: + with (destination / 'fetch-log.jsonl').open('a', encoding='utf8') as log: + log.write(json.dumps(record, sort_keys=True) + '\n') + verify_asset_files(destination / lock['asset'], lock) + return destination / lock['asset'] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--output', required=True, help='new asset directory outside the repository') + args = parser.parse_args() + try: + asset = fetch(args.output) + print(json.dumps({'asset': str(asset), 'files': 8, 'bytes': 31_942_504})) + return 0 + except Exception as error: + print(f'{type(error).__name__}: {error}', file=sys.stderr) + return 1 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/experiments/mobilitygen_jetbot/fixed_case.json b/experiments/mobilitygen_jetbot/fixed_case.json new file mode 100644 index 0000000..d387e47 --- /dev/null +++ b/experiments/mobilitygen_jetbot/fixed_case.json @@ -0,0 +1,41 @@ +{ + "schema": "mobility-probe.fixed-case.60hz.v2", + "asset_relative_path": "assets/Isaac/Robots_Multiphysics/NVIDIA/Jetbot/jetbot.usda", + "physics_device": "cpu", + "physics_dt_s": 0.016666666666666666, + "solver_type": "TGS", + "enable_external_forces_every_iteration": true, + "settling_steps": 30, + "task_step_budget": 600, + "seed": 20261116, + "wheel_max_effort_nm": 1.0, + "native_wheel_damping": [1.0, 1.0], + "native_wheel_damping_tolerance": 0.00001, + "spawn_position_m": [0.0, 0.0, 0.05], + "spawn_orientation_wxyz": [1.0, 0.0, 0.0, 0.0], + "initial_orientation_tolerance_rad": 0.02, + "initial_xy_tolerance_m": 0.02, + "initial_z_range_m": [0.02, 0.06], + "initial_pair_wheel_position_tolerance_rad": 0.001, + "initial_pair_wheel_velocity_tolerance_rad_s": 0.001, + "initial_linear_speed_tolerance_m_s": 0.05, + "initial_angular_speed_tolerance_rad_s": 0.1, + "initial_pair_linear_velocity_tolerance_m_s": 0.005, + "initial_pair_angular_velocity_tolerance_rad_s": 0.02, + "minimum_driven_steps": 10, + "goal_xy_m": [0.8, 0.0], + "arrival_distance_m": 0.08, + "target_speed_m_s": 0.16, + "maximum_yaw_rate_rad_s": 1.0, + "maximum_wheel_speed_rad_s": 8.0, + "lookahead_m": 0.30, + "wheel_names": ["left_wheel_joint", "right_wheel_joint"], + "wheel_radius_m": 0.03, + "wheel_base_m": 0.1125, + "map_resolution_m": 0.05, + "map_shape": [80, 80], + "map_origin_xyyaw": [-2.0, -2.0, 0.0], + "map_border_cells": 2, + "floor_contact_required": true, + "physical_walls_inner_edge_m": 1.9 +} diff --git a/experiments/mobilitygen_jetbot/pair_check.py b/experiments/mobilitygen_jetbot/pair_check.py new file mode 100644 index 0000000..3002a78 --- /dev/null +++ b/experiments/mobilitygen_jetbot/pair_check.py @@ -0,0 +1,152 @@ +"""Independent, read-only checks of the positive/zero physical evidence.""" +import math +from evaluate import evaluate_horizon, validate_drive_snapshot + + +def check_pair(positive, control): + errors = [] + a, b = positive['metadata'], control['metadata'] + checks = {'positive': evaluate_horizon(positive['rows'], 'positive'), + 'zero': evaluate_horizon(control['rows'], 'zero')} + if not all(item['passed'] for item in checks.values()): + return {'passed': False, 'errors': ['one or both physical checks failed'], 'checks': checks, + 'native_velocity_consistency': 'not_verified'} + keys = ('case_sha256', 'script_sha256', 'asset_sha256', 'isaac_version', 'case', + 'observed_physics_device', 'observed_physics_dt_s', 'wheel_dof_indices', 'dof_names', 'path_xy_m', + 'native_dof_paths', 'native_link_paths', + 'stage_physics_repairs', 'stage_drive_effort_overrides', 'observed_solver_settings_usd') + for key in keys: + if a.get(key) is None or a.get(key) != b.get(key): + errors.append('paired metadata mismatch: ' + key) + if a.get('mode') != 'positive' or b.get('mode') != 'zero': + errors.append('incorrect run modes') + case = a.get('case') + if (not isinstance(case, dict) or case.get('settling_steps') != 30 or + any(item['rows'][0].get('physics_callback_count') != 30 for item in (positive, control))): + errors.append('first task sample must follow exactly 30 physics callbacks') + expected_solver = {'solver_type': 'TGS', 'enable_external_forces_every_iteration': True} + if (not isinstance(case, dict) or any(case.get(k) != v for k, v in expected_solver.items()) or + any(m.get('observed_solver_settings_usd') != expected_solver for m in (a, b))): + errors.append('frozen solver settings were not read back from the USD scene') + if (not isinstance(case, dict) or case.get('native_wheel_damping') != [1., 1.] or + case.get('native_wheel_damping_tolerance') != 1e-5): + errors.append('fixed native wheel damping and tolerance are missing') + path = a.get('path_xy_m') + route = [[0., 0.], [.8, 0.]] + if (not isinstance(path, list) or len(path) != 2 or any( + not isinstance(point, list) or len(point) != 2 or any( + isinstance(x, bool) or not isinstance(x, (int, float)) or not math.isfinite(x) for x in point) + for point in path) or any(math.dist(actual, expected) > 1e-6 + for actual, expected in zip(path, route))): + errors.append('recorded path is not the frozen straight route') + if (not isinstance(case, dict) or type(case.get('seed')) is not int or + any(m.get('seed') != case['seed'] or m.get('seeded_rngs') != ['python.random', 'numpy.random'] + for m in (a, b))): + errors.append('fixed seed or seeded RNG declarations are missing or inconsistent') + names, indices = a.get('dof_names'), a.get('wheel_dof_indices') + wanted = case.get('wheel_names') if isinstance(case, dict) else None + if (not isinstance(names, list) or len(names) != 2 or len(set(names)) != 2 or + not isinstance(indices, list) or len(indices) != 2 or any(type(i) is not int or i not in (0, 1) for i in indices) + or len(set(indices)) != 2 or not isinstance(wanted, list) or len(wanted) != 2 or + [names[i] for i in indices] != wanted): + errors.append('wheel DOF indices do not map frozen wheel names to native names') + else: + paths, links = a.get('native_dof_paths'), a.get('native_link_paths') + if (not isinstance(paths, list) or len(paths) != 2 or len(set(paths)) != 2 or + [paths[i] for i in indices] != ['/World/Jetbot/chassis/' + name for name in wanted] or + not isinstance(links, list) or len(links) != 3 or set(links) != { + '/World/Jetbot/chassis', '/World/Jetbot/left_wheel', '/World/Jetbot/right_wheel'}): + errors.append('native wheel or link paths differ from frozen robot topology') + if (a.get('observed_physics_device') != 'cpu' or + abs(a.get('observed_physics_dt_s', 0) - 1 / 60) > 1e-9): + errors.append('unexpected physics device or timestep') + if any(m.get('requested_steps') != 600 or m.get('actual_task_steps') != 600 for m in (a, b)): + errors.append('fixed horizon was not completed') + if a.get('terminal_status') != 'arrived' or b.get('terminal_status') != 'zero_target_duration_complete': + errors.append('unexpected terminal status') + repairs = a.get('stage_physics_repairs') + expected_casters = {'/World/Jetbot/chassis/geometry/caster_ball_' + end + '/caster_ball_front' + for end in ('front', 'back')} + if (not isinstance(repairs, list) or len(repairs) != 2 or + {x.get('collider') for x in repairs} != expected_casters or any( + x.get('original_resolved_targets') != [] or + x.get('new_material') != '/World/Jetbot/caster_material' or + abs(x.get('source_coefficients', {}).get('dynamic_friction', -1) - .01) > 1e-6 for x in repairs)): + errors.append('caster repair evidence missing or inconsistent') + overrides = a.get('stage_drive_effort_overrides') + expected_joints = {'/World/Jetbot/chassis/' + side + '_wheel_joint' for side in ('left', 'right')} + if (not isinstance(overrides, list) or len(overrides) != 2 or + {x.get('joint_path') for x in overrides} != expected_joints or any( + x.get('original_max_effort_nm') != 'infinity' or x.get('scene_max_effort_nm') != 1.0 or + x.get('type') != 'force' for x in overrides)): + errors.append('wheel effort overrides missing or inconsistent') + for item in (positive, control): + for key in ('native_drive_before', 'native_drive_after'): + errors.extend(validate_drive_snapshot(item['metadata'].get(key))) + if item['process'].get('exit_code') != 0: + errors.append('nonzero queued simulator exit') + if not all(text in item['log'] for text in ('Simulation App Startup Complete', + 'isaacsim.replicator.experimental.mobility_gen-0.5.0', + 'isaacsim.replicator.mobility_gen.examples-0.4.1')): + errors.append('expected extension startup missing') + snapshots = [m.get(key) for m in (a, b) for key in ('native_drive_before', 'native_drive_after')] + if all(not validate_drive_snapshot(s) for s in snapshots): + reference = snapshots[0] + if any(s['drive_type_codes'] != reference['drive_type_codes'] or any( + abs(x - y) > 1e-6 for key in ('max_effort_nm', 'stiffness', 'damping') + for x, y in zip(s[key], reference[key])) for s in snapshots[1:]): + errors.append('native wheel drive configuration differs across runs or task boundaries') + if positive['rows'] and control['rows']: + first, second = positive['rows'][0], control['rows'][0] + start_distance = math.dist(first['base_position_m'], second['base_position_m']) + quat_dot = abs(sum(x * y for x, y in zip(first['base_orientation_wxyz'], second['base_orientation_wxyz']))) + if start_distance > .001 or abs(quat_dot - 1.0) > .0001: + errors.append('initial chassis poses differ') + if any(abs(v) > .05 for row in (first, second) for v in row['wheel_velocities_rad_s']): + errors.append('initial raw wheel velocity readback exceeds fixed bound') + def quaternion_angle(left, right): + dot = abs(sum(x * y for x, y in zip(left, right))) + norm = math.sqrt(sum(x*x for x in left) * sum(x*x for x in right)) + return 2 * math.acos(min(1., max(0., dot / norm))) + target = case.get('spawn_orientation_wxyz') if isinstance(case, dict) else None + if (not isinstance(target, list) or len(target) != 4 or any( + isinstance(x, bool) or not isinstance(x, (int, float)) or not math.isfinite(x) for x in target) + or abs(math.sqrt(sum(x*x for x in target)) - 1.) > 1e-6): + errors.append('frozen initial orientation is invalid') + elif any(quaternion_angle(row['base_orientation_wxyz'], target) > case.get('initial_orientation_tolerance_rad', .02) + for row in (first, second)): + errors.append('initial chassis orientation differs from frozen spawn orientation') + if quaternion_angle(first['base_orientation_wxyz'], second['base_orientation_wxyz']) > .01: + errors.append('paired initial chassis orientations differ') + spawn = case.get('spawn_position_m') if isinstance(case, dict) else None + z_range = case.get('initial_z_range_m') if isinstance(case, dict) else None + if (not isinstance(spawn, list) or len(spawn) != 3 or not isinstance(z_range, list) or len(z_range) != 2 or + any(isinstance(x, bool) or not isinstance(x, (int, float)) or not math.isfinite(x) + for x in spawn + z_range) or z_range[0] >= z_range[1]): + errors.append('frozen initial position bounds are invalid') + elif any(math.hypot(row['base_position_m'][0] - spawn[0], row['base_position_m'][1] - spawn[1]) > + case.get('initial_xy_tolerance_m', .02) or + not z_range[0] <= row['base_position_m'][2] <= z_range[1] for row in (first, second)): + errors.append('initial chassis position differs from frozen spawn bounds') + paired_fields = [('wheel_positions_rad', 'initial_pair_wheel_position_tolerance_rad', .001), + ('wheel_velocities_rad_s', 'initial_pair_wheel_velocity_tolerance_rad_s', .001), + ('base_com_linear_velocity_m_s', 'initial_pair_linear_velocity_tolerance_m_s', .005), + ('base_angular_velocity_rad_s', 'initial_pair_angular_velocity_tolerance_rad_s', .02)] + for field, limit, default in paired_fields: + if math.dist(first[field], second[field]) > case.get(limit, default): + errors.append('paired initial state differs: ' + field) + for field, limit, default in [('base_com_linear_velocity_m_s', 'initial_linear_speed_tolerance_m_s', .05), + ('base_angular_velocity_rad_s', 'initial_angular_speed_tolerance_rad_s', .1)]: + if any(math.sqrt(sum(x*x for x in row[field])) > case.get(limit, default) for row in (first, second)): + errors.append('initial raw chassis velocity readback exceeds bound: ' + field) + if any(abs(value) > 1e-9 for row in (first, second) + for field in ('wheel_targets_rad_s', 'native_wheel_targets_rad_s') for value in row[field]): + errors.append('initial drive target is not zero') + else: + start_distance = None + errors.append('missing initial states') + return {'passed': not errors, 'errors': errors, 'checks': checks, 'initial_chassis_difference_m': start_distance, + 'native_velocity_consistency': 'not_verified', + 'final_wheel_velocities_rad_s': { + name: item['rows'][-1]['wheel_velocities_rad_s'] if item['rows'] else None + for name, item in [('positive', positive), ('zero', control)]}} diff --git a/experiments/mobilitygen_jetbot/run_pair.py b/experiments/mobilitygen_jetbot/run_pair.py new file mode 100644 index 0000000..93b50ba --- /dev/null +++ b/experiments/mobilitygen_jetbot/run_pair.py @@ -0,0 +1,140 @@ +#!/usr/bin/env python3 +"""Run the fixed experimental Jetbot pair via SimScene's per-user queue.""" +import argparse +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile + +from asset_lock import sha256, snapshot_assets, verify_asset_files, verify_runtime +from audit_output import TOOL_FILES +from evidence_lock import create_evidence_lock + +HERE = Path(__file__).resolve().parent + + +def _write_manifest(path, value): + with tempfile.NamedTemporaryFile('w', encoding='utf8', dir=path.parent, prefix='.manifest-', delete=False) as f: + temporary = Path(f.name) + json.dump(value, f, indent=2, sort_keys=True) + f.write('\n'); f.flush(); os.fsync(f.fileno()) + try: + os.replace(temporary, path) + finally: + temporary.unlink(missing_ok=True) + + +def _validate_tool_lock(queue): + lock = json.loads((HERE / 'tool-lock.json').read_text()) + expected = lock.get('files_sha256') + names = set(TOOL_FILES) + if lock.get('schema') != 'simscene.mobilitygen_jetbot.tool-lock.v1' or not isinstance(expected, dict) or set(expected) != names: + raise ValueError('tool lock is missing required files') + for name, digest in expected.items(): + path = HERE / name + if not path.is_file() or path.is_symlink() or sha256(path) != digest: + raise ValueError('tool file differs from its frozen lock: ' + name) + if not queue.is_file() or sha256(queue) != lock.get('queue_sha256'): + raise ValueError('queue script differs from the pinned SimScene GPU queue') + return lock + + +def run_pair(isaac_python, asset_path, output, queue_script=None): + launcher = Path(isaac_python).expanduser().resolve() + asset = Path(asset_path).expanduser().absolute() + output = Path(output).expanduser().absolute() + default_queue = HERE.parent.parent / 'src/simscene/worker/gpu_queue.py' + queue = Path(queue_script).expanduser().resolve() if queue_script else default_queue.resolve() + lock = _validate_tool_lock(queue) + runtime_lock = json.loads((HERE / 'runtime-lock.json').read_text()) + verify_runtime(launcher, runtime_lock) + asset_lock = json.loads((HERE / 'asset-lock.json').read_text()) + verify_asset_files(asset, asset_lock) + if output.exists() or output.is_symlink(): + raise ValueError('output must be a new path; prior evidence is never overwritten') + output_real = output.resolve() + repository = next((parent for parent in HERE.parents if (parent / '.git').exists()), None) + if repository and output_real.is_relative_to(repository): + raise ValueError('output must be outside the repository; source assets are not repository files') + if output_real.is_relative_to(asset.parent.resolve()): + raise ValueError('output must be outside the input asset tree') + output.mkdir(parents=True, exist_ok=False) + runtime = output / 'runtime' + runtime.mkdir() + try: + for name in TOOL_FILES: + shutil.copyfile(HERE / name, runtime / name) + shutil.copyfile(HERE / 'tool-lock.json', runtime / 'tool-lock.json') + shutil.copyfile(queue, runtime / 'gpu_queue.py') + snapshot = snapshot_assets(asset, asset_lock, output / 'assets') + files = {name: sha256(runtime / name) for name in (*TOOL_FILES, 'gpu_queue.py')} + for name in TOOL_FILES: + if files[name] != lock['files_sha256'][name]: + raise ValueError('runtime snapshot changed while copying: ' + name) + if files['gpu_queue.py'] != lock['queue_sha256']: + raise ValueError('queue changed while copying') + manifest = {'schema': 'simscene.mobilitygen_jetbot.run.v1', 'isaac_python': str(launcher), + 'isaac_python_sha256': sha256(launcher), 'runtime_files_sha256': files, + 'source_tool_lock_sha256': sha256(HERE / 'tool-lock.json'), + 'input_asset_root': str(asset), 'experimental': True, 'evidence_locks': {}} + _write_manifest(output / 'run-manifest.json', manifest) + launches = [] + env = os.environ.copy() + env.pop('PYTHONEXE', None) + env['PYTHONUNBUFFERED'] = '1' + for mode in ('positive', 'zero'): + run = output / 'runs' / mode + run.mkdir(parents=True) + (run / 'queue-state.json').write_text(json.dumps({'state': 'queued'}) + '\n') + command = [sys.executable, str(runtime / 'gpu_queue.py'), str(run / 'queue-state.json'), + str(launcher), '--no-ros-env', str(runtime / 'worker.py'), '--mode', mode, + '--asset', str(snapshot), '--output', str(run)] + print(f'Starting {mode} through the SimScene GPU queue', file=sys.stderr, flush=True) + with (run / 'worker.log').open('xb') as log: + try: + code = subprocess.run(command, stdout=log, stderr=subprocess.STDOUT, env=env, check=False).returncode + except OSError as error: + code = None + (run / 'launch-error.txt').write_text(f'{type(error).__name__}: {error}\n') + launches.append({'mode': mode, 'returncode': code}) + manifest['evidence_locks'][mode] = create_evidence_lock(run, mode, code) + _write_manifest(output / 'run-manifest.json', manifest) + (output / 'launch-summary.json').write_text(json.dumps(launches, indent=2) + '\n') + audit = subprocess.run([sys.executable, str(runtime / 'audit_output.py'), str(output), + '--isaac-python', str(launcher)], capture_output=True, text=True, check=False) + (output / 'audit.json').write_text(audit.stdout) + if audit.stderr: + (output / 'audit-stderr.txt').write_text(audit.stderr) + try: + result = json.loads(audit.stdout) + except ValueError: + result = {'passed': False, 'errors': ['audit produced invalid JSON']} + if audit.returncode != 0 and result.get('passed'): + result = {'passed': False, 'errors': ['audit process exited unsuccessfully']} + result['output'] = str(output) + return result + except BaseException as error: + (output / 'launch-error.txt').write_text(f'{type(error).__name__}: {error}\n') + raise + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--isaac-python', required=True, help='tested Isaac Sim python.sh') + parser.add_argument('--asset', required=True, help='locally acquired, locked jetbot.usda') + parser.add_argument('--output', required=True, help='new output path outside the repository') + parser.add_argument('--queue-script', help='copy of the pinned SimScene gpu_queue.py') + args = parser.parse_args() + try: + result = run_pair(args.isaac_python, args.asset, args.output, args.queue_script) + except (OSError, ValueError) as error: + result = {'passed': False, 'errors': [f'{type(error).__name__}: {error}']} + print(json.dumps(result, indent=2, sort_keys=True)) + return 0 if result['passed'] else 1 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/experiments/mobilitygen_jetbot/runtime-lock.json b/experiments/mobilitygen_jetbot/runtime-lock.json new file mode 100644 index 0000000..41c6b65 --- /dev/null +++ b/experiments/mobilitygen_jetbot/runtime-lock.json @@ -0,0 +1,19 @@ +{ + "files": { + "exts/isaacsim.replicator.experimental.mobility_gen/config/extension.toml": "5652b5a4e0518f6a6e379552936fc6d8306cee1aca122034c4e384f520cb787a", + "exts/isaacsim.replicator.experimental.mobility_gen/isaacsim/replicator/experimental/mobility_gen/bindings/_path_planner.cpython-312-x86_64-linux-gnu.so": "952eee7e366bb962f8d718b635611387e3fda282a6a3a0778835e4437f767918", + "exts/isaacsim.replicator.experimental.mobility_gen/isaacsim/replicator/experimental/mobility_gen/impl/occupancy_map.py": "8b49092b00b4e2a01c2923a8bb1f7a82fdf6fa5db5c98c28f655e7a786ecef68", + "exts/isaacsim.replicator.experimental.mobility_gen/isaacsim/replicator/experimental/mobility_gen/impl/path_planner.py": "8db343e1cb9ae0d409b6cd542938f808f4a8d99a60a803c56e9ac65f7321bd57", + "exts/isaacsim.replicator.experimental.mobility_gen/isaacsim/replicator/experimental/mobility_gen/impl/scenario.py": "8f485b544670fc19824c3d8a7ec99e9a3b222d6249118bc0c49a1436daad2c10", + "exts/isaacsim.replicator.mobility_gen.examples/config/extension.toml": "b9b0160b74c413dd8c8abd4951300c26e4cecbd2ae5f17b04e09910022dc1293", + "exts/isaacsim.replicator.mobility_gen.examples/isaacsim/replicator/mobility_gen/examples/robots.py": "f7cb3149ba2665f32db7b2d63544907d7284be43227ccd121a5348972da7f582", + "exts/isaacsim.replicator.mobility_gen.examples/isaacsim/replicator/mobility_gen/examples/scenarios.py": "6e06f1504a4f015f10af4568770f54f74eb868de03c1cbf9987e6831a2025948", + "exts/isaacsim.robot.experimental.wheeled_robots/isaacsim/robot/experimental/wheeled_robots/controllers/differential_controller.py": "99e1733c3cdb92b17e65f8e22264e8ba0de9e9a7b79186e6a790e8f9a3c984db", + "kit/mdl/core/Base/OmniGlass.mdl": "cc3d21e95997fb16d9435982c4f0a14f3438b1705d2e2b3d3e75454e5b329d61", + "kit/mdl/core/Base/OmniPBR.mdl": "d384fc800f120e3cad1b7ca8837f9c554f9c34343d194813fca27caa493001f2" + }, + "isaac_version": "6.2.0-rc.14+release.52805.02189a84.gl", + "launcher_sha256": "02e191f61075faf8757c3295941e5ed937a2b121b6be8f0d6b7a8899e6815fec", + "schema": "simscene.mobilitygen_jetbot.runtime-lock.v1", + "scope": "selected MobilityGen implementation and MDL files, not the full Isaac runtime" +} diff --git a/experiments/mobilitygen_jetbot/test_contract.py b/experiments/mobilitygen_jetbot/test_contract.py new file mode 100644 index 0000000..d7f77e0 --- /dev/null +++ b/experiments/mobilitygen_jetbot/test_contract.py @@ -0,0 +1,69 @@ +import hashlib +import tempfile +import unittest +from pathlib import Path + +from asset_lock import verify_asset_files, verify_runtime + + +class AssetLockTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.root = Path(self.tmp.name) + (self.root / 'jetbot.usda').write_bytes(b'root') + (self.root / 'payloads').mkdir() + (self.root / 'payloads/physics.usda').write_bytes(b'physics') + self.lock = {'asset': 'jetbot.usda', 'total_bytes': 11, 'files': [ + {'path': 'jetbot.usda', 'bytes': 4, 'sha256': hashlib.sha256(b'root').hexdigest()}, + {'path': 'payloads/physics.usda', 'bytes': 7, 'sha256': hashlib.sha256(b'physics').hexdigest()}, + ]} + + def tearDown(self): + self.tmp.cleanup() + + def test_exact_files_and_hashes_admitted(self): + self.assertEqual(set(verify_asset_files(self.root / 'jetbot.usda', self.lock)), + {'jetbot.usda', 'payloads/physics.usda'}) + + def test_corrupt_or_missing_file_rejected(self): + (self.root / 'payloads/physics.usda').write_bytes(b'changed') + with self.assertRaises(ValueError): + verify_asset_files(self.root / 'jetbot.usda', self.lock) + (self.root / 'payloads/physics.usda').unlink() + with self.assertRaises(ValueError): + verify_asset_files(self.root / 'jetbot.usda', self.lock) + + def test_path_escape_duplicates_and_symlinks_rejected(self): + self.lock['files'][1]['path'] = '../other.usda' + with self.assertRaises(ValueError): + verify_asset_files(self.root / 'jetbot.usda', self.lock) + self.lock['files'][1]['path'] = 'jetbot.usda' + with self.assertRaises(ValueError): + verify_asset_files(self.root / 'jetbot.usda', self.lock) + self.lock['files'][1]['path'] = 'payloads/physics.usda' + (self.root / 'payloads/physics.usda').unlink() + (self.root / 'payloads/physics.usda').symlink_to(self.root / 'jetbot.usda') + with self.assertRaises(ValueError): + verify_asset_files(self.root / 'jetbot.usda', self.lock) + + +class RuntimeLockTests(unittest.TestCase): + def test_selected_runtime_version_and_source_hashes(self): + with tempfile.TemporaryDirectory() as name: + root = Path(name) + (root / 'python.sh').write_text('launcher') + (root / 'VERSION').write_text('release-v1') + (root / 'module.py').write_text('source') + lock = {'isaac_version': 'release-v1', 'launcher_sha256': hashlib.sha256(b'launcher').hexdigest(), 'files': { + 'module.py': hashlib.sha256(b'source').hexdigest()}} + self.assertEqual(verify_runtime(root / 'python.sh', lock), root) + (root / 'module.py').write_text('changed') + with self.assertRaises(ValueError): + verify_runtime(root / 'python.sh', lock) + lock['files'] = {'../escape': '0' * 64} + with self.assertRaises(ValueError): + verify_runtime(root / 'python.sh', lock) + + +if __name__ == '__main__': + unittest.main() diff --git a/experiments/mobilitygen_jetbot/test_evaluate.py b/experiments/mobilitygen_jetbot/test_evaluate.py new file mode 100644 index 0000000..e475d3b --- /dev/null +++ b/experiments/mobilitygen_jetbot/test_evaluate.py @@ -0,0 +1,63 @@ +import unittest + +from evaluate import evaluate + + +def sample(step, x, *, target=0.0, arrived=None, collision=False): + return { + "step": step, + "physics_callback_count": step + 30, + "time_s": step / 60, + "base_position_m": [x, 0.0, 0.04], + "base_orientation_wxyz": [1.0, 0.0, 0.0, 0.0], + "base_com_linear_velocity_m_s": [0.0, 0.0, 0.0], + "base_angular_velocity_rad_s": [0.0, 0.0, 0.0], + "wheel_positions_rad": [step * .01, step * .01], + "wheel_targets_rad_s": [target, target], + "wheel_velocities_rad_s": [target, target], + "goal_distance_m": abs(0.8 - x), + "arrived": abs(0.8 - x) <= .08 if arrived is None else arrived, + "obstacle_collision": collision, + "map_out_of_bounds": False, + "map_collision": False, + "ground_contact": True, + "contact_actor_pairs": [['/World/Jetbot/chassis', '/World/Ground'], + ['/World/Jetbot/left_wheel', '/World/Ground'], + ['/World/Jetbot/right_wheel', '/World/Ground']] + + ([['/World/Jetbot/chassis', '/World/WallEast']] if collision else []), + } + + +class EvaluationTests(unittest.TestCase): + def test_positive_requires_real_displacement_and_arrival(self): + path = [sample(i, i * .75 / 200, target=0 if i == 0 else 1) for i in range(201)] + self.assertTrue(evaluate(path, "positive")["passed"]) + self.assertFalse(evaluate([sample(0, 0), sample(1, 0.01, target=1)], "positive")["passed"]) + + def test_zero_requires_zero_targets_and_little_displacement(self): + self.assertTrue(evaluate([sample(0, 0), sample(1, 0.001)], "zero")["passed"]) + self.assertFalse(evaluate([sample(0, 0), sample(1, 0.001, target=0.1)], "zero")["passed"]) + self.assertFalse(evaluate([sample(0, 0), sample(1, 0.2)], "zero")["passed"]) + + def test_collision_and_incomplete_or_nonfinite_readback_fail_closed(self): + self.assertFalse(evaluate([sample(0, 0), sample(1, 0.75, arrived=True, collision=True)], "positive")["passed"]) + self.assertFalse(evaluate([sample(0, 0), sample(2, 0.75, arrived=True)], "positive")["passed"]) + self.assertFalse(evaluate([sample(0, 0), sample(1, float('nan'), arrived=True)], "positive")["passed"]) + no_contact = [sample(0, 0), sample(1, 0.001)] + for item in no_contact: + item['ground_contact'] = False + self.assertFalse(evaluate(no_contact, "zero")["passed"]) + + def test_rejects_teleport_and_missing_physics_callback(self): + self.assertFalse(evaluate([sample(0, 0), sample(1, 0.75, target=1, arrived=True)], "positive")["passed"]) + values = [sample(0, 0), sample(1, 0.001)] + values[-1]['physics_callback_count'] = values[0]['physics_callback_count'] + self.assertFalse(evaluate(values, "zero")["passed"]) + + def test_zero_control_cannot_move_away_and_return(self): + values = [sample(0, 0), sample(1, .2), sample(2, 0)] + self.assertFalse(evaluate(values, "zero")["passed"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/experiments/mobilitygen_jetbot/test_fetch.py b/experiments/mobilitygen_jetbot/test_fetch.py new file mode 100644 index 0000000..51f1632 --- /dev/null +++ b/experiments/mobilitygen_jetbot/test_fetch.py @@ -0,0 +1,49 @@ +import hashlib +import io +import json +from pathlib import Path +import tempfile +import unittest +from unittest.mock import patch + +import fetch_assets + + +class Response(io.BytesIO): + def __init__(self, data): + super().__init__(data) + self.headers = {'Content-Length': str(len(data))} + + +class FetchTests(unittest.TestCase): + def test_fetches_only_locked_objects_and_preserves_failure(self): + with tempfile.TemporaryDirectory() as name: + root = Path(name) + source = root / 'tool'; source.mkdir() + payloads = {'jetbot.usda': b'root', **{f'payloads/{n}.usda': bytes([n]) for n in range(7)}} + lock = {'asset': 'jetbot.usda', 'total_bytes': sum(map(len, payloads.values())), 'files': [ + {'path': path, 'bytes': len(data), 'sha256': hashlib.sha256(data).hexdigest(), + 'url': fetch_assets.SOURCE + path} for path, data in payloads.items()]} + lock_file = source / 'asset-lock.json' + lock_file.write_text(json.dumps(lock)) + (source / 'tool-lock.json').write_text(json.dumps({'files_sha256': { + 'asset-lock.json': hashlib.sha256(lock_file.read_bytes()).hexdigest()}})) + def response(request, timeout): + return Response(payloads[request.full_url.removeprefix(fetch_assets.SOURCE)]) + with patch.object(fetch_assets, 'HERE', source), patch.object(fetch_assets, 'urlopen', side_effect=response): + result = fetch_assets.fetch(root / 'download') + self.assertEqual(result.read_bytes(), b'root') + self.assertEqual(len((root / 'download/fetch-log.jsonl').read_text().splitlines()), 8) + with self.assertRaises(ValueError): + fetch_assets.fetch(root / 'download') + def corrupted(request, timeout): + return Response(b'bad') + with patch.object(fetch_assets, 'HERE', source), patch.object(fetch_assets, 'urlopen', side_effect=corrupted): + with self.assertRaises(ValueError): + fetch_assets.fetch(root / 'failed') + record = json.loads((root / 'failed/fetch-log.jsonl').read_text()) + self.assertEqual(record['status'], 'error') + + +if __name__ == '__main__': + unittest.main() diff --git a/experiments/mobilitygen_jetbot/test_new_guards.py b/experiments/mobilitygen_jetbot/test_new_guards.py new file mode 100644 index 0000000..7ed1799 --- /dev/null +++ b/experiments/mobilitygen_jetbot/test_new_guards.py @@ -0,0 +1,50 @@ +import hashlib +import json +from pathlib import Path +import tempfile +import unittest + +from asset_lock import verify_runtime +from evidence_lock import create_evidence_lock, verify_evidence_lock + + +class RuntimeLauncherTests(unittest.TestCase): + def test_launcher_is_hash_locked_before_any_simulator_starts(self): + with tempfile.TemporaryDirectory() as name: + root = Path(name) + (root / 'python.sh').write_bytes(b'changed launcher') + (root / 'VERSION').write_text('version') + (root / 'selected.py').write_bytes(b'selected') + lock = {'isaac_version': 'version', + 'launcher_sha256': hashlib.sha256(b'original launcher').hexdigest(), + 'files': {'selected.py': hashlib.sha256(b'selected').hexdigest()}} + with self.assertRaises(ValueError): + verify_runtime(root / 'python.sh', lock) + + +class EvidenceLockTests(unittest.TestCase): + def test_mutation_of_any_frozen_result_or_observation_fails(self): + with tempfile.TemporaryDirectory() as name: + root = Path(name) + for filename in ('telemetry.jsonl', 'metadata.json', 'result.json', 'process-exit.json', 'worker.log'): + (root / filename).write_text(filename) + digest = create_evidence_lock(root, 'positive', 0) + self.assertFalse(verify_evidence_lock(root, 'positive', digest)['partial']) + (root / 'result.json').write_text('modified') + with self.assertRaises(ValueError): + verify_evidence_lock(root, 'positive', digest) + + def test_failed_partial_run_records_missing_files_and_is_not_complete(self): + with tempfile.TemporaryDirectory() as name: + root = Path(name) + (root / 'worker.log').write_text('failure') + digest = create_evidence_lock(root, 'zero', 1) + locked = verify_evidence_lock(root, 'zero', digest) + self.assertTrue(locked['partial']) + self.assertIsNone(locked['files']['result.json']) + with self.assertRaises(FileExistsError): + create_evidence_lock(root, 'zero', 1) + + +if __name__ == '__main__': + unittest.main() diff --git a/experiments/mobilitygen_jetbot/test_pair.py b/experiments/mobilitygen_jetbot/test_pair.py new file mode 100644 index 0000000..2027441 --- /dev/null +++ b/experiments/mobilitygen_jetbot/test_pair.py @@ -0,0 +1,60 @@ +import copy +import unittest +from pair_check import check_pair +from test_sixty import fixed_rows + + +def records(): + drive = {'drive_type_codes': [1, 1], 'max_effort_nm': [1., 1.], + 'stiffness': [0., 0.], 'damping': [1., 1.]} + repair = [{'collider': '/World/Jetbot/chassis/geometry/caster_ball_' + end + '/caster_ball_front', + 'original_resolved_targets': [], 'new_material': '/World/Jetbot/caster_material', + 'source_coefficients': {'dynamic_friction': .01}} for end in ('front', 'back')] + override = [{'joint_path': '/World/Jetbot/chassis/' + side + '_wheel_joint', + 'original_max_effort_nm': 'infinity', 'scene_max_effort_nm': 1., 'type': 'force'} + for side in ('left', 'right')] + meta = {'case_sha256': 'a', 'script_sha256': 'b', 'asset_sha256': 'c', 'isaac_version': 'v', + 'case': {'dt': 1 / 60, 'seed': 20261116, 'settling_steps': 30, + 'solver_type': 'TGS', 'enable_external_forces_every_iteration': True, + 'native_wheel_damping': [1., 1.], 'native_wheel_damping_tolerance': 1e-5, + 'wheel_names': ['left_wheel_joint', 'right_wheel_joint'], + 'spawn_orientation_wxyz': [1., 0., 0., 0.], 'initial_orientation_tolerance_rad': .02, + 'spawn_position_m': [0., 0., .05], 'initial_xy_tolerance_m': .02, + 'initial_z_range_m': [.02, .06]}, + 'seed': 20261116, 'seeded_rngs': ['python.random', 'numpy.random'], + 'observed_physics_device': 'cpu', 'observed_physics_dt_s': 1 / 60, + 'observed_solver_settings_usd': {'solver_type': 'TGS', 'enable_external_forces_every_iteration': True}, + 'wheel_dof_indices': [0, 1], 'dof_names': ['left_wheel_joint', 'right_wheel_joint'], + 'native_dof_paths': ['/World/Jetbot/chassis/left_wheel_joint', '/World/Jetbot/chassis/right_wheel_joint'], + 'native_link_paths': ['/World/Jetbot/chassis', '/World/Jetbot/left_wheel', '/World/Jetbot/right_wheel'], + 'path_xy_m': [[0., 0.], [.8, 0.]], 'requested_steps': 600, 'actual_task_steps': 600, + 'stage_physics_repairs': repair, 'stage_drive_effort_overrides': override, + 'native_drive_before': drive, 'native_drive_after': drive} + log = ('Simulation App Startup Complete isaacsim.replicator.experimental.mobility_gen-0.5.0 ' + 'isaacsim.replicator.mobility_gen.examples-0.4.1') + a = {'metadata': {**copy.deepcopy(meta), 'mode': 'positive', 'terminal_status': 'arrived'}, + 'rows': fixed_rows('positive'), 'process': {'exit_code': 0}, 'log': log} + b = {'metadata': {**copy.deepcopy(meta), 'mode': 'zero', 'terminal_status': 'zero_target_duration_complete'}, + 'rows': fixed_rows('zero'), 'process': {'exit_code': 0}, 'log': log} + return a, b + + +class PairedEvidenceTests(unittest.TestCase): + def test_matching_pair_passes(self): + self.assertTrue(check_pair(*records())['passed']) + + def test_different_case_and_missing_repair_fail(self): + a, b = records(); b['metadata']['case_sha256'] = 'different' + self.assertFalse(check_pair(a, b)['passed']) + a, b = records(); b['metadata']['stage_physics_repairs'] = [] + self.assertFalse(check_pair(a, b)['passed']) + + def test_wrong_effort_or_failed_process_fail(self): + a, b = records(); b['metadata']['native_drive_after']['max_effort_nm'][0] = float('inf') + self.assertFalse(check_pair(a, b)['passed']) + a, b = records(); b['process']['exit_code'] = 1 + self.assertFalse(check_pair(a, b)['passed']) + + +if __name__ == '__main__': + unittest.main() diff --git a/experiments/mobilitygen_jetbot/test_reaudit.py b/experiments/mobilitygen_jetbot/test_reaudit.py new file mode 100644 index 0000000..1e8ac5c --- /dev/null +++ b/experiments/mobilitygen_jetbot/test_reaudit.py @@ -0,0 +1,28 @@ +import json +from pathlib import Path +import tempfile +import unittest + +from audit_output import audit_output +from evidence_lock import create_evidence_lock + + +class ReauditTests(unittest.TestCase): + def test_changed_evidence_is_rejected_before_reading_result(self): + for changed in ('telemetry.jsonl', 'metadata.json', 'result.json', 'process-exit.json', 'worker.log'): + with self.subTest(file=changed), tempfile.TemporaryDirectory() as name: + root = Path(name); locks = {} + for mode in ('positive', 'zero'): + run = root / 'runs' / mode; run.mkdir(parents=True) + for filename in ('telemetry.jsonl', 'metadata.json', 'result.json', 'process-exit.json', 'worker.log'): + (run / filename).write_text(filename) + locks[mode] = create_evidence_lock(run, mode, 0) + (root / 'run-manifest.json').write_text(json.dumps({ + 'schema': 'simscene.mobilitygen_jetbot.run.v1', 'evidence_locks': locks})) + (root / 'runs' / 'positive' / changed).write_text('tampered') + with self.assertRaisesRegex(ValueError, 'evidence missing or changed'): + audit_output(root) + + +if __name__ == '__main__': + unittest.main() diff --git a/experiments/mobilitygen_jetbot/test_redirect.py b/experiments/mobilitygen_jetbot/test_redirect.py new file mode 100644 index 0000000..2301b1a --- /dev/null +++ b/experiments/mobilitygen_jetbot/test_redirect.py @@ -0,0 +1,64 @@ +import hashlib +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +import json +import os +from pathlib import Path +import tempfile +from threading import Thread +import unittest +from unittest.mock import patch +from urllib.error import HTTPError +import urllib.request + +import fetch_assets + + +class RedirectTests(unittest.TestCase): + def test_redirect_is_rejected_before_cross_origin_request(self): + hits, source_hits = [], [] + class Target(BaseHTTPRequestHandler): + def do_GET(self): + hits.append(self.path) + self.send_response(200); self.send_header('Content-Length', '4'); self.end_headers() + self.wfile.write(b'root') + def log_message(self, *args): + pass + target = ThreadingHTTPServer(('127.0.0.1', 0), Target) + target_thread = Thread(target=target.serve_forever, daemon=True); target_thread.start() + class Source(BaseHTTPRequestHandler): + def do_GET(self): + source_hits.append(self.path) + self.send_response(302) + self.send_header('Location', f'http://127.0.0.1:{target.server_port}/private') + self.end_headers() + def log_message(self, *args): + pass + source = ThreadingHTTPServer(('127.0.0.1', 0), Source) + source_thread = Thread(target=source.serve_forever, daemon=True); source_thread.start() + try: + with tempfile.TemporaryDirectory() as name: + root = Path(name); tool = root / 'tool'; tool.mkdir() + prefix = f'http://127.0.0.1:{source.server_port}/' + payloads = {'jetbot.usda': b'root', **{f'{n}.usda': bytes([n]) for n in range(7)}} + lock = {'asset': 'jetbot.usda', 'total_bytes': sum(map(len, payloads.values())), 'files': [ + {'path': p, 'bytes': len(data), 'sha256': hashlib.sha256(data).hexdigest(), 'url': prefix + p} + for p, data in payloads.items()]} + lock_file = tool / 'asset-lock.json'; lock_file.write_text(json.dumps(lock)) + (tool / 'tool-lock.json').write_text(json.dumps({'files_sha256': { + 'asset-lock.json': hashlib.sha256(lock_file.read_bytes()).hexdigest()}})) + with (patch.object(fetch_assets, 'HERE', tool), patch.object(fetch_assets, 'SOURCE', prefix), + patch.dict(os.environ, {'NO_PROXY': '127.0.0.1', 'no_proxy': '127.0.0.1'}), + patch.object(urllib.request, '_opener', None)): + with self.assertRaises(Exception) as caught: + fetch_assets.fetch(root / 'download') + self.assertIsInstance(caught.exception, HTTPError) + self.assertEqual(caught.exception.code, 302) + self.assertEqual(source_hits, ['/jetbot.usda']) + self.assertEqual(hits, [], 'redirect target must never be contacted') + finally: + source.shutdown(); target.shutdown() + source.server_close(); target.server_close() + + +if __name__ == '__main__': + unittest.main() diff --git a/experiments/mobilitygen_jetbot/test_review_regressions.py b/experiments/mobilitygen_jetbot/test_review_regressions.py new file mode 100644 index 0000000..b832131 --- /dev/null +++ b/experiments/mobilitygen_jetbot/test_review_regressions.py @@ -0,0 +1,206 @@ +import copy +import math +import unittest + +from pair_check import check_pair +from test_pair import records + + +def valid_records(): + positive, control = records() + for run in (positive, control): + meta = run['metadata'] + meta['case'].update(seed=20261116, wheel_names=['left_wheel_joint', 'right_wheel_joint'], + spawn_orientation_wxyz=[1., 0., 0., 0.], initial_orientation_tolerance_rad=.02, + spawn_position_m=[0., 0., .05], initial_xy_tolerance_m=.02, + initial_z_range_m=[.02, .06], + initial_pair_wheel_position_tolerance_rad=.001, + initial_pair_wheel_velocity_tolerance_rad_s=.001, + initial_linear_speed_tolerance_m_s=.05, initial_angular_speed_tolerance_rad_s=.1, + initial_pair_linear_velocity_tolerance_m_s=.005, + initial_pair_angular_velocity_tolerance_rad_s=.02, + minimum_driven_steps=10) + meta['seed'] = 20261116 + meta['seeded_rngs'] = ['python.random', 'numpy.random'] + for row in run['rows']: + row['time_s'] = row['step'] / 60 + row['wheel_positions_rad'] = [row['step'] * .01, row['step'] * .01] + row['base_com_linear_velocity_m_s'] = [0., 0., 0.] + row['base_angular_velocity_rad_s'] = [0., 0., 0.] + row['contact_actor_pairs'] = [['/World/Jetbot/chassis', '/World/Ground'], + ['/World/Jetbot/left_wheel', '/World/Ground'], + ['/World/Jetbot/right_wheel', '/World/Ground']] + return positive, control + + +class ReviewRegressionTests(unittest.TestCase): + def test_matching_enriched_records_pass(self): + self.assertTrue(check_pair(*valid_records())['passed']) + + def test_wall_contact_cannot_be_hidden_by_false_flag(self): + a, b = valid_records() + a['rows'][10]['contact_actor_pairs'].append(['/World/Jetbot/chassis', '/World/WallEast']) + a['rows'][10]['obstacle_collision'] = False + self.assertFalse(check_pair(a, b)['passed']) + + def test_invalid_time_and_missing_or_nonfinite_joint_positions_fail(self): + for field, value in [('time_s', -987), ('time_s', float('nan')), + ('wheel_positions_rad', None), ('wheel_positions_rad', [0., float('inf')])]: + a, b = valid_records() + for row in a['rows']: + row[field] = value + self.assertFalse(check_pair(a, b)['passed'], field) + + def test_wheel_index_name_mapping_is_not_just_equal_across_runs(self): + a, b = valid_records() + for run in (a, b): + run['metadata']['wheel_dof_indices'] = [1, 0] + self.assertFalse(check_pair(a, b)['passed']) + + def test_swapped_native_paths_fail_even_when_names_match(self): + a, b = valid_records() + for run in (a, b): + run['metadata']['native_dof_paths'].reverse() + self.assertFalse(check_pair(a, b)['passed']) + + def test_native_drive_configuration_must_match_both_runs_and_times(self): + a, b = valid_records() + b['metadata']['native_drive_before']['damping'] = [2., 2.] + b['metadata']['native_drive_after']['damping'] = [2., 2.] + self.assertFalse(check_pair(a, b)['passed']) + + def test_common_180_degree_initial_yaw_is_not_accepted(self): + a, b = valid_records() + for run in (a, b): + run['rows'][0]['base_orientation_wxyz'] = [0., 0., 0., 1.] + self.assertFalse(check_pair(a, b)['passed']) + + def test_common_wrong_initial_height_is_not_accepted(self): + a, b = valid_records() + for run in (a, b): + for row in run['rows']: + row['base_position_m'][2] = .5 + self.assertFalse(check_pair(a, b)['passed']) + + def test_only_step_zero_nonzero_does_not_establish_task_driving(self): + a, b = valid_records() + for row in a['rows']: + value = [1., 1.] if row['step'] == 0 else [0., 0.] + row['wheel_targets_rad_s'] = value + row['native_wheel_targets_rad_s'] = list(value) + self.assertFalse(check_pair(a, b)['passed']) + + def test_arrival_flag_must_match_observed_distance(self): + a, b = valid_records() + a['rows'][0]['arrived'] = True + a['rows'][0]['wheel_targets_rad_s'] = [1., 1.] + a['rows'][0]['native_wheel_targets_rad_s'] = [1., 1.] + for row in a['rows'][1:]: + row['wheel_targets_rad_s'] = [0., 0.] + row['native_wheel_targets_rad_s'] = [0., 0.] + self.assertFalse(check_pair(a, b)['passed']) + + def test_seed_must_be_recorded_and_agree_with_frozen_case(self): + a, b = valid_records() + del a['metadata']['seed']; del b['metadata']['seed'] + self.assertFalse(check_pair(a, b)['passed']) + a, b = valid_records() + b['metadata']['seed'] = 7 + self.assertFalse(check_pair(a, b)['passed']) + + def test_matching_paths_must_still_be_the_frozen_route(self): + a, b = valid_records() + for run in (a, b): + run['metadata']['path_xy_m'] = [[100., 100.], [200., 200.]] + self.assertFalse(check_pair(a, b)['passed']) + + def test_native_pose_cannot_leave_physical_walls_with_false_map_flags(self): + a, b = valid_records() + for row in a['rows']: + x = row['base_position_m'][0] + y = 2.1 * math.sin(math.pi * row['step'] / 600) + row['base_position_m'][1] = y + row['goal_distance_m'] = math.hypot(.8 - x, y) + row['arrived'] = row['goal_distance_m'] <= .08 + self.assertFalse(check_pair(a, b)['passed']) + + def test_chassis_contact_does_not_replace_wheel_contacts(self): + for side in ('left', 'right'): + with self.subTest(side=side): + a, b = valid_records() + for run in (a, b): + for row in run['rows'][1:]: + row['contact_actor_pairs'] = [pair for pair in row['contact_actor_pairs'] + if '/World/Jetbot/' + side + '_wheel' not in pair] + self.assertFalse(check_pair(a, b)['passed']) + + def test_settling_contacts_cannot_stand_in_for_task_contacts(self): + a, b = valid_records() + for run in (a, b): + for row in run['rows'][1:]: + row['contact_actor_pairs'] = [] + row['ground_contact'] = False + self.assertFalse(check_pair(a, b)['passed']) + + def test_missing_or_disabled_tgs_solver_configuration_is_rejected(self): + a, b = valid_records() + for run in (a, b): + run['metadata']['observed_solver_settings_usd']['enable_external_forces_every_iteration'] = False + self.assertFalse(check_pair(a, b)['passed']) + + def test_pair_result_explicitly_declares_native_velocity_unverified(self): + result = check_pair(*valid_records()) + self.assertEqual(result.get('native_velocity_consistency'), 'not_verified') + + def test_uniformly_wrong_native_drive_damping_is_rejected(self): + a, b = valid_records() + for run in (a, b): + for key in ('native_drive_before', 'native_drive_after'): + run['metadata'][key]['damping'] = [1e-12, 1e12] + self.assertFalse(check_pair(a, b)['passed']) + + def test_ten_initial_commands_cannot_explain_the_recorded_motion_interval(self): + a, b = valid_records() + for row in a['rows'][11:]: + row['wheel_targets_rad_s'] = [0., 0.] + row['native_wheel_targets_rad_s'] = [0., 0.] + self.assertFalse(check_pair(a, b)['passed']) + + def test_constant_sampled_wheel_positions_do_not_show_wheel_motion(self): + a, b = valid_records() + for row in a['rows']: + row['wheel_positions_rad'] = [0., 0.] + self.assertFalse(check_pair(a, b)['passed']) + + def test_callback_clock_must_start_after_exact_frozen_settling_steps(self): + a, b = valid_records() + for run in (a, b): + for row in run['rows']: + row['physics_callback_count'] += 7 + self.assertFalse(check_pair(a, b)['passed']) + + def test_initial_native_velocities_and_wheel_positions_are_paired_and_bounded(self): + for field, value in [('wheel_positions_rad', [.1, 0.]), + ('wheel_velocities_rad_s', [.01, 0.]), + ('base_com_linear_velocity_m_s', [.02, 0., 0.]), + ('base_angular_velocity_rad_s', [.04, 0., 0.])]: + a, b = valid_records() + b['rows'][0][field] = value + self.assertFalse(check_pair(a, b)['passed'], field) + for field, value in [('base_com_linear_velocity_m_s', [.1, 0., 0.]), + ('base_angular_velocity_rad_s', [.2, 0., 0.])]: + a, b = valid_records() + a['rows'][0][field] = value; b['rows'][0][field] = value + self.assertFalse(check_pair(a, b)['passed'], field) + + def test_missing_or_nonfinite_native_chassis_velocity_fails(self): + a, b = valid_records() + del a['rows'][1]['base_com_linear_velocity_m_s'] + self.assertFalse(check_pair(a, b)['passed']) + a, b = valid_records() + a['rows'][1]['base_angular_velocity_rad_s'] = [float('nan'), 0., 0.] + self.assertFalse(check_pair(a, b)['passed']) + + +if __name__ == '__main__': + unittest.main() diff --git a/experiments/mobilitygen_jetbot/test_sixty.py b/experiments/mobilitygen_jetbot/test_sixty.py new file mode 100644 index 0000000..0430a2a --- /dev/null +++ b/experiments/mobilitygen_jetbot/test_sixty.py @@ -0,0 +1,48 @@ +import copy +import unittest +from evaluate import evaluate_horizon, validate_drive_snapshot +from test_evaluate import sample + + +def fixed_rows(mode): + rows = [] + for step in range(601): + x = min(.75, step * .75 / 200) if mode == 'positive' else 0. + arrived = abs(.8 - x) <= .08 + target = 1. if mode == 'positive' and step and not arrived else 0. + row = sample(step, x, target=target, arrived=arrived) + row['native_wheel_targets_rad_s'] = list(row['wheel_targets_rad_s']) + rows.append(row) + return rows + + +class FixedHorizonTests(unittest.TestCase): + def test_fixed_horizon_positive_and_zero(self): + self.assertTrue(evaluate_horizon(fixed_rows('positive'), 'positive')['passed']) + self.assertTrue(evaluate_horizon(fixed_rows('zero'), 'zero')['passed']) + + def test_partial_run_or_nonzero_terminal_target_rejected(self): + values = fixed_rows('positive') + self.assertFalse(evaluate_horizon(values[:-1], 'positive')['passed']) + values[-1]['wheel_targets_rad_s'] = [1., 1.] + values[-1]['native_wheel_targets_rad_s'] = [1., 1.] + self.assertFalse(evaluate_horizon(values, 'positive')['passed']) + + def test_native_drive_target_mismatch_rejected(self): + values = fixed_rows('zero') + values[10]['native_wheel_targets_rad_s'] = [1., 0.] + self.assertFalse(evaluate_horizon(values, 'zero')['passed']) + + def test_both_native_force_drives_require_finite_effort_and_gains(self): + good = {'drive_type_codes': [1, 1], 'max_effort_nm': [1., 1.], + 'stiffness': [0., 0.], 'damping': [1., 1.]} + self.assertEqual(validate_drive_snapshot(good), []) + for key, bad in [('max_effort_nm', [1., float('inf')]), + ('max_effort_nm', [1., 2.]), ('damping', [1., 0.]), + ('drive_type_codes', [1, 2])]: + value = copy.deepcopy(good); value[key] = bad + self.assertTrue(validate_drive_snapshot(value)) + + +if __name__ == '__main__': + unittest.main() diff --git a/experiments/mobilitygen_jetbot/tool-lock.json b/experiments/mobilitygen_jetbot/tool-lock.json new file mode 100644 index 0000000..329418a --- /dev/null +++ b/experiments/mobilitygen_jetbot/tool-lock.json @@ -0,0 +1,17 @@ +{ + "files_sha256": { + "asset-lock.json": "5b02cd1a5cae7978d2b47047896a21432939de708d2ebd24ca50459d7b83c438", + "asset_lock.py": "824ca870b0f9c521b090a11bdba185fb5200512f5fb5aef19a7f49ec4be63d9c", + "audit_output.py": "ded5b549274e0d1672ddb064bf5a418477356279c46005ccb631863b18633ed6", + "evaluate.py": "a3bccdfa93e3c100368517f1a991bbde10f82ac3b93ff0eff46d64754a52b433", + "evidence_lock.py": "235c8e3b90089fb53e8f07a47c79b0a171363ee184cbdb90b4d6e298f2d7e0db", + "fetch_assets.py": "1275fbed9d54d3050b0b1a36ac98a88215f98ce94d29ce98385886b54db2d0f1", + "fixed_case.json": "fd5dfd04758437dfc4e5d70cc713a1c3b14645b834e291586151a4e80fc3a5f6", + "pair_check.py": "96b529bd37d44461a2499d5deb7cc82a792a49932a11130919cde6c48af88bf5", + "run_pair.py": "6c48c7c947e168888d418e61076b2538667ce2ef4d0458a550e9754a38222cd3", + "runtime-lock.json": "25ceadc5b971957a013f6a21cbfe18f40d08c8be3c998482e87016dba0ac6d9f", + "worker.py": "13bce1462f5f6dfd9b82e46cab1d0fc45ea35c163cfc05411694e9497e040302" + }, + "queue_sha256": "0a5550135c4d1bf9a9b15069e73d615bc792a5dcc2dd8afa6ced1af9141dfc8b", + "schema": "simscene.mobilitygen_jetbot.tool-lock.v1" +} diff --git a/experiments/mobilitygen_jetbot/worker.py b/experiments/mobilitygen_jetbot/worker.py new file mode 100644 index 0000000..851546d --- /dev/null +++ b/experiments/mobilitygen_jetbot/worker.py @@ -0,0 +1,393 @@ +"""Fixed-route probe with explicit scene-local source caster material repair. + +The stock example writes instantaneous wheel velocities. This adapter sends +PhysX drive velocity targets instead and never calls replay or task-time reset. +""" +import argparse +import hashlib +import json +import math +import os +import random +from pathlib import Path +import sys +import traceback + +HERE = Path(__file__).resolve().parent +CASE = json.loads((HERE / 'fixed_case.json').read_text()) +parser = argparse.ArgumentParser() +parser.add_argument('--mode', required=True, choices=['positive', 'zero']) +parser.add_argument('--steps', type=int, default=CASE['task_step_budget']) +parser.add_argument('--output', required=True) +parser.add_argument('--asset', required=True) +args = parser.parse_args() +run_dir = Path(args.output).resolve() +if not run_dir.is_dir() or (run_dir / 'metadata.json').exists() or (run_dir / 'telemetry.jsonl').exists(): + raise SystemExit('output must be an empty, existing run directory') +if args.steps != CASE['task_step_budget']: + raise SystemExit('the frozen fixed horizon requires exactly 600 task steps') +asset = Path(args.asset).expanduser().absolute() +from asset_lock import verify_asset_files +verify_asset_files(asset, json.loads((HERE / 'asset-lock.json').read_text())) +isaac_root = Path(os.environ['ISAAC_PATH']).resolve() +version = (isaac_root / 'VERSION').read_text().strip() +if version != '6.2.0-rc.14+release.52805.02189a84.gl': + raise SystemExit(f'untested Isaac version: {version}') + +metadata = {'mode': args.mode, 'case': CASE, 'requested_steps': args.steps, + 'script_name': Path(__file__).name, + 'case_sha256': hashlib.sha256((HERE / 'fixed_case.json').read_bytes()).hexdigest(), + 'script_sha256': hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), + 'isaac_version': version, + 'asset_sha256': hashlib.sha256(asset.read_bytes()).hexdigest(), + 'drive_adapter': 'set_dof_velocity_targets; no task-time joint-state setter', + 'trajectory_adapter': 'fixed BFS endpoints; MobilityGen path-following controller', + 'collision_adapter': 'meters converted to pixels through buffered_meters; no automatic reset'} +(run_dir / 'metadata.json').write_text(json.dumps(metadata, indent=2) + '\n') +app = None +try: + if type(CASE.get('seed')) is not int or not 0 <= CASE['seed'] < 2**32: + raise ValueError('frozen seed must be a 32-bit integer') + random.seed(CASE['seed']) + from isaacsim import SimulationApp + app = SimulationApp({'headless': True, 'multi_gpu': False, + 'active_gpu': int(os.environ.get('SIMSCENE_GPU', '0'))}) + + import numpy as np + np.random.seed(CASE['seed']) + metadata.update(seed=CASE['seed'], seeded_rngs=['python.random', 'numpy.random']) + import omni.usd + import omni.physx + from pxr import Gf, PhysxSchema, PhysicsSchemaTools, Usd, UsdGeom, UsdPhysics, UsdShade + import isaacsim.core.experimental.utils.app as app_utils + from isaacsim.core.experimental.prims import Articulation, RigidPrim + from isaacsim.core.simulation_manager import SimulationManager, SimulationEvent + app_utils.enable_extension('isaacsim.replicator.mobility_gen.examples') + app.update() + from isaacsim.replicator.experimental.mobility_gen import MobilityGenScenario, OccupancyMap, Buffer + from isaacsim.replicator.experimental.mobility_gen.impl.path_planner import generate_paths, compress_path + from isaacsim.replicator.experimental.mobility_gen.impl.utils.path_utils import PathHelper + from isaacsim.replicator.mobility_gen.examples import JetbotRobot, RandomPathFollowingScenario + from isaacsim.robot.experimental.wheeled_robots import DifferentialController + + stage = omni.usd.get_context().get_stage() + UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z) + UsdGeom.SetStageMetersPerUnit(stage, 1.0) + world = UsdGeom.Xform.Define(stage, '/World') + stage.SetDefaultPrim(world.GetPrim()) + physics = UsdPhysics.Scene.Define(stage, '/World/PhysicsScene') + physics.CreateGravityDirectionAttr(Gf.Vec3f(0, 0, -1)) + physics.CreateGravityMagnitudeAttr(9.81) + pscene = PhysxSchema.PhysxSceneAPI.Apply(physics.GetPrim()) + pscene.CreateEnableGPUDynamicsAttr().Set(False) + pscene.CreateBroadphaseTypeAttr().Set('MBP') + pscene.CreateSolverTypeAttr().Set(CASE['solver_type']) + pscene.CreateEnableExternalForcesEveryIterationAttr().Set(CASE['enable_external_forces_every_iteration']) + + def static_cube(path, center, size): + cube = UsdGeom.Cube.Define(stage, path) + cube.CreateSizeAttr(1.0) + xf = UsdGeom.XformCommonAPI(cube) + xf.SetTranslate(Gf.Vec3d(*center)) + xf.SetScale(Gf.Vec3f(*size)) + UsdPhysics.CollisionAPI.Apply(cube.GetPrim()) + + static_cube('/World/Ground', (0, 0, -0.05), (4, 4, 0.1)) + static_cube('/World/WallEast', (1.95, 0, 0.25), (0.1, 4, 0.5)) + static_cube('/World/WallWest', (-1.95, 0, 0.25), (0.1, 4, 0.5)) + static_cube('/World/WallNorth', (0, 1.95, 0.25), (4, 0.1, 0.5)) + static_cube('/World/WallSouth', (0, -1.95, 0.25), (4, 0.1, 0.5)) + root = UsdGeom.Xform.Define(stage, '/World/Jetbot').GetPrim() + root.GetReferences().AddReference(str(asset)) + UsdGeom.XformCommonAPI(root).SetTranslate(Gf.Vec3d(*CASE['spawn_position_m'])) + # The source instances bind an absolute /jetbot/caster_material outside + # their reference scope, so USD drops that relationship. Repair only the + # composed scene, keeping the source USD unchanged and restoring the + # existing source-authored material and its original parameters. + material_path = '/World/Jetbot/caster_material' + material_prim = stage.GetPrimAtPath(material_path) + material = UsdShade.Material(material_prim) + material_api = UsdPhysics.MaterialAPI(material_prim) + coefficients = {'static_friction': material_api.GetStaticFrictionAttr().Get(), + 'dynamic_friction': material_api.GetDynamicFrictionAttr().Get(), + 'restitution': material_api.GetRestitutionAttr().Get()} + if not material or not material_prim.HasAPI(UsdPhysics.MaterialAPI) or any( + abs(coefficients[k] - v) > 1e-6 for k, v in + [('static_friction', .01), ('dynamic_friction', .01), ('restitution', .1)]): + raise RuntimeError('source caster material missing or parameters changed') + repairs = [] + for end in ('front', 'back'): + parent = stage.GetPrimAtPath('/World/Jetbot/chassis/geometry/caster_ball_' + end) + if not parent or not parent.IsInstance() or not parent.SetInstanceable(False): + raise RuntimeError(f'cannot expand expected caster instance: {end}') + collider = stage.GetPrimAtPath(str(parent.GetPath()) + '/caster_ball_front') + if not collider or not collider.HasAPI(UsdPhysics.CollisionAPI): + raise RuntimeError(f'expected caster collider missing: {end}') + old = [str(x) for x in collider.GetRelationship('material:binding:physics').GetTargets()] + if old: + raise RuntimeError(f'expected broken source binding, found {old}') + if not UsdShade.MaterialBindingAPI.Apply(collider).Bind(material, materialPurpose='physics'): + raise RuntimeError(f'cannot author caster physics material: {end}') + actual, _ = UsdShade.MaterialBindingAPI(collider).ComputeBoundMaterial(materialPurpose='physics') + if not actual or str(actual.GetPath()) != material_path: + raise RuntimeError(f'caster physics material did not resolve: {end}') + repairs.append({'collider': str(collider.GetPath()), 'original_resolved_targets': old, + 'new_material': material_path, 'source_coefficients': coefficients, + 'action': 'deinstance and restore source-authored physics material in scene only'}) + metadata['stage_physics_repairs'] = repairs + drive_repairs = [] + for name in CASE['wheel_names']: + joint_path = '/World/Jetbot/chassis/' + name + joint = stage.GetPrimAtPath(joint_path) + drive = UsdPhysics.DriveAPI.Get(joint, 'angular') + if not joint or not drive or drive.GetTypeAttr().Get() != 'force': + raise RuntimeError(f'expected angular force drive missing: {joint_path}') + original = drive.GetMaxForceAttr().Get() + if not math.isinf(original): + raise RuntimeError(f'expected original unbounded effort, got {original}') + if not drive.GetMaxForceAttr().Set(CASE['wheel_max_effort_nm']): + raise RuntimeError(f'cannot set finite effort on {joint_path}') + authored = drive.GetMaxForceAttr().Get() + if abs(authored - CASE['wheel_max_effort_nm']) > 1e-6: + raise RuntimeError(f'finite drive effort was not authored on {joint_path}') + drive_repairs.append({'joint_path': joint_path, 'type': drive.GetTypeAttr().Get(), + 'original_max_effort_nm': 'infinity', 'scene_max_effort_nm': authored, + 'stiffness_usd': drive.GetStiffnessAttr().Get(), + 'damping_usd': drive.GetDampingAttr().Get()}) + metadata['stage_drive_effort_overrides'] = drive_repairs + robot_bodies = [] + for prim in Usd.PrimRange(root, Usd.TraverseInstanceProxies()): + if prim.HasAPI(UsdPhysics.RigidBodyAPI): + PhysxSchema.PhysxContactReportAPI.Apply(prim).CreateThresholdAttr().Set(0) + robot_bodies.append(str(prim.GetPath())) + if len(robot_bodies) != 3: + raise RuntimeError(f'expected 3 robot rigid bodies: {robot_bodies}') + + pending_contacts = [] + def contact_callback(headers, data): + for header in headers: + if getattr(header, 'num_contact_data', 0) <= 0: + continue + actors = [str(PhysicsSchemaTools.intToSdfPath(header.actor0)), + str(PhysicsSchemaTools.intToSdfPath(header.actor1))] + if any(a == '/World/Jetbot' or a.startswith('/World/Jetbot/') for a in actors): + pending_contacts.append(actors) + subscription = omni.physx.get_physx_simulation_interface().subscribe_contact_report_events(contact_callback) + + app.update() # load stage while timeline remains stopped + SimulationManager.setup_simulation(dt=CASE['physics_dt_s'], device='cpu') + scenes = SimulationManager.get_physics_scenes() + if len(scenes) != 1: + raise RuntimeError(f'expected one physics scene, got {len(scenes)}') + scenes[0].set_enabled_gpu_dynamics(False) + if str(SimulationManager.get_physics_sim_device()) != 'cpu': + raise RuntimeError('physics device is not CPU') + app_utils.play() + app.update() # SDK warmup occurs before task time + app_utils.pause() + if not app_utils.is_paused(): + raise RuntimeError('timeline failed to pause for controlled stepping') + settings = {'solver_type': pscene.GetSolverTypeAttr().Get(), + 'enable_external_forces_every_iteration': pscene.GetEnableExternalForcesEveryIterationAttr().Get()} + if settings != {'solver_type': CASE['solver_type'], + 'enable_external_forces_every_iteration': CASE['enable_external_forces_every_iteration']}: + raise RuntimeError('PhysX scene settings differ from the frozen USD attributes') + metadata['observed_solver_settings_usd'] = settings + + art = Articulation('/World/Jetbot') + chassis = RigidPrim('/World/Jetbot/chassis') + if not art.is_physics_tensor_entity_valid() or not chassis.is_physics_tensor_entity_valid(): + raise RuntimeError('robot articulation or chassis tensor is invalid') + if set(art.dof_names) != set(CASE['wheel_names']) or len(art.dof_names) != 2: + raise RuntimeError(f'unexpected physical DOFs: {art.dof_names}') + dof_indices = art.get_dof_indices(CASE['wheel_names']) + dof_index_list = dof_indices.numpy().tolist() + native_view = art._physics_articulation_view + if native_view is None: + raise RuntimeError('native PhysX articulation view is missing') + native_dof_paths = list(native_view.dof_paths[0]) + native_link_paths = list(native_view.link_paths[0]) + expected_dofs = ['/World/Jetbot/chassis/' + name for name in CASE['wheel_names']] + if (len(native_dof_paths) != 2 or len(set(native_dof_paths)) != 2 or + [native_dof_paths[i] for i in dof_index_list] != expected_dofs or + len(native_link_paths) != 3 or set(native_link_paths) != set(robot_bodies)): + raise RuntimeError(f'native body or DOF paths differ from frozen paths: {native_dof_paths}, {native_link_paths}') + native_chassis = chassis._physics_rigid_body_view + if native_chassis is None: + raise RuntimeError('native chassis rigid-body view is missing') + def native_wheels(getter): + values = np.asarray(getter().numpy()) + if values.shape != (1, 2): + raise RuntimeError(f'unexpected native drive tensor shape: {values.shape}') + return values[0, dof_index_list].tolist() + def native_drive_snapshot(): + return {'drive_type_codes': [int(v) for v in native_wheels(native_view.get_drive_types)], + 'max_effort_nm': native_wheels(native_view.get_dof_max_forces), + 'stiffness': native_wheels(native_view.get_dof_stiffnesses), + 'damping': native_wheels(native_view.get_dof_dampings)} + from evaluate import validate_drive_snapshot + native_drive_before = native_drive_snapshot() + errors = validate_drive_snapshot(native_drive_before) + if errors: + raise RuntimeError('native drive readback failed: ' + ', '.join(errors)) + controller = DifferentialController(wheel_radius=CASE['wheel_radius_m'], wheel_base=CASE['wheel_base_m'], + max_linear_speed=CASE['target_speed_m_s'], max_angular_speed=CASE['maximum_yaw_rate_rad_s'], + max_wheel_speed=CASE['maximum_wheel_speed_rad_s']) + step_count = [0] + def post_step(dt, context): + if abs(dt - CASE['physics_dt_s']) > 1e-8: + raise RuntimeError(f'unexpected physics callback dt {dt}') + step_count[0] += 1 + callback_id = SimulationManager.register_callback(post_step, event=SimulationEvent.PHYSICS_POST_STEP) + def step_once(): + previous = step_count[0] + SimulationManager.step(steps=1) + if step_count[0] != previous + 1: + raise RuntimeError(f'expected one physics callback, got {step_count[0] - previous}') + + class DriveTargetJetbot(JetbotRobot): + path_following_speed = CASE['target_speed_m_s'] + path_following_stop_distance_threshold = CASE['arrival_distance_m'] + path_following_target_point_offset_meters = CASE['lookahead_m'] + + def write_action(self, step_size): + requested = np.asarray(self.action.get_value(), dtype=np.float64) + applied = np.zeros(2) if args.mode == 'zero' else requested + wheel = np.asarray(self.controller.forward(command=applied), dtype=np.float32) + self.articulation.set_dof_velocity_targets(wheel[np.newaxis], dof_indices=dof_indices) + self.last_twist = applied.tolist() + self.last_wheel_targets = wheel.tolist() + + robot = DriveTargetJetbot('/World/Jetbot', art, controller, front_camera=None) + robot.action.set_value(np.zeros(2)) + robot.write_action(CASE['physics_dt_s']) + for _ in range(CASE['settling_steps']): + step_once() + settled_contacts = list(pending_contacts) + pending_contacts.clear() + + # Reproduce the stock controller while fixing its pixel-vs-meter buffer call. + # Random reset is deliberately never invoked. + shape = tuple(CASE['map_shape']) + free = np.ones(shape, dtype=bool) + border = CASE['map_border_cells'] + free[:border, :] = free[-border:, :] = False + free[:, :border] = free[:, -border:] = False + occupancy = OccupancyMap.from_masks(free, ~free, CASE['map_resolution_m'], tuple(CASE['map_origin_xyyaw'])) + + class FixedScenario(RandomPathFollowingScenario): + def __init__(self, robot, occupancy_map): + MobilityGenScenario.__init__(self, robot, occupancy_map) + self.is_alive = True + self.target_path = Buffer() + self.collision_occupancy_map = occupancy_map.buffered_meters(robot.occupancy_map_collision_radius) + + scenario = FixedScenario(robot, occupancy) + start_px = np.rint(occupancy.world_to_pixel_numpy(np.array([[0.0, 0.0]])))[0].astype(int) + end_px = np.rint(occupancy.world_to_pixel_numpy(np.array([CASE['goal_xy_m']])))[0].astype(int) + graph = generate_paths((int(start_px[1]), int(start_px[0])), scenario.buffered_occupancy_map.freespace_mask()) + end = (int(end_px[1]), int(end_px[0])) + if not graph.visited[end]: + raise RuntimeError('fixed goal is not reachable on occupancy map') + points, _ = compress_path(graph.unroll_path(end)) + path = occupancy.pixel_to_world_numpy(points[:, ::-1]) + if len(path) < 2 or np.linalg.norm(path[-1] - np.array(CASE['goal_xy_m'])) > 1e-6: + raise RuntimeError(f'bad reconstructed fixed path: {path.tolist()}') + scenario.target_path.set_value(path) + scenario.target_path_helper = PathHelper(path) + metadata.update({'robot_bodies': robot_bodies, 'dof_names': art.dof_names, + 'wheel_dof_indices': dof_index_list, 'path_xy_m': path.tolist(), + 'native_dof_paths': native_dof_paths, 'native_link_paths': native_link_paths, + 'native_drive_before': native_drive_before, + 'observed_physics_device': str(SimulationManager.get_physics_sim_device()), + 'observed_physics_dt_s': SimulationManager.get_physics_dt(), + 'ground_contacts_during_settling': sum(any('/World/Ground' in a for a in p) for p in settled_contacts)}) + (run_dir / 'metadata.json').write_text(json.dumps(metadata, indent=2) + '\n') + + goal = CASE['goal_xy_m'] + def sample(step, contacts): + transforms = np.asarray(native_chassis.get_transforms().numpy()) + velocities = np.asarray(native_chassis.get_velocities().numpy()) + if transforms.shape != (1, 7) or velocities.shape != (1, 6): + raise RuntimeError('native chassis transform or velocity has an invalid shape') + pos = transforms[0, :3].tolist() + quat = transforms[0, [6, 3, 4, 5]].tolist() + base_linear = velocities[0, :3].tolist() + base_angular = velocities[0, 3:].tolist() + positions = art.get_dof_positions(dof_indices=dof_indices).numpy().reshape(-1).tolist() + velocities = art.get_dof_velocities(dof_indices=dof_indices).numpy().reshape(-1).tolist() + robot.update_state() + pose = robot.get_pose_2d() + ground = any(any(a == '/World/Ground' or a.startswith('/World/Ground/') for a in pair) for pair in contacts) + obstacle = any(any(a.startswith('/World/Wall') for a in pair) for pair in contacts) + distance = math.hypot(goal[0] - pos[0], goal[1] - pos[1]) + return {'step': step, 'physics_callback_count': step_count[0], 'time_s': step * CASE['physics_dt_s'], + 'base_position_m': pos, 'base_orientation_wxyz': quat, + 'base_com_linear_velocity_m_s': base_linear, 'base_angular_velocity_rad_s': base_angular, + 'wheel_positions_rad': positions, 'wheel_velocities_rad_s': velocities, + 'wheel_targets_rad_s': list(robot.last_wheel_targets), 'twist_command': list(robot.last_twist), + 'native_wheel_targets_rad_s': native_wheels(native_view.get_dof_velocity_targets), + 'goal_distance_m': distance, 'arrived': distance <= CASE['arrival_distance_m'], + 'obstacle_collision': obstacle, + 'map_out_of_bounds': not scenario.collision_occupancy_map.check_world_point_in_bounds(pose), + 'map_collision': not scenario.collision_occupancy_map.check_world_point_in_freespace(pose), + 'ground_contact': ground, 'contact_actor_pairs': contacts} + + terminal_status = None + with (run_dir / 'telemetry.jsonl').open('x', encoding='utf8') as stream: + initial = sample(0, settled_contacts) + stream.write(json.dumps(initial, allow_nan=False) + '\n'); stream.flush() + for step in range(1, args.steps + 1): + pending_contacts.clear() + if terminal_status is None: + alive = scenario.step(CASE['physics_dt_s']) + if not alive: + robot.action.set_value(np.zeros(2)); robot.write_action(CASE['physics_dt_s']) + pose = robot.get_pose_2d() + if not scenario.collision_occupancy_map.check_world_point_in_bounds(pose): + terminal_status = 'map_out_of_bounds' + elif not scenario.collision_occupancy_map.check_world_point_in_freespace(pose): + terminal_status = 'map_collision' + elif math.hypot(goal[0] - pose.x, goal[1] - pose.y) < CASE['arrival_distance_m']: + terminal_status = 'arrived' + else: + terminal_status = 'unknown_controller_stop' + else: + robot.action.set_value(np.zeros(2)); robot.write_action(CASE['physics_dt_s']) + step_once() + row = sample(step, list(pending_contacts)) + if row['obstacle_collision']: + terminal_status = 'obstacle_collision' + elif row['map_out_of_bounds']: + terminal_status = 'map_out_of_bounds' + elif row['map_collision']: + terminal_status = 'map_collision' + row['terminal_status'] = terminal_status + stream.write(json.dumps(row, allow_nan=False) + '\n'); stream.flush() + if terminal_status is None: + terminal_status = 'zero_target_duration_complete' if args.mode == 'zero' else 'timeout' + native_drive_after = native_drive_snapshot() + errors = validate_drive_snapshot(native_drive_after) + if errors: + raise RuntimeError('native final drive readback failed: ' + ', '.join(errors)) + metadata.update(native_drive_after=native_drive_after, terminal_status=terminal_status, + actual_task_steps=step_count[0] - CASE['settling_steps']) + (run_dir / 'metadata.json').write_text(json.dumps(metadata, indent=2) + '\n') + from evaluate import evaluate_horizon + rows = [json.loads(line) for line in (run_dir / 'telemetry.jsonl').read_text().splitlines()] + result = evaluate_horizon(rows, args.mode) + expected_terminal = 'arrived' if args.mode == 'positive' else 'zero_target_duration_complete' + if terminal_status != expected_terminal: + result['passed'] = False + result['errors'].append(f'unexpected terminal status {terminal_status}') + result['terminal_status'] = terminal_status + (run_dir / 'result.json').write_text(json.dumps(result, indent=2) + '\n') + print('RESULT', json.dumps(result), flush=True) + if not result['passed']: + raise RuntimeError('independent experiment checks did not pass') +except BaseException: + (run_dir / 'failure.txt').write_text(traceback.format_exc()) + raise +finally: + if app is not None: + app.close() diff --git a/plugins/build.py b/plugins/build.py index dbed999..36d2277 100644 --- a/plugins/build.py +++ b/plugins/build.py @@ -38,7 +38,14 @@ def versions(root=ROOT): checks remain experimental. Configure `SIMSCENE_ISAAC_PYTHON` for the host and use the `build-scene` skill to create and observe a scene. Asset licensing and dependency completeness must be checked for each selected model. +The optional layout, Sand3D and USDCraft SDK runtimes are configured separately; +small pinned example recipes are included without model payloads. ''' +EXAMPLE_DATA={ + 'artvip_door':('assets.lock.json','case.json','recipe.json','supplement.json'), + 'usdcraft_two_drawer':('assets.lock.json','case.json','recipe.json','recipe-control.json'), + 'usdcraft_sdk_guide':('assets.lock.json','case.json','recipe-short.json','recipe-long.json','check_pair.py'), +} def write(path, value): path.parent.mkdir(parents=True,exist_ok=True) path.write_text(json.dumps(value,indent=2)+'\n') @@ -92,7 +99,9 @@ def copy_installed_dependencies(vendor): for name in ('catalog/data/sources.yaml','recipes/data/recipes.json','preparation/data/package.json', 'preparation/data/package-lock.json','preparation/worker.py','worker/isaac_run.py', 'worker/gpu_queue.py','generation/worker.py','generation/backend_worker.py', - 'generation/templates/guide_plate_v1.py'): + 'generation/templates/guide_plate_v1.py','generation/templates/usdcraft_sdk_guide_plate_v1.py', + 'generation/usdcraft_backend_worker.py','preparation/articulation_v2.py', + 'verification/articulated_asset_two_joint_pair.py','catalog/providers/artvip.py'): assert root.joinpath(name).is_file(),name from simscene.catalog.registry import load_registry from simscene.recipes.registry import list_recipes @@ -142,7 +151,7 @@ def build(destination, use_installed_deps=False): write(portable/'server'/'build-info.json',{'python_version':PYTHON_VERSION,'plugin_version':PACKAGE_VERSION, 'builder_python':sys.version.split()[0],'wheel_sha256':wheel_sha256, 'dependency_mode':'installed' if use_installed_deps else 'pip', - 'optional_backends':'Isaac/USD, isolated GLB decoder and Sand3D runtimes are configured separately'}) + 'optional_backends':'Isaac/USD, isolated GLB decoder, layout, Sand3D and USDCraft SDK runtimes are configured separately'}) validate_vendor(vendor) (portable/'server'/'launch.py').write_text(LAUNCHER) (portable/'README.md').write_text(PACKAGE_README) @@ -150,6 +159,12 @@ def build(destination, use_installed_deps=False): shutil.copyfile(ROOT/notice,portable/notice) shutil.copyfile(ROOT/'plugins'/'install.py',portable/'install.py') shutil.copytree(ROOT/'skills',portable/'skills',ignore=shutil.ignore_patterns('__pycache__','*.pyc','.simscene-plugin-root')) + # Small, model-free reference recipes are read on demand by the skills. + # Copy only explicitly enumerated reference data and checker; never + # bundle source assets. + for example,names in EXAMPLE_DATA.items(): + target=portable/'examples'/example;target.mkdir(parents=True) + for name in names:shutil.copyfile(ROOT/'examples'/example/name,target/name) shutil.copyfile(ROOT/'docs'/'passive-network-verification.md', portable/'skills'/'build-scene'/'references'/'passive-network-verification.md') shutil.copyfile(ROOT/'docs'/'structural-loads-verification.md', @@ -161,6 +176,7 @@ def build(destination, use_installed_deps=False): claude.mkdir(parents=True) shutil.copytree(portable/'server',claude/'server') shutil.copytree(portable/'skills',claude/'skills') + shutil.copytree(portable/'examples',claude/'examples') shutil.copyfile(portable/'README.md',claude/'README.md') for notice in ('LICENSE','NOTICE','OPEN_SOURCE_NOTICES.md'): shutil.copyfile(portable/notice,claude/notice) @@ -169,6 +185,7 @@ def build(destination, use_installed_deps=False): deepseek.mkdir(parents=True) shutil.copytree(portable/'server',deepseek/'server') shutil.copytree(portable/'skills',deepseek/'skills') + shutil.copytree(portable/'examples',deepseek/'examples') shutil.copyfile(portable/'README.md',deepseek/'README.md') for notice in ('LICENSE','NOTICE','OPEN_SOURCE_NOTICES.md'): shutil.copyfile(portable/notice,deepseek/notice) diff --git a/skills/build-scene/references/native-assets.md b/skills/build-scene/references/native-assets.md index 7a292ee..7b1ab3c 100644 --- a/skills/build-scene/references/native-assets.md +++ b/skills/build-scene/references/native-assets.md @@ -4,7 +4,9 @@ Use explicit catalog source IDs when the role requires an optional provider: `usdcraft` for the admitted native USD manifest, `polyhaven` for the configured HDRI IDs. Default discovery combines NVIDIA search, ABO and GSO. Central offers additional owner locators, with individual package/licensing admission still -required. Source admission never grants every model a physical pass. +required. `artvip` is an explicitly selected experimental source with one +curated `door002` candidate, not a full ArtVIP index. Source admission never +grants every model a physical pass. `articulated_prop_v1` preserves an existing canonical metre/Z-up single-DOF graph. Use `source_physics_policy: preserve_valid`, `scale_mode: preserve`, @@ -13,6 +15,34 @@ topology, missing mass and joint/inertia scaling fail rather than synthesizing a hinge. The scene asset requires `dynamic: true` and its exact two-key prepared binding. Native auto-computed inertia is checked through actual cooked readback. +The curated ArtVIP door needs an opt-in `repair_explicit` preparation: its +source links have no authored total mass, seven colliders bind density-bearing +materials, and its source acceleration drive has unbounded effort. Supply and +record each experimental mass, affected material-density override and drive +neutralization in `native_physics_repairs` (`missing_masses_kg`, +`material_density_overrides`, `neutralize_drives` and a `reason`). Do not claim +those assumptions are source measurements or +silently apply them to another model; inspect its source first. +The selected object's exact repair assumptions and source pins are available +on demand in `examples/artvip_door/assets.lock.json` and its `case.json`. +Resolve `examples/` against the plugin root: for a skill copied into a project, +read the `build-scene/.simscene-plugin-root` marker; otherwise use the root +containing the `skills/` directory. + +`articulated_prop_v2` preserves an admitted three-link tree with two finite-limit +scalar hinge/slider joints. It currently accepts `preserve_valid` source physics +only and rejects coupled, geared, mimic or tendon structures. Use the actual +manifest joint IDs and body paths, not the source joint count, and request +strict per-step observations. For the selected USDCraft two-drawer sample, use a +frozen `simscene.articulated_asset_two_joint.v1` case and `run_verify`; a +matched control omitting the second drive uses mode +`missing_second_joint_drive`, the control job ID and positive reference job ID. +The tested two-slider result does not certify other axes or assets. +The tested cabinet is `ds_R022_02`; inspect its pinned +`examples/usdcraft_two_drawer/assets.lock.json` and `case.json` when needed. +Replace template binding markers with the newly prepared manifest and source +pins before starting the new run. + For a driven trial, add ordinary object `mechanism.commands`: ```json diff --git a/skills/build-scene/references/recipes.md b/skills/build-scene/references/recipes.md index bad49cd..90278c5 100644 --- a/skills/build-scene/references/recipes.md +++ b/skills/build-scene/references/recipes.md @@ -27,4 +27,25 @@ Optional `asset_generate` accepts a shipped fixed template and structured parameters, not arbitrary programs. Its completed generated AssetRef enters the same plan/prepare/verify workflow. The generator needs an explicitly configured independent runtime. Generation resource limits are not a network -or filesystem sandbox; external program execution is unavailable. +or filesystem sandbox; the interface does not accept arbitrary submitted programs. + +For the optional USDCraft SDK, use `usdcraft_sdk_guide_plate_v1` with numeric +`length_m`, `width_m` and `thickness_m`; inspect and prepare the result for its +actual role. Probe a separately installed reviewed SDK with +`simscene generate probe --backend usdcraft-sdk --python --checkout + --output ` and set +`usdcraft_generation_runtime` in the V2 configuration. Python, third-party +dependencies and local job storage must be trusted. Regeneration from a +portable lock requires the same template, runtime intent and output hashes. +The tested static guide uses an explicitly declared replacement box proxy; +generation and preparation are not a physical pass. +Length is 0.05–2 m, width 0.02–0.8 m and thickness 0.002–0.08 m; +thickness must be smaller than length and width. For measured preparation +parameters, source hashes and the two-size comparison, inspect the +`examples/usdcraft_sdk_guide/assets.lock.json` and `case.json` on demand. Resolve +`examples/` against the plugin root; a copied project skill records that root in +`build-scene/.simscene-plugin-root`. +This case uses the accompanying `check_pair.py`, not a built-in `run_verify` +case type. Run it with Python configured to import the plugin's `simscene` +package and USD bindings. Freeze binding markers before running both scenes; +examine the actual output and complete input/evidence locks. diff --git a/src/simscene/acquisition/dispatch.py b/src/simscene/acquisition/dispatch.py index 2016023..4ec7754 100644 --- a/src/simscene/acquisition/dispatch.py +++ b/src/simscene/acquisition/dispatch.py @@ -3,7 +3,7 @@ import hashlib import json import os -from pathlib import Path +from pathlib import Path, PurePosixPath from urllib.parse import urlencode, urlsplit from ..assets import USDSearch, SearchError from ..cache import AssetCache @@ -83,7 +83,7 @@ def acquire_selected(plan, *, config=None, job_directory=None): directory = Path(config['asset_cache_directory']).expanduser().resolve() capacity = config['asset_cache_capacity_bytes'] descriptor = plan.get('acquisition', {}) - if ref.source_id == 'local-sand3d' and descriptor.get('kind') == 'generated_package': + if ref.source_id in {'local-sand3d', 'local-usdcraft-sdk'} and descriptor.get('kind') == 'generated_package': from ..generation.acquisition import acquire_generated return acquire_generated(plan,config,job_directory) source_record = plan.get('source_snapshot', {}) @@ -99,10 +99,18 @@ def acquire_selected(plan, *, config=None, job_directory=None): if descriptor.get('kind') == 'hf_usd_package': from ..catalog.registry import load_registry source=load_registry(config.get('registry_path')).get(ref.source_id) - if (source.state not in {'audited','enabled'} or source.adapter not in {'usdcraft','simready_package'} + if (source.state not in {'audited','enabled'} or source.adapter not in {'usdcraft','artvip','simready_package'} or descriptor.get('repository') != source.repository or descriptor.get('revision') != ref.revision or descriptor.get('path') != source_record.get('entry_path')): raise ValueError('native selection differs from its admitted source descriptor') + if source.repository == 'X-Humanoid/ArtVIP': + path = descriptor.get('path') + registered = any(entry.path == ref.asset_id and entry.revision == ref.revision + for entry in source.metadata_entries) + if (not registered or descriptor.get('package_path') != ref.asset_id + or not isinstance(path, str) or PurePosixPath(path).as_posix() != path + or PurePosixPath(path).parent.as_posix() != ref.asset_id): + raise ValueError('ArtVIP selection differs from its current registered object or root directory') from .hf_package import acquire_hf_package return acquire_hf_package(descriptor,ref,limits,config,source_record,license_info,provenance,job_directory) transaction = TransferBudget(limits['download_bytes'], limits['unpacked_bytes'], limits['staging_bytes']) diff --git a/src/simscene/acquisition/plans.py b/src/simscene/acquisition/plans.py index 16bf73c..61d8bd9 100644 --- a/src/simscene/acquisition/plans.py +++ b/src/simscene/acquisition/plans.py @@ -71,7 +71,7 @@ def make_plan(ref, profile_id='visual_prop_v1', parameters=None, target=None, bu elif ref.source_id == 'nvidia-usd-search': descriptor = {'kind':'usd_dependency_closure','asset_url': availability.get('asset_url') or (record.provenance or {}).get('asset_url')} - elif ref.source_id == 'local-sand3d' and descriptor.get('kind') == 'generated_package': + elif ref.source_id in {'local-sand3d', 'local-usdcraft-sdk'} and descriptor.get('kind') == 'generated_package': if descriptor.get('revision') != ref.revision: blocking.append({'code':'verification_failed','detail':'generated content revision differs from selection'}) elif descriptor.get('kind') == 'http_files': diff --git a/src/simscene/catalog/audit.py b/src/simscene/catalog/audit.py index 0d5a6f6..8922559 100644 --- a/src/simscene/catalog/audit.py +++ b/src/simscene/catalog/audit.py @@ -98,7 +98,7 @@ def audit_source(candidate, policy=None): # revision may yield a review-only config. Similar filenames never create # a new provider and a source's old audit does not cover a new revision. registered = next((source for source in load_registry().sources - if source.repository == repo and source.adapter in {'abo', 'hf_manifest', 'usdcraft'}), None) + if source.repository == repo and source.adapter in {'abo', 'hf_manifest', 'usdcraft', 'artvip'}), None) if registered is not None and revision and recognized and layout.get('adapter') == registered.adapter: if distinct and distinct != [registered.license_policy['license'].lower()]: blocking.append('license_conflicts_with_registered_source') @@ -134,7 +134,7 @@ def build_source_list(registry=None, audit_snapshot=None): '|---|---|---|---|---|---|---|---|'] for source in registry.sources: examples = [item for item in source.evidence if isinstance(item, dict) and item.get('evidence_basis') == 'locally_executed' and item.get('runtime_validation') == 'pass'] - formats = {'nvidia': 'USD', 'abo': 'GLB', 'hf_manifest': 'GLB', 'usdcraft': 'USD', + formats = {'nvidia': 'USD', 'abo': 'GLB', 'hf_manifest': 'GLB', 'usdcraft': 'USD', 'artvip': 'USD', 'simready_package':'USD', 'http_assets':'HDRI / material maps (selected IDs)', 'simready_central':'USD locators (metadata only)'}.get(source.adapter, 'unknown') license_info = source.license_policy diff --git a/src/simscene/catalog/config.py b/src/simscene/catalog/config.py index c1a40ea..1b41dc6 100644 --- a/src/simscene/catalog/config.py +++ b/src/simscene/catalog/config.py @@ -15,7 +15,7 @@ def read(): from ..settings import config_path, get path = Path(os.getenv('SIMSCENE_V2_CONFIG', str(config_path().with_name('v2.json')))).expanduser() data = json.loads(path.read_text()) if path.is_file() else {} - allowed = set(DEFAULTS) | {'index_directory', 'prepared_directory', 'registry_path', 'runtime_manifest', 'converter_tools_prefix', 'generation_runtime'} + allowed = set(DEFAULTS) | {'index_directory', 'prepared_directory', 'registry_path', 'runtime_manifest', 'converter_tools_prefix', 'generation_runtime', 'usdcraft_generation_runtime'} if not isinstance(data, dict) or set(data)-allowed: raise ValueError('invalid V2 settings fields') result = dict(DEFAULTS, **data) @@ -33,7 +33,7 @@ def read(): result.setdefault('runtime_manifest', str(home/'preparation-runtime.json')) if os.getenv('SIMSCENE_GLTF_TRANSFORM_PREFIX'): result['converter_tools_prefix'] = os.environ['SIMSCENE_GLTF_TRANSFORM_PREFIX'] - for key in ('index_directory', 'prepared_directory', 'runtime_manifest', 'registry_path', 'converter_tools_prefix', 'generation_runtime'): + for key in ('index_directory', 'prepared_directory', 'runtime_manifest', 'registry_path', 'converter_tools_prefix', 'generation_runtime', 'usdcraft_generation_runtime'): if key in result: if not isinstance(result[key], str) or not result[key].strip(): raise ValueError('nonempty path required for '+key) diff --git a/src/simscene/catalog/data/sources.yaml b/src/simscene/catalog/data/sources.yaml index 8777dde..50f79f3 100644 --- a/src/simscene/catalog/data/sources.yaml +++ b/src/simscene/catalog/data/sources.yaml @@ -245,6 +245,39 @@ sources: runtime_validation: pass target: *id001 public_validation: docs/validation/catalog-capabilities.md + - schema_version: 1 + source_id: artvip + kind: asset_dataset + homepage: https://huggingface.co/datasets/X-Humanoid/ArtVIP + repository: X-Humanoid/ArtVIP + adapter: artvip + state: audited + default_enabled: false + metadata_entries: + - path: Articulated_objects/small_furniture/door/door002 + format: json + size_bytes: null + revision: d22f2095bc9db29fdd4b60f4a3c4f8177e1f5e9e + contains_images: false + contains_code: false + acquisition_granularity: dependency_closure + access: + visibility: public + gated: false + credentials_required: false + license_policy: + status: known + license: Apache-2.0 + per_asset_required: true + note: Dataset card declaration; no separate per-object license was found. + capabilities: {} + checked_at: '2026-11-16' + evidence: + - scope: static_source_review + origin: pinned_huggingface_metadata_2026-11-16 + url: https://huggingface.co/datasets/X-Humanoid/ArtVIP/tree/d22f2095bc9db29fdd4b60f4a3c4f8177e1f5e9e/Articulated_objects/small_furniture/door/door002 + runtime_validation: not_run + note: Only the explicitly listed object is indexed; USD dependencies and physics require selected-asset verification. - schema_version: 1 source_id: polyhaven kind: asset_dataset diff --git a/src/simscene/catalog/providers/artvip.py b/src/simscene/catalog/providers/artvip.py new file mode 100644 index 0000000..84d52fc --- /dev/null +++ b/src/simscene/catalog/providers/artvip.py @@ -0,0 +1,153 @@ +"""Curated, pinned ArtVIP object-tree metadata without downloading asset payloads.""" +import hashlib +import json +from pathlib import PurePosixPath +import re +import time +from urllib.parse import quote + +from .base import Provider, ProviderPage +from .hf_manifest import declared_license, safe_path +from ..models import AssetRecord, AssetRef +from ..network import MetadataError, fetch_metadata + +AUDITED_REVISION = 'd22f2095bc9db29fdd4b60f4a3c4f8177e1f5e9e' +CARD_SHA256 = '3193c5d74ef7f1d4777fe0ff77d3f9f2f4c436969ea1802726da177897003f63' + + +class ArtVIPProvider(Provider): + """Index only explicitly registered object directories at one immutable revision.""" + + def __init__(self, store, source, *, base_url='https://huggingface.co', max_index_bytes=4*1024**2): + if source.repository != 'X-Humanoid/ArtVIP': + raise ValueError('ArtVIP license projection requires its audited repository') + entries = source.metadata_entries + if not 1 <= len(entries) <= 100 or any(entry.format != 'json' for entry in entries): + raise ValueError('ArtVIP requires bounded explicit object-tree entries') + revisions = {entry.revision for entry in entries} + if len(revisions) != 1 or not re.fullmatch('[0-9a-f]{40}', next(iter(revisions)) or ''): + raise ValueError('ArtVIP object trees require one immutable revision') + paths = [safe_path(entry.path) for entry in entries] + if (len(set(paths)) != len(paths) or any(not 3 <= len(PurePosixPath(p).parts) <= 5 + or PurePosixPath(p).parts[0] != 'Articulated_objects' + for p in paths)): + raise ValueError('ArtVIP metadata entries must be distinct selected object directories') + self.store = store + self.source = source + self.source_id = source.source_id + self.entry = entries[0] + self.paths = tuple(paths) + self.base_url = base_url.rstrip('/') + self.max_index_bytes = max_index_bytes + selection = hashlib.sha256(json.dumps(paths, separators=(',', ':')).encode()).hexdigest() + self.prefix = self.entry.revision + ':' + selection + ':' + self.suffix = ':artvip-tree-v2' + self.configure(time.monotonic()+12, []) + + @property + def snapshot(self): + value = self.store.snapshot(self.source_id) + return value if value and value.startswith(self.prefix) and value.endswith(self.suffix) else 'index_not_refreshed' + + def _record(self, folder, item): + if folder not in self.paths or not isinstance(item, dict) or item.get('type') != 'file': + raise ValueError('unregistered ArtVIP object') + path = safe_path(item.get('path')) + if PurePosixPath(path).parent.as_posix() != folder or PurePosixPath(path).suffix.lower() not in {'.usd', '.usda', '.usdc'}: + raise ValueError('invalid selected ArtVIP root') + size = item.get('size') + lfs = item.get('lfs') + digest = lfs.get('oid') if isinstance(lfs, dict) else None + if (type(size) is not int or size <= 0 or not isinstance(digest, str) + or not re.fullmatch('[0-9a-f]{64}', digest) + or lfs.get('size') != size): + raise ValueError('ArtVIP root lacks a complete LFS content pin') + parts = PurePosixPath(folder).parts + category = parts[-2].replace('_', ' ') + card_url = ('https://huggingface.co/datasets/X-Humanoid/ArtVIP/resolve/' + + self.entry.revision + '/README.md') + if self.entry.revision == AUDITED_REVISION: + license_info = declared_license('Apache-2.0', basis='pinned_ArtVIP_dataset_card') + license_info.update(card_url=card_url, card_sha256=CARD_SHA256) + else: + license_info = declared_license(None, basis='unreviewed_ArtVIP_dataset_card_revision') + license_info.update(card_url=card_url, card_sha256=None) + return AssetRecord( + ref=AssetRef(self.source_id, folder, self.entry.revision), + title=parts[-1].replace('_', ' '), category=category, + tags=tuple(part.replace('_', ' ') for part in parts[1:-1]), + format='usd', entry_path=path, + license=license_info, + physics=None, capabilities={}, evidence_level='declared', + availability={'status': 'declared', 'granularity': 'dependency_closure', + 'estimated_download_bytes': None, 'files_complete': False, + 'acquisition': {'kind': 'hf_usd_package', 'repository': self.source.repository, + 'revision': self.entry.revision, 'path': path, 'package_path': folder, + 'files': [{'path': path, 'size': size, 'sha256': digest}], + 'files_complete': False, 'dependency_mode': 'inspect_selected_usd_closure'}}, + provenance={'repository': self.source.repository, 'metadata_revision': self.entry.revision, + 'selected_object_directory': folder, 'root_tree_entry': item, + 'license_scope': 'dataset-card declaration; per-object notice not independently established', + 'structure_and_runtime': 'unknown until selected USD is inspected and tested'}) + + def refresh(self): + records = [] + used = 0 + digest = hashlib.sha256() + try: + for folder in self.paths: + self.check_deadline() + url = (self.base_url + '/api/datasets/' + self.source.repository + '/tree/' + + self.entry.revision + '/' + quote(folder, safe='/') + + '?recursive=false&expand=true&limit=100') + headers = {} + raw = fetch_metadata(url, deadline=self.deadline, max_bytes=self.max_index_bytes-used, + ledger=self.ledger, response_metadata=headers) + used += len(raw) + items = json.loads(raw) + if headers.get('link') or not isinstance(items, list) or len(items) >= 100: + raise ValueError('incomplete or oversized ArtVIP object listing') + roots = [] + for item in items: + if not isinstance(item, dict) or item.get('type') not in {'file', 'directory'}: + raise ValueError('invalid ArtVIP tree entry') + path = safe_path(item.get('path')) + if PurePosixPath(path).parent.as_posix() != folder: + raise ValueError('unexpected nested ArtVIP tree entry') + if item['type'] == 'file' and PurePosixPath(path).suffix.lower() in {'.usd', '.usda', '.usdc'}: + roots.append(item) + if len(roots) != 1: + raise ValueError('ArtVIP object requires one unambiguous USD root') + records.append(self._record(folder, roots[0])) + digest.update(folder.encode() + b'\0' + raw + b'\0') + except (ValueError, TypeError, KeyError, UnicodeError): + raise MetadataError('ArtVIP object metadata changed; previous index preserved') from None + snapshot = self.prefix + digest.hexdigest() + self.suffix + self.store.replace_index(self.source_id, records, snapshot) + return {'source_id': self.source_id, 'snapshot': snapshot, 'records': len(records), + 'metadata_bytes': used, 'model_bytes': 0} + + def _reproject(self, record): + provenance = record.provenance or {} + result = self._record(provenance.get('selected_object_directory'), provenance.get('root_tree_entry')) + if result.ref != record.ref: + raise ValueError('ArtVIP index identity differs from selected metadata') + return result + + def search(self, request): + self.check_deadline() + start = len(self.ledger) + if self.snapshot == 'index_not_refreshed': + self.refresh() + records = self.store.search(self.source_id, request.query, limit=100, revision=self.entry.revision) + self.check_deadline() + count = sum(item.get('bytes', 0) for item in self.ledger[start:] if item.get('category') == 'metadata') + return ProviderPage(tuple(self._reproject(record) for record in records), self.snapshot, + bytes_read=count, warnings=(() if self.store.fts else ('fts5_unavailable',))) + + def resolve(self, ref): + if ref.source_id != self.source_id or ref.revision != self.entry.revision: + raise ValueError('ArtVIP selection differs from configured source revision') + ref.validate_selection(huggingface=True) + record = self.store.get(ref, require_snapshot_prefix=self.prefix, require_snapshot_suffix=self.suffix) + return self._reproject(record) diff --git a/src/simscene/catalog/providers/factory.py b/src/simscene/catalog/providers/factory.py index dd942c4..5c35eeb 100644 --- a/src/simscene/catalog/providers/factory.py +++ b/src/simscene/catalog/providers/factory.py @@ -15,6 +15,9 @@ def make_provider(store, source, config): if source.adapter=='usdcraft': from .simready_package import USDCraftProvider return USDCraftProvider(store,source,max_index_bytes=cap) + if source.adapter=='artvip': + from .artvip import ArtVIPProvider + return ArtVIPProvider(store,source,max_index_bytes=min(4*1024**2,cap)) if source.adapter=='simready_package': from .simready_package import SimReadyPackageProvider return SimReadyPackageProvider(store,source,max_index_bytes=min(4*1024**2,cap)) diff --git a/src/simscene/catalog/registry.py b/src/simscene/catalog/registry.py index b9c4f17..7d26566 100644 --- a/src/simscene/catalog/registry.py +++ b/src/simscene/catalog/registry.py @@ -5,7 +5,7 @@ import yaml from .models import SourceRecord -KNOWN_ADAPTERS = frozenset({'nvidia', 'abo', 'hf_manifest', 'usdcraft', 'simready_package', 'http_assets', 'simready_central'}) +KNOWN_ADAPTERS = frozenset({'nvidia', 'abo', 'hf_manifest', 'usdcraft', 'artvip', 'simready_package', 'http_assets', 'simready_central'}) MAX_REGISTRY_BYTES = 1024 * 1024 @@ -17,7 +17,9 @@ def validate_source(record: dict) -> SourceRecord: raise ValueError('ABO adapter requires the audited codepawl/abo-glb repository') if source.adapter == 'usdcraft' and source.repository != 'nvidia/USDCraft-10K': raise ValueError('USDCraft adapter requires its audited native source repository') - if source.adapter in {'abo','hf_manifest','usdcraft','simready_package'}: + if source.adapter == 'artvip' and source.repository != 'X-Humanoid/ArtVIP': + raise ValueError('ArtVIP adapter requires its audited native source repository') + if source.adapter in {'abo','hf_manifest','usdcraft','artvip','simready_package'}: import re if not source.repository or not re.fullmatch(r'[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+',source.repository): raise ValueError('HF adapter requires an explicit repository') diff --git a/src/simscene/catalog/search.py b/src/simscene/catalog/search.py index 014e45b..b2cc006 100644 --- a/src/simscene/catalog/search.py +++ b/src/simscene/catalog/search.py @@ -282,7 +282,12 @@ def resolve_asset(ref, *, index_directory=None, registry_path=_CONFIGURED_REGIST if source is not None and source.adapter == 'usdcraft': from .providers.simready_package import USDCraftProvider return USDCraftProvider(store, source).resolve(ref) + if source is not None and source.adapter == 'artvip': + from .providers.artvip import ArtVIPProvider + return ArtVIPProvider(store, source).resolve(ref) record = store.get(ref) if source is None and isinstance(record.provenance, dict) and record.provenance.get('repository') == 'nvidia/USDCraft-10K': raise ValueError('USDCraft source must be present in the configured registry before planning') + if source is None and isinstance(record.provenance, dict) and record.provenance.get('repository') == 'X-Humanoid/ArtVIP': + raise ValueError('ArtVIP source must be present in the configured registry before planning') return record diff --git a/src/simscene/cli.py b/src/simscene/cli.py index 03c85fb..a83c537 100644 --- a/src/simscene/cli.py +++ b/src/simscene/cli.py @@ -35,9 +35,11 @@ def main(): recipe=commands.add_parser('recipe',help='compile editable role-based scene operations without running physics') recipe.add_argument('action',choices=['list','compile']);recipe.add_argument('identifier',nargs='?') recipe.add_argument('--parameters');recipe.add_argument('--bindings');recipe.add_argument('--scene');recipe.add_argument('--output') - generation=commands.add_parser('generate',help='optional trusted Sand3D template jobs in an independent runtime') + generation=commands.add_parser('generate',help='optional trusted template jobs in independent runtimes') generation.add_argument('action',choices=['probe','start','status','cancel']);generation.add_argument('identifier',nargs='?') generation.add_argument('--python',dest='generation_python');generation.add_argument('--output');generation.add_argument('--parameters');generation.add_argument('--request-id') + generation.add_argument('--backend',choices=['sand3d','usdcraft-sdk'],help='independent runtime to probe (default: sand3d)') + generation.add_argument('--checkout',help='reviewed USDCraft source checkout to probe') asset=commands.add_parser('asset',help='immutable plans and durable preparation jobs') asset.add_argument('action',choices=['plan','prepare','probe','status','cancel','setup-decoder']) asset.add_argument('identifier',nargs='?');asset.add_argument('--ref');asset.add_argument('--parameters') @@ -89,9 +91,9 @@ def main(): run.add_argument('--archive-verified-objects',action='store_true',help='experimentally reclaim objects only after pinned per-item case checks') verify=commands.add_parser('verify') verify.add_argument('--run',required=True);verify.add_argument('--case',help='independent JSON/YAML case; defaults to a case snapshotted in a run directory') - verify.add_argument('--type',choices=['contact','suction','moving','repeated','domino','parallel','stream','mechanism','passive_network','rigid_asset_smoke'],help='case type; inferred for passive, stream or parallel cases') + verify.add_argument('--type',choices=['contact','suction','moving','repeated','domino','parallel','stream','mechanism','passive_network','rigid_asset_smoke','articulated_asset_two_joint'],help='case type; inferred for passive, stream or parallel cases') verify.add_argument('--spec',help='saved run spec, required for parallel and stream cases') - verify.add_argument('--mode',choices=['positive','detached_drawer','no_trigger','broken_rope','locked_door'],default='positive',help='read-only paired passive verification mode') + verify.add_argument('--mode',choices=['positive','detached_drawer','no_trigger','broken_rope','locked_door','missing_second_joint_drive'],default='positive',help='read-only paired passive or two-joint verification mode') verify.add_argument('--reference-run',help='matching completed positive run directory for a detached mechanism control') suite=commands.add_parser('verify-suite') suite.add_argument('--case',required=True);suite.add_argument('--run',required=True,action='append');suite.add_argument('--long-run',required=True) @@ -128,11 +130,18 @@ def main(): result=service.search(args.query,filters,args.limit,args.cursor) elif args.command=='generate': from .generation import jobs as generation_jobs + if args.checkout is not None and args.action != 'probe':raise ValueError('checkout applies only to probe') if args.action=='probe': if not args.generation_python or not args.output:raise ValueError('probe requires --python and a new --output') - from .generation.sand3d import probe_runtime - result=probe_runtime(args.generation_python,args.output) + if args.backend == 'usdcraft-sdk': + from .generation.usdcraft_sdk import probe_runtime + result=probe_runtime(args.generation_python,args.output,checkout=args.checkout) + else: + if args.checkout:raise ValueError('checkout applies only to the USDCraft SDK probe') + from .generation.sand3d import probe_runtime + result=probe_runtime(args.generation_python,args.output) elif args.action=='start': + if args.backend is not None:raise ValueError('backend applies to probe; start selects its backend by template ID') if not args.identifier:raise ValueError('start requires a registered template ID') result=generation_jobs.start(args.identifier,_load(args.parameters) if args.parameters else {},args.request_id) else: diff --git a/src/simscene/generation/jobs.py b/src/simscene/generation/jobs.py index c68ef57..658a478 100644 --- a/src/simscene/generation/jobs.py +++ b/src/simscene/generation/jobs.py @@ -1,4 +1,6 @@ """Durable trusted-template jobs with request replay and conservative reconnects.""" +import fcntl +import hashlib import json import os from pathlib import Path @@ -29,22 +31,87 @@ def _receipt(record): return {'job_id':record['job_id'],'type':'asset_generation','recipe_id':record['recipe_id']} -def start(recipe_id, parameters, request_id=None, *, config=None): +def _request_digest(payload): + return hashlib.sha256(json.dumps(payload,sort_keys=True,separators=(',',':'),allow_nan=False).encode()).hexdigest() + + +def _check_expected_intent(expected,recipe_id,parameters,runtime,package): + """Match a portable lock to the actual runtime and copied trusted template.""" + from ..recipes.io import _generation_intent + if not isinstance(expected,dict):raise ValueError('invalid portable lock intent') + if recipe_id=='usdcraft_sdk_guide_plate_v1': + from .usdcraft_sdk import COMMIT + generator='usdcraft_sdk' + else: + from .sand3d import COMMIT + generator='sand3d' + root=Path(package).resolve();template=root/'generation'/'templates'/(recipe_id+'.py') + if template.is_symlink() or not template.is_file() or not template.resolve().is_relative_to(root): + raise ValueError('portable lock requires a copied trusted template') + identity={'recipe_id':recipe_id,'parameters':parameters,'seed':0,'toolchain':runtime, + 'template_sha256':hashlib.sha256(template.read_bytes()).hexdigest()} + if generator=='usdcraft_sdk':identity['generation_contract_version']=3 + actual=_generation_intent(identity,{'generator':generator,'reviewed_commit':COMMIT}) + if actual!=expected:raise ValueError('frozen runtime or copied template differs from the portable lock') + + +def _resume_legacy_request(home, request_id, payload): + """Reconnect old reservations whose original request hash included runtime. + + Do not rewrite the old request or its frozen task. An interrupted or + ambiguous reservation stays uncertain and can never trigger another job. + """ + from ..scene import SceneError, _id + _id(request_id) + home=Path(home);directory=home/'job-requests' + if not directory.is_dir():return None + record_path=directory/(request_id+'.json') + with (directory/(request_id+'.lock')).open('a') as lock: + fcntl.flock(lock,fcntl.LOCK_EX) + if not record_path.exists():return None + try: prior=json.loads(record_path.read_text()) + except (OSError,ValueError) as error:raise SceneError('job request record is unreadable') from error + if prior.get('payload_sha256')==_request_digest(payload):return None + found=[] + for path in (home/'generation_jobs').glob('gen-*/job.json'): + try:record=json.loads(path.read_text()) + except (OSError,ValueError) as error:raise SceneError('generation reservation is unreadable') from error + if record.get('request_id')==request_id:found.append((path,record)) + if len(found)!=1:raise SceneError('request ID reused with different job parameters or an uncertain reservation') + path,record=found[0] + try:task=json.loads((path.parent/'task.json').read_text()) + except (OSError,ValueError) as error:raise SceneError('legacy generation task is unreadable') from error + if not isinstance(task,dict) or any(task.get(key)!=value for key,value in payload.items()) or not isinstance(task.get('runtime'),dict): + raise SceneError('request ID reused with different job parameters') + legacy=dict(payload,runtime=task['runtime']) + if (record.get('job_id')!=path.parent.name or record.get('request_payload_sha256')!=prior.get('payload_sha256') + or prior.get('payload_sha256')!=_request_digest(legacy)): + raise SceneError('legacy generation reservation is inconsistent') + receipt=_receipt(record) + if prior.get('state') not in ('starting','started') or (prior.get('state')=='started' and prior.get('result')!=receipt): + raise SceneError('legacy generation request record is inconsistent') + return dict(receipt,replayed=True) + + +def start(recipe_id, parameters, request_id=None, *, config=None, expected_intent=None): from ..catalog.config import read from ..request_registry import invoke from ..jobs import _process_identity - from .sand3d import parameters as normalize config=config or read() + if recipe_id == 'usdcraft_sdk_guide_plate_v1': + from .usdcraft_sdk import parameters as normalize, validate_runtime + runtime_key = 'usdcraft_generation_runtime' + else: + from .sand3d import parameters as normalize + validate_runtime = None + runtime_key = 'generation_runtime' normalized=normalize(recipe_id,parameters) - manifest=config.get('generation_runtime') - if not manifest or not Path(manifest).is_file() or Path(manifest).stat().st_size>65536: - raise ValueError('generation_runtime_unavailable: configure a separately probed Sand3D runtime manifest') - runtime=json.loads(Path(manifest).read_text()) - from .sand3d import COMMIT - if runtime.get('reviewed_commit') != COMMIT or runtime.get('observed',{}).get('sand3d_commit') != COMMIT: - raise ValueError('generation_runtime_unavailable: unreviewed generator version') request_id=request_id or 'generate-'+uuid.uuid4().hex - payload={'operation':'asset_generate','recipe_id':recipe_id,'parameters':normalized,'runtime':runtime} + payload={'operation':'asset_generate','recipe_id':recipe_id,'parameters':normalized} + if expected_intent is not None:payload['expected_generation_intent']=expected_intent + legacy=_resume_legacy_request(config['home'],request_id,payload) + if legacy is not None:return legacy + safe_prelaunch_abort=False def recover(identifier,digest): found=[] for path in (Path(config['home'])/'generation_jobs').glob('gen-*/job.json'): @@ -53,19 +120,43 @@ def recover(identifier,digest): if record.get('request_id') == identifier: if record.get('request_payload_sha256') != digest or record.get('job_id') != path.parent.name:return None found.append(_receipt(record)) - return found[0] if len(found)==1 else None + return found[0] if len(found)==1 else (False if not found and safe_prelaunch_abort else None) def launch(identifier,digest): - job_id='gen-'+uuid.uuid4().hex - root=directory(job_id,config=config);root.mkdir(parents=True) - write(root/'config.json',config);write(root/'task.json',dict(payload,runtime=runtime)) - record={'schema_version':1,'job_id':job_id,'type':'asset_generation','recipe_id':recipe_id,'state':'queued', - 'request_id':identifier,'request_payload_sha256':digest,'created_unix_ns':time.time_ns()} - package=root/'runtime'/'simscene' - shutil.copytree(Path(__file__).parents[1],package,ignore=shutil.ignore_patterns('__pycache__','*.pyc')) - write(root/'job.json',record) + nonlocal safe_prelaunch_abort + try: + manifest=config.get(runtime_key) + if not manifest or not Path(manifest).is_file() or Path(manifest).stat().st_size>65536: + raise ValueError('generation_runtime_unavailable: configure the separately probed runtime manifest for this template') + runtime=json.loads(Path(manifest).read_text()) + if validate_runtime: + validate_runtime(runtime) + else: + from .sand3d import COMMIT + if runtime.get('reviewed_commit') != COMMIT or runtime.get('observed',{}).get('sand3d_commit') != COMMIT: + raise ValueError('generation_runtime_unavailable: unreviewed generator version') + except Exception: + # Only this callback can prove that this failure happened before + # a job directory or supervisor was created. A later process that + # merely finds no reservation must still report uncertainty. + safe_prelaunch_abort=True + raise + try: + job_id='gen-'+uuid.uuid4().hex + root=directory(job_id,config=config);root.mkdir(parents=True) + package=root/'runtime'/'simscene' + shutil.copytree(Path(__file__).parents[1],package,ignore=shutil.ignore_patterns('__pycache__','*.pyc')) + if expected_intent is not None: + _check_expected_intent(expected_intent,recipe_id,normalized,runtime,package) + write(root/'config.json',config);write(root/'task.json',dict(payload,runtime=runtime)) + record={'schema_version':1,'job_id':job_id,'type':'asset_generation','recipe_id':recipe_id,'state':'queued', + 'request_id':identifier,'request_payload_sha256':digest,'created_unix_ns':time.time_ns()} + write(root/'job.json',record) + except Exception: + safe_prelaunch_abort=True + raise with (root/'worker.log').open('ab') as log: process=subprocess.Popen([sys.executable,'-m','simscene.generation.worker',str(root)], - env=dict(os.environ,PYTHONPATH=str(root/'runtime')),stdout=log,stderr=subprocess.STDOUT,start_new_session=True) + env=dict(os.environ,PYTHONPATH=str(root/'runtime')),cwd=str(root),stdout=log,stderr=subprocess.STDOUT,start_new_session=True) write(root/'launch.json',{'pid':process.pid,'identity':_process_identity(process.pid)}) return _receipt(record) return invoke(config['home'],request_id,payload,launch,recover) diff --git a/src/simscene/generation/templates/usdcraft_sdk_guide_plate_v1.py b/src/simscene/generation/templates/usdcraft_sdk_guide_plate_v1.py new file mode 100644 index 0000000..36bf1eb --- /dev/null +++ b/src/simscene/generation/templates/usdcraft_sdk_guide_plate_v1.py @@ -0,0 +1,40 @@ +"""Only this shipped SDK authoring program may be compiled by the adapter.""" +import json +from pathlib import Path +from sdk import (ArticulatedObject, BaseMode, Box, Inertial, Origin, + RigidBodyProperties, TestContext, TestReport, estimate_mass_from_density) + +PARAMETERS = json.loads(Path(__file__).with_name('dimensions.json').read_text()) +LENGTH_M = PARAMETERS['length_m'] +WIDTH_M = PARAMETERS['width_m'] +THICKNESS_M = PARAMETERS['thickness_m'] +DENSITY_KG_M3 = 650. + + +def build_object_model() -> ArticulatedObject: + model = ArticulatedObject(name='simscene_usdcraft_guide_plate', base_mode=BaseMode.FLOATING) + model.meta['mode'] = 'static' + shape = Box((LENGTH_M, WIDTH_M, THICKNESS_M)) + model.physics_material('contact', static_friction=.55, dynamic_friction=.4, + restitution=.05, density=DENSITY_KG_M3) + finish = model.material('wood', rgba=(.5, .3, .16, 1.), roughness=.65) + body = model.part('body', inertial=Inertial.from_geometry( + shape, mass=estimate_mass_from_density(shape, DENSITY_KG_M3), + origin=Origin(xyz=(0., 0., THICKNESS_M / 2))), + rigid_body=RigidBodyProperties(physics_material='contact')) + body.visual(shape, origin=Origin(xyz=(0., 0., THICKNESS_M / 2)), material=finish, name='plate') + return model + + +object_model = build_object_model() + + +def run_tests() -> TestReport: + ctx = TestContext(object_model) + bounds = ctx.part_world_aabb('body') + ctx.check('grounded plate', bounds is not None and abs(bounds[0][2]) < 1e-6) + if bounds is not None: + ctx.check('specified length', abs(bounds[1][0] - bounds[0][0] - LENGTH_M) < 1e-6) + ctx.check('specified width', abs(bounds[1][1] - bounds[0][1] - WIDTH_M) < 1e-6) + ctx.check('specified thickness', abs(bounds[1][2] - bounds[0][2] - THICKNESS_M) < 1e-6) + return ctx.report() diff --git a/src/simscene/generation/usdcraft_backend_worker.py b/src/simscene/generation/usdcraft_backend_worker.py new file mode 100644 index 0000000..189bd47 --- /dev/null +++ b/src/simscene/generation/usdcraft_backend_worker.py @@ -0,0 +1,237 @@ +"""Only a bundled guide-plate model is passed to the reviewed USDCraft SDK.""" +import hashlib +from importlib import metadata, resources, util +from importlib.machinery import PathFinder +import json +import os +from pathlib import Path +import re +import resource +import subprocess +import sys + +from .usdcraft_sdk import COMMIT, RECIPE, parameters + + +def validate_task(task, folder, *, normalize=True): + folder = Path(folder).resolve() + if not isinstance(task, dict): + raise ValueError('invalid USDCraft SDK backend task') + if task.get('operation') == 'probe': + if (set(task) not in ({'operation', 'output'}, {'operation', 'output', 'checkout_path'}) + or task['output'] != str(folder / 'observed.json') + or 'checkout_path' in task and (not isinstance(task['checkout_path'], str) + or not Path(task['checkout_path']).is_absolute())): + raise ValueError('invalid USDCraft SDK probe output') + return + expected = {'operation', 'recipe_id', 'parameters', 'expected_runtime', 'template_sha256', + 'output', 'runtime_output', 'report_output'} + if (set(task) != expected or task.get('operation') != 'generate' or task.get('recipe_id') != RECIPE + or not isinstance(task.get('expected_runtime'), dict) + or not isinstance(task.get('template_sha256'), str) or not re.fullmatch('[0-9a-f]{64}', task['template_sha256']) + or task.get('output') != str(folder / 'source.usda') + or task.get('runtime_output') != str(folder / 'backend-runtime.json') + or task.get('report_output') != str(folder / 'sdk-report.json') + or normalize and parameters(RECIPE, task['parameters']) != task['parameters']): + raise ValueError('invalid trusted USDCraft SDK generation task') + + +def _sha(path): + digest = hashlib.sha256() + with Path(path).open('rb') as stream: + for chunk in iter(lambda: stream.read(1024*1024), b''): + digest.update(chunk) + return digest.hexdigest() + + +def _git(root, *args): + git_env = dict(os.environ, GIT_CONFIG_NOSYSTEM='1', GIT_CONFIG_GLOBAL='/dev/null', + GIT_OPTIONAL_LOCKS='0', GIT_NO_REPLACE_OBJECTS='1') + return subprocess.run(['/usr/bin/git', '-C', str(root), *args], env=git_env, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True, timeout=20).stdout + + +def _verify_checkout(root, commit): + """Compare every committed file to its Git blob, ignoring index flags.""" + root = Path(root).resolve() + top = Path(os.fsdecode(_git(root, 'rev-parse', '--show-toplevel')).strip()).resolve() + if top != root or _git(root, 'rev-parse', 'HEAD').decode().strip() != commit: + raise ValueError('USDCraft checkout is not at the reviewed commit') + entries = _git(root, 'ls-tree', '-rz', '--full-tree', commit).split(b'\0') + committed = set(); directories = {''} + digest = hashlib.sha256() + for entry in entries: + if not entry: + continue + header, name = entry.split(b'\t', 1) + mode, kind, blob = header.split(b' ') + if mode not in (b'100644', b'100755') or kind != b'blob' or not re.fullmatch(b'[0-9a-f]{40}', blob): + raise ValueError('unsupported committed SDK file mode or Git blob') + relative = os.fsdecode(name) + path = root / relative + if (path.is_symlink() or any(parent.is_symlink() for parent in path.parents if parent != root.parent) + or not path.is_file() or not path.resolve().is_relative_to(root)): + raise ValueError('USDCraft checkout has an unsafe committed file') + data = path.read_bytes() + blob_hash = hashlib.sha1(b'blob ' + str(len(data)).encode() + b'\0' + data).hexdigest().encode() + if blob_hash != blob: + raise ValueError('USDCraft checkout file differs from commit blob: ' + relative) + digest.update(name + b'\0' + hashlib.sha256(data).hexdigest().encode() + b'\0') + committed.add(relative) + parent = Path(relative).parent + while parent != Path('.'): + directories.add(parent.as_posix()) + parent = parent.parent + if not committed: + raise ValueError('USDCraft checkout has no committed files') + for current, names, files in os.walk(root, topdown=True, followlinks=False): + current_path = Path(current) + for name in list(names): + path = current_path / name + relative = path.relative_to(root).as_posix() + if current_path == root and name in {'.git', '.venv'}: + names.remove(name) + elif name == '__pycache__' and not path.is_symlink(): + # The subprocess has a fresh PYTHONPYCACHEPREFIX and cannot + # read these ordinary checkout caches. + names.remove(name) + elif path.is_symlink() or relative not in directories: + raise ValueError('unexpected or untracked checkout directory: ' + relative) + for name in files: + path = current_path / name + relative = path.relative_to(root).as_posix() + if path.is_symlink() or relative not in committed: + raise ValueError('unexpected or untracked checkout file: ' + relative) + return digest.hexdigest() + + +def _verify_import_origins(root, search_paths): + root = Path(root).resolve() + for name in ('sdk', 'usdcraft', 'storage', 'viewer'): + spec = PathFinder.find_spec(name, search_paths) + expected = root / name / '__init__.py' + if not spec or not spec.origin or Path(spec.origin).resolve() != expected: + raise ValueError('USDCraft package import origin is shadowed: ' + name) + + +def _bootstrap(task): + """Add trusted venv packages without executing .pth or sitecustomize.""" + from urllib.parse import unquote, urlsplit + if not sys.flags.no_site or not sys.pycache_prefix: + raise ValueError('USDCraft backend requires -S and isolated bytecode cache') + venv = Path(sys.executable).absolute().parent.parent + site_packages = venv / 'lib' / f'python{sys.version_info.major}.{sys.version_info.minor}' / 'site-packages' + if not (venv / 'pyvenv.cfg').is_file() or not site_packages.is_dir(): + raise ValueError('USDCraft requires an independent Python virtual environment') + checkout = task.get('checkout_path') if task.get('operation') == 'probe' else task.get('expected_runtime', {}).get('repository_path') + if checkout is None: + metadata_files = list(site_packages.glob('usdcraft-*.dist-info/direct_url.json')) + if len(metadata_files) != 1: + raise ValueError('USDCraft editable checkout location is missing or ambiguous') + info = json.loads(metadata_files[0].read_text()) + url = urlsplit(info.get('url', '')) + if info.get('dir_info', {}).get('editable') is not True or url.scheme != 'file' or url.netloc not in ('', 'localhost'): + raise ValueError('USDCraft must be installed from a local editable checkout') + checkout = unquote(url.path) + root = Path(checkout).resolve() + _verify_checkout(root, COMMIT) + search_paths = [*sys.path, str(site_packages), str(root)] + _verify_import_origins(root, search_paths) + sys.path[:] = search_paths + return root + + +def _observe(): + """Pin the checked checkout, tool versions and interpreter without remote access.""" + sdk = util.find_spec('sdk'); package = util.find_spec('usdcraft') + if not sdk or not package or not sdk.origin or not package.origin: + raise ValueError('reviewed USDCraft SDK package is not installed') + root = Path(sdk.origin).resolve().parent.parent + _verify_import_origins(root, sys.path) + tree_sha = _verify_checkout(root, COMMIT) + dependencies = {} + for name in ('usdcraft', 'usd-core', 'numpy', 'scipy', 'trimesh', 'pydantic', 'networkx'): + dependencies[name] = metadata.version(name) + from pxr import Usd + return {'usdcraft_commit': COMMIT, 'usdcraft_version': dependencies['usdcraft'], 'source_clean': True, + 'source_tree_sha256': tree_sha, 'repository_path': str(root), + 'python_version': list(sys.version_info[:3]), 'python_executable_sha256': _sha(sys.executable), + 'usd_version': list(Usd.GetVersion()), 'dependencies': dependencies} + + +def run(task, folder): + folder = Path(folder).resolve() + validate_task(task, folder) + observed = _observe() + if observed['usdcraft_version'] != '1.0.0': + raise ValueError('USDCraft SDK version differs from the reviewed release') + if task['operation'] == 'probe': + Path(task['output']).write_text(json.dumps(observed, sort_keys=True, indent=2) + '\n') + return + if observed != task['expected_runtime']: + raise ValueError('generation runtime changed; explicitly probe again') + template = resources.files('simscene.generation').joinpath('templates/' + RECIPE + '.py').read_bytes() + if hashlib.sha256(template).hexdigest() != task['template_sha256']: + raise ValueError('trusted USDCraft template differs from the frozen job') + model = folder / 'model.py' + dimensions = folder / 'dimensions.json' + with model.open('xb') as stream: + stream.write(template) + with dimensions.open('x') as stream: + json.dump(task['parameters'], stream, sort_keys=True, allow_nan=False) + from usdcraft.compile import check_model, compile_model + check_model(model) + build = folder / 'sdk-build' + artifacts = compile_model(model, build, clean=False, render=False) + report = json.loads(Path(artifacts.report_path).read_text()) + if report.get('status') != 'success': + raise ValueError('USDCraft strict compile did not pass') + root = Path(artifacts.usdc_path).resolve() + if not root.is_relative_to(build.resolve()) or not root.is_file() or root.is_symlink(): + raise ValueError('USDCraft compiled root escaped its job') + from pxr import Sdf, Usd, UsdGeom, UsdPhysics, UsdUtils + def verify_closure(path): + layers, assets, unresolved = UsdUtils.ComputeAllDependencies(str(path)) + if assets or unresolved or len(layers) != 1 or Path(layers[0].realPath).resolve() != path.resolve(): + raise ValueError('generated selected USD is not a closed single file') + stage = Usd.Stage.Open(str(path)) + if (not stage or str(stage.GetDefaultPrim().GetPath()) != '/Asset' + or not stage.HasAuthoredMetadata('metersPerUnit') or UsdGeom.GetStageMetersPerUnit(stage) != 1. + or not stage.HasAuthoredMetadata('upAxis') or UsdGeom.GetStageUpAxis(stage) != UsdGeom.Tokens.z): + raise ValueError('generated USD lacks the expected root, metric units or Z-up') + return stage + stage = verify_closure(root) + rigid = sum(prim.HasAPI(UsdPhysics.RigidBodyAPI) for prim in stage.Traverse()) + colliders = sum(prim.HasAPI(UsdPhysics.CollisionAPI) for prim in stage.Traverse()) + if rigid != 1 or colliders != 1: + raise ValueError('generated guide plate did not preserve its declared native body and collider') + output = Path(task['output']) + if output.exists() or output.is_symlink() or not Sdf.Layer.FindOrOpen(str(root)).Export(str(output)): + raise ValueError('could not export the isolated generated source') + verify_closure(output) + if _observe() != observed: + raise ValueError('USDCraft SDK runtime changed during generation') + details = {'check': 'passed', 'compile': 'passed', 'closure': 'resolved_locally', + 'native_rigid_bodies': rigid, 'native_colliders': colliders, + 'compiled_root_sha256': _sha(root), 'compile_report_sha256': _sha(artifacts.report_path)} + Path(task['runtime_output']).write_text(json.dumps(observed, sort_keys=True, indent=2) + '\n') + Path(task['report_output']).write_text(json.dumps(details, sort_keys=True, indent=2) + '\n') + + +def main(): + resource.setrlimit(resource.RLIMIT_CPU, (120, 120)) + resource.setrlimit(resource.RLIMIT_FSIZE, (32*1024**2, 32*1024**2)) + resource.setrlimit(resource.RLIMIT_AS, (8*1024**3, 8*1024**3)) + resource.setrlimit(resource.RLIMIT_NOFILE, (256, 256)) + task_path = Path(sys.argv[1]).resolve() + folder = Path.cwd().resolve() + if task_path != folder / 'sdk-backend-task.json': + raise ValueError('backend task must be the isolated job task') + task = json.loads(task_path.read_text()) + validate_task(task, folder, normalize=False) + _bootstrap(task) + run(task, folder) + + +if __name__ == '__main__': + main() diff --git a/src/simscene/generation/usdcraft_sdk.py b/src/simscene/generation/usdcraft_sdk.py new file mode 100644 index 0000000..66cfafb --- /dev/null +++ b/src/simscene/generation/usdcraft_sdk.py @@ -0,0 +1,229 @@ +"""Trusted fixed-template generation through an optional USDCraft SDK runtime.""" + +COMMIT = '46fec187bdce40845c30863a56143047edc4a263' +RECIPE = 'usdcraft_sdk_guide_plate_v1' +SDK_TIMEOUT_SECONDS = 180 + + +class GenerationCancelled(Exception): + """The durable job was cancelled while its SDK process group was running.""" + + +def _stop_group(process): + """Kill the isolated group and wait for live descendants to exit on Linux.""" + import os + from pathlib import Path + import signal + import time + + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait(timeout=5) + proc = Path('/proc') + if not proc.is_dir(): + raise RuntimeError('cannot verify that the SDK process group has terminated') + deadline = time.monotonic() + 5 + while True: + live = False + for entry in proc.iterdir(): + if not entry.name.isdecimal(): + continue + try: + raw = (entry / 'stat').read_text() + fields = raw[raw.rfind(')') + 2:].split() + if int(fields[2]) == process.pid and fields[0] not in ('Z', 'X'): + live = True + break + except (OSError, IndexError, ValueError): + continue + if not live: + return + if time.monotonic() >= deadline: + raise RuntimeError('SDK process group did not terminate') + time.sleep(.02) + + +def parameters(recipe_id, value): + if recipe_id != RECIPE: + raise ValueError('unknown trusted USDCraft SDK template') + from .sand3d import parameters as normalize + return normalize('guide_plate_v1', value) + + +def validate_runtime(runtime): + observed = runtime.get('observed', {}) if isinstance(runtime, dict) else {} + if (not isinstance(runtime, dict) or runtime.get('schema_version') != 1 + or runtime.get('backend') != 'usdcraft_sdk' or runtime.get('reviewed_commit') != COMMIT + or not isinstance(runtime.get('python'), str) or not runtime['python'] + or not isinstance(observed, dict) or observed.get('usdcraft_commit') != COMMIT + or observed.get('usdcraft_version') != '1.0.0' or observed.get('source_clean') is not True): + raise ValueError('generation_runtime_unavailable: configure an explicitly probed reviewed USDCraft SDK runtime') + return runtime + + +def _run(task, python, folder): + import os + from pathlib import Path + import subprocess + import tempfile + import time + from ..preparation.jobs import write + + python = str(Path(python).expanduser().absolute()) + if not Path(python).is_file(): + raise ValueError('independent USDCraft SDK interpreter is missing') + folder = Path(folder).resolve() + cache = folder / '.sdk-cache'; cache.mkdir(exist_ok=True) + temporary = folder / '.sdk-tmp'; temporary.mkdir(exist_ok=True) + bytecode = Path(tempfile.mkdtemp(prefix='.sdk-pycache-', dir=folder)) + task_path = folder / 'sdk-backend-task.json' + write(task_path, task) + env = {'PATH': str(Path(python).parent) + ':/usr/bin:/bin', + 'LANG': 'C.UTF-8', 'PYTHONPATH': str(Path(__file__).parents[2]), + 'XDG_CACHE_HOME': str(cache), 'TMPDIR': str(temporary), 'PYTHONDONTWRITEBYTECODE': '1', + 'PYTHONPYCACHEPREFIX': str(bytecode), + 'OMP_NUM_THREADS': '2', 'OPENBLAS_NUM_THREADS': '2', 'MALLOC_ARENA_MAX': '2'} + with (folder / 'sdk-backend.log').open('ab') as log: + command = [python, '-S', '-m', 'simscene.generation.usdcraft_backend_worker', str(task_path)] + process = subprocess.Popen(command, env=env, stdout=log, stderr=subprocess.STDOUT, + cwd=folder, start_new_session=True) + try: + deadline = time.monotonic() + SDK_TIMEOUT_SECONDS + while True: + if task.get('operation') == 'generate' and (folder.parent / 'cancel-request.json').exists(): + raise GenerationCancelled('USDCraft SDK generation cancelled') + remaining = deadline - time.monotonic() + if remaining <= 0: + raise subprocess.TimeoutExpired(command, SDK_TIMEOUT_SECONDS) + try: + code = process.wait(timeout=min(remaining, .1)) + break + except subprocess.TimeoutExpired: + pass + if code: + raise subprocess.CalledProcessError(code, command) + if task.get('operation') == 'generate' and (folder.parent / 'cancel-request.json').exists(): + raise GenerationCancelled('USDCraft SDK generation cancelled') + except BaseException: + # SDK compilation uses multiprocessing. Killing only the immediate + # backend leaves descendants alive and able to mutate job files. + _stop_group(process) + raise + + +def probe_runtime(python, output, *, checkout=None): + import json + from pathlib import Path + from ..preparation.jobs import write + output = Path(output).expanduser().resolve() + if output.exists(): + raise FileExistsError('runtime observation must be a new file') + output.parent.mkdir(parents=True, exist_ok=True) + folder = output.with_name(output.name + '.probe') + folder.mkdir() + result = folder / 'observed.json' + task = {'operation': 'probe', 'output': str(result)} + if checkout is not None: + task['checkout_path'] = str(Path(checkout).expanduser().absolute()) + _run(task, python, folder) + runtime = {'schema_version': 1, 'backend': 'usdcraft_sdk', 'python': str(Path(python).expanduser().absolute()), + 'reviewed_commit': COMMIT, 'observed': json.loads(result.read_text())} + validate_runtime(runtime) + write(output, runtime) + return runtime + + +def generate_asset(recipe_id, value, runtime, *, output_directory, config): + """Publish only the checked output of the shipped SDK guide-plate template.""" + import fcntl + import hashlib + from importlib.resources import files + import json + import os + from pathlib import Path + import shutil + import tempfile + from ..catalog.models import AssetRecord, AssetRef, stable_hash + from ..catalog.store import CatalogStore + from ..preparation.jobs import write + from .sand3d import sha + + p = parameters(recipe_id, value) + validate_runtime(runtime) + output = Path(output_directory).resolve() + output.mkdir(parents=True, exist_ok=False) + template = files('simscene.generation').joinpath('templates/' + RECIPE + '.py').read_bytes() + template_sha = hashlib.sha256(template).hexdigest() + task = {'operation': 'generate', 'recipe_id': recipe_id, 'parameters': p, + 'expected_runtime': runtime['observed'], 'template_sha256': template_sha, + 'output': str(output / 'source.usda'), + 'runtime_output': str(output / 'backend-runtime.json'), 'report_output': str(output / 'sdk-report.json')} + _run(task, runtime['python'], output) + source = output / 'source.usda' + if not source.is_file() or source.is_symlink() or not 0 < source.stat().st_size <= 16 * 1024**2: + raise ValueError('generation_failed: SDK output missing or exceeded size cap') + if json.loads((output / 'backend-runtime.json').read_text()) != runtime['observed']: + raise ValueError('generation_failed: SDK runtime changed during generation') + report_path = output / 'sdk-report.json' + report = json.loads(report_path.read_text()) + if not isinstance(report, dict) or any(report.get(key) != expected for key, expected in + [('check', 'passed'), ('compile', 'passed'), ('closure', 'resolved_locally')]): + raise ValueError('generation_failed: SDK checks or USD closure did not pass') + # These auxiliary build artifacts contain per-job paths or binary USD + # serialization details. Their hashes are kept in the job report, not in + # the immutable source manifest whose identity is the exported USDA. + volatile_report_fields = {'compiled_root_sha256', 'compile_report_sha256'} + stable_report = {key: item for key, item in report.items() if key not in volatile_report_fields} + identity = {'generation_contract_version': 3, 'recipe_id': recipe_id, 'parameters': p, 'seed': 0, + 'template_sha256': template_sha, 'toolchain': runtime, + 'output_sha256': sha(source)} + revision = stable_hash(identity) + ref = AssetRef('local-usdcraft-sdk', recipe_id, revision) + closure = [{'path': 'source.usda', 'sha256': identity['output_sha256'], 'size_bytes': source.stat().st_size}] + generated = {'schema_version': 1, 'schema': 'simscene.generated_source.v1', 'asset_ref': ref.to_dict(), + 'identity': identity, 'files': closure, 'root': 'source.usda', + 'unit_contract': {'input': 'm', 'output': 'm', 'up_axis': 'Z'}, + 'execution_scope': 'shipped template in a trusted Python and dependency runtime with process limits; no filesystem/network sandbox', + 'source_physics': 'native rigid body, mass and collider generated; inspection and preparation required', + 'generator_check': stable_report, 'physics_status': 'not_prepared', 'actual_download_bytes': 0} + write(output / 'generated.json', generated) + destination = Path(config['home']) / 'generated_assets' / revision + destination.parent.mkdir(parents=True, exist_ok=True) + with (destination.parent / '.publish.lock').open('a') as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + if destination.exists(): + published = json.loads((destination / 'generated.json').read_text()) + if published != generated or sha(destination / 'source.usda') != identity['output_sha256']: + raise ValueError('immutable generated source collision') + else: + with tempfile.TemporaryDirectory(dir=destination.parent, prefix='.publish-') as temporary: + staging = Path(temporary) / 'asset'; staging.mkdir() + shutil.copyfile(source, staging / 'source.usda') + write(staging / 'generated.json', generated) + os.replace(staging, destination) + descriptor = {'kind': 'generated_package', 'manifest_path': str(destination / 'generated.json'), + 'manifest_sha256': sha(destination / 'generated.json'), 'revision': revision} + license_info = {'status': 'known', 'license': 'Apache-2.0', 'evidence': 'declared', + 'basis': 'project-owned template and reviewed USDCraft SDK repository', + 'generator_license': 'Apache-2.0', 'notices_required': True, + 'license_url': 'https://github.com/NVlabs/USDCraft/blob/' + COMMIT + '/LICENSE', + 'notice_url': 'https://github.com/NVlabs/USDCraft/blob/' + COMMIT + '/NOTICE', + 'third_party_notices_url': 'https://github.com/NVlabs/USDCraft/blob/' + COMMIT + '/THIRD_PARTY_NOTICES.md'} + record = AssetRecord(ref=ref, title='USDCraft SDK parametric guide plate', category='guide', format='usda', + entry_path='source.usda', dimensions_m=[p['length_m'], p['width_m'], p['thickness_m']], + license=license_info, physics={'rigid_body': {'value': True, 'evidence': 'declared'}, + 'collider': {'value': True, 'evidence': 'declared'}}, + availability={'status': 'declared', 'granularity': 'generated', 'estimated_download_bytes': 0, + 'acquisition': descriptor}, + provenance={'generator': 'usdcraft_sdk', 'reviewed_commit': COMMIT, 'identity': identity, + 'generated_manifest_sha256': descriptor['manifest_sha256'], + 'source_physics': generated['source_physics'], 'generator_check': stable_report}, + evidence_level='declared', capabilities={}) + detail = CatalogStore(config['index_directory']).remember(record) + return {'asset_ref': ref.to_dict(), 'generated_manifest_path': descriptor['manifest_path'], + 'generated_manifest_sha256': descriptor['manifest_sha256'], 'detail_ref': detail, + 'sdk_report_path': str(report_path), 'sdk_report_sha256': sha(report_path), + 'runtime_trust_boundary': 'Python executable, third-party dependencies and local job storage are trusted; no filesystem/network sandbox', + 'actual_download_bytes': 0, 'physics_status': 'not_prepared', 'source_physics': generated['source_physics']} diff --git a/src/simscene/generation/worker.py b/src/simscene/generation/worker.py index 88d35d7..a930730 100644 --- a/src/simscene/generation/worker.py +++ b/src/simscene/generation/worker.py @@ -11,18 +11,32 @@ def execute(root): def phase(state,**fields): record.update(state=state,**fields);write(root/'job.json',record) try: + import simscene + if Path(simscene.__file__).resolve().parent != (root/'runtime'/'simscene').resolve(): + raise ValueError('generation supervisor was not loaded from the frozen job snapshot') if (root/'cancel-request.json').exists(): phase('cancelled');return task=json.loads((root/'task.json').read_text());config=json.loads((root/'config.json').read_text()) + if task.get('expected_generation_intent') is not None: + from .jobs import _check_expected_intent + _check_expected_intent(task['expected_generation_intent'],task['recipe_id'],task['parameters'], + task['runtime'],root/'runtime'/'simscene') phase('generating') - from .sand3d import generate_asset + if task['recipe_id'] == 'usdcraft_sdk_guide_plate_v1': + from .usdcraft_sdk import generate_asset + else: + from .sand3d import generate_asset result=generate_asset(task['recipe_id'],task['parameters'],task['runtime'],output_directory=root/'output',config=config) if (root/'cancel-request.json').exists(): phase('cancelled',result_retained=True);return write(root/'result.json',result) phase('completed',result=result) except Exception as error: - phase('failed',error=str(error),error_type=type(error).__name__) + from .usdcraft_sdk import GenerationCancelled + if isinstance(error, GenerationCancelled): + phase('cancelled', result_retained=False) + else: + phase('failed',error=str(error),error_type=type(error).__name__) if __name__=='__main__': diff --git a/src/simscene/jobs.py b/src/simscene/jobs.py index b5d1824..3708b64 100644 --- a/src/simscene/jobs.py +++ b/src/simscene/jobs.py @@ -292,9 +292,9 @@ def _start(scene_id, steps=120, seed=None, case_path=None, continue_on_controlle if not executable or not Path(executable).is_file(): raise SceneError('set SIMSCENE_ISAAC_PYTHON to the Isaac Sim python.sh path') scene = SceneStore().get(scene_id) - if case_snapshot and parsed.get('schema') in ('simscene.articulated_asset_smoke.v1','simscene.container_asset_smoke.v1','simscene.asset_gallery.v1','simscene.handoff_chain.v1'): + if case_snapshot and parsed.get('schema') in ('simscene.articulated_asset_smoke.v1','simscene.articulated_asset_two_joint.v1','simscene.container_asset_smoke.v1','simscene.asset_gallery.v1','simscene.handoff_chain.v1'): from importlib import import_module - module={'simscene.articulated_asset_smoke.v1':'articulated_asset_smoke','simscene.container_asset_smoke.v1':'container_asset_smoke','simscene.asset_gallery.v1':'asset_gallery','simscene.handoff_chain.v1':'handoff_chain'}[parsed['schema']] + module={'simscene.articulated_asset_smoke.v1':'articulated_asset_smoke','simscene.articulated_asset_two_joint.v1':'articulated_asset_two_joint','simscene.container_asset_smoke.v1':'container_asset_smoke','simscene.asset_gallery.v1':'asset_gallery','simscene.handoff_chain.v1':'handoff_chain'}[parsed['schema']] try: checker=import_module('.verification.'+module,__package__) checker.validate_case(parsed) diff --git a/src/simscene/mcp_server.py b/src/simscene/mcp_server.py index 992e28f..99ee11d 100644 --- a/src/simscene/mcp_server.py +++ b/src/simscene/mcp_server.py @@ -52,7 +52,7 @@ def scene_compile_recipe(scene_id: str, recipe_id: str, parameters: dict, bindin @threaded_tool() def asset_generate(recipe_id: str, parameters: dict, request_id: str | None = None) -> dict: - """Start a durable job for an explicitly configured independent Sand3D runtime and a shipped fixed template (guide_plate_v1 or open_receiver_v1). Accepts structured dimensions only, never external programs. Completion returns a generated AssetRef for ordinary asset_plan/asset_prepare; generation alone gives no physical pass.""" + """Start a durable job for a configured independent runtime and a shipped fixed template: Sand3D guide_plate_v1/open_receiver_v1 or USDCraft SDK usdcraft_sdk_guide_plate_v1. Accepts structured dimensions only, never external programs. Returns a generated AssetRef for ordinary asset_plan/asset_prepare; generation alone gives no physical pass.""" from .generation.jobs import start return start(recipe_id,parameters,request_id) @@ -394,7 +394,7 @@ def run_verify_lock(job_id: str) -> dict: @threaded_tool(annotations=_read_local) def run_verify(job_id: str, case_path: str | None = None, case_type: str | None = None, mode: str = 'positive', reference_job_id: str | None = None) -> dict: - """Check completed physical evidence against an independent pinned local case. Types: contact, suction, moving, repeated, domino, parallel, stream, mechanism, passive_network. Passive schemas infer their type. Mechanism detached_drawer and network no_trigger/broken_rope/locked_door modes require the matching reference_job_id and isolated declared changes. A single positive network run does not accept the whole stage: use run_verify_passive_suite with its frozen required controls. This verifier only reads measurements and never releases or moves a mechanism.""" + """Check completed physical evidence against an independent pinned local case. Passive and imported-asset schemas infer their type. For a two-joint control use mode='missing_second_joint_drive' with the control job_id and the positive reference_job_id. Mechanism detached_drawer and network no_trigger/broken_rope/locked_door modes also require a matching positive reference. A single positive network run does not accept the whole stage: use run_verify_passive_suite with its frozen required controls. This verifier only reads measurements and never releases or moves a mechanism.""" from .jobs import verify_task return verify_task(job_id,case_path,case_type,mode,reference_job_id) diff --git a/src/simscene/physics_binding.py b/src/simscene/physics_binding.py index c7cf537..7fd5418 100644 --- a/src/simscene/physics_binding.py +++ b/src/simscene/physics_binding.py @@ -1,4 +1,5 @@ """Validate prepared file closures and resolve explicit imported body paths.""" +import hashlib import json import re from pathlib import Path, PurePosixPath @@ -62,6 +63,66 @@ def validate_asset_binding(binding, *, require_dynamic=False, asset_path=None): main = _relative(manifest.get('main')) if main not in names or manifest.get('default_prim') != '/Asset': raise ValueError('prepared default prim or entry file is invalid') + if manifest.get('profile_id') in {'articulated_prop_v1','articulated_prop_v2'}: + if 'source/acquired.json' not in names: + raise ValueError('prepared native source attribution snapshot is missing') + acquired=json.loads((root/'source/acquired.json').read_text()) + if not isinstance(acquired,dict): + raise ValueError('prepared native source attribution snapshot is malformed') + original_ref=acquired.get('source_ref',acquired.get('asset_ref')) + if (manifest.get('source_ref')!=original_ref or manifest.get('license','unknown')!=acquired.get('license','unknown') + or manifest.get('provenance')!=acquired.get('provenance') + or manifest.get('source_manifest_sha256')!=acquired.get('manifest_sha256',acquired.get('source_manifest_hash'))): + raise ValueError('prepared native source attribution differs from its acquired snapshot') + source_files={item['path'][len('source/'):]:item for item in files + if item['path'].startswith('source/') and item['path']!='source/acquired.json'} + acquired_files=acquired.get('files') + is_artvip=isinstance(original_ref,dict) and original_ref.get('source_id')=='artvip' + if is_artvip and not acquired_files: + raise ValueError('prepared native source acquisition file list is empty') + if acquired_files: + if not isinstance(acquired_files,list): + raise ValueError('prepared native source acquisition file list is malformed') + acquired_manifest=acquired.get('manifest_sha256',acquired.get('source_manifest_hash')) + if acquired_manifest is not None: + computed=hashlib.sha256(json.dumps(acquired_files,sort_keys=True,separators=(',',':'),ensure_ascii=False).encode()).hexdigest() + if acquired_manifest!=computed: + raise ValueError('prepared native source acquisition manifest hash differs from its file list') + recorded={} + for item in acquired_files: + if not isinstance(item,dict):raise ValueError('prepared native source acquisition file is malformed') + name=_relative(item.get('path')) + if name in recorded:raise ValueError('duplicate prepared native source acquisition file') + recorded[name]=item + if set(recorded)!=set(source_files): + raise ValueError('prepared native source acquisition file closure differs') + for name,item in recorded.items(): + saved=source_files[name];size=item.get('size_bytes',item.get('size')) + if is_artvip and (not isinstance(item.get('sha256'),str) or type(size) is not int): + raise ValueError('ArtVIP source acquisition requires every file hash and size') + if item.get('sha256') not in (None,saved['sha256']) or size is not None and size!=saved.get('size_bytes',saved.get('size')): + raise ValueError('prepared native source acquisition file hash or size differs') + closure=[{'path':name,'sha256':entry['sha256'],'size_bytes':entry.get('size_bytes',entry.get('size'))} + for name,entry in sorted(source_files.items())] + closure_hash=hashlib.sha256(json.dumps(closure,sort_keys=True,separators=(',',':')).encode()).hexdigest() + if manifest.get('source_closure_sha256') is not None and manifest['source_closure_sha256']!=closure_hash: + raise ValueError('prepared native source closure hash differs from its snapshot') + source_root=manifest.get('source_root') + if source_root is not None: + source_root=_relative(source_root) + matches=[item for item in files if item.get('path')==source_root and item.get('sha256')==manifest.get('source_sha256')] + if not source_root.startswith('source/') or len(matches)!=1: + raise ValueError('prepared native source attribution has an invalid root hash') + provenance=manifest.get('provenance') + if isinstance(original_ref,dict) and original_ref.get('source_id')=='artvip': + if not isinstance(provenance,dict) or provenance.get('repository')!='X-Humanoid/ArtVIP' or provenance.get('metadata_revision')!=original_ref.get('revision'): + raise ValueError('ArtVIP source attribution has an inconsistent repository or revision') + tree=provenance.get('root_tree_entry') + if (not isinstance(tree,dict) or not isinstance(tree.get('lfs'),dict) or not isinstance(tree.get('path'),str) + or tree['lfs'].get('oid')!=manifest.get('source_sha256') + or PurePosixPath(tree.get('path','')).parent.as_posix()!=original_ref.get('asset_id') + or source_root is not None and source_root!='source/'+tree.get('path','')): + raise ValueError('ArtVIP source attribution differs from its pinned object metadata') if asset_path is not None and Path(asset_path).expanduser().absolute() != root / main: raise ValueError('scene asset_path does not match its prepared binding') body_map = manifest.get('body_map', {}) @@ -85,6 +146,14 @@ def validate_asset_binding(binding, *, require_dynamic=False, asset_path=None): report=manifest.get('articulation_report') if not isinstance(report,dict) or report.get('body_map') != body_map or report.get('joint_map') != manifest.get('joint_map'): raise ValueError('articulated prepared maps must match the inspected immutable graph') + parameters=manifest.get('parameters',{}) + if parameters.get('source_physics_policy') == 'repair_explicit': + from .preparation.native_repairs import validate_repair_report,annotate_repaired_graph + repairs=validate_repair_report(parameters.get('native_physics_repairs'),manifest.get('physics_repairs')) + if annotate_repaired_graph(report,repairs) != report: + raise ValueError('prepared native repair report lacks derived graph provenance') + elif manifest.get('physics_repairs') is not None or parameters.get('native_physics_repairs') is not None: + raise ValueError('native repair report requires the explicit repair policy') from .worker.mechanism import validate_binding joints={} for local_id,entry in manifest.get('joint_map',{}).items(): @@ -94,7 +163,27 @@ def validate_asset_binding(binding, *, require_dynamic=False, asset_path=None): raise ValueError('prepared joint references an undeclared body') joints[local_id]=dict(entry,joint_path='/World/validation/'+rel,parent_body='/World/validation/'+body_map[parent]['relative_prim_path'] if parent else None,child_body='/World/validation/'+body_map[child]['relative_prim_path']) validate_binding({'joints':joints}) - if require_dynamic and manifest.get('profile_id') != 'articulated_prop_v1': + elif manifest.get('profile_id') == 'articulated_prop_v2': + from .preparation.articulation_v2 import runtime_joint + from .worker.mechanism_v2 import TwoDofTensorState + report=manifest.get('articulation_report') + if (not isinstance(report,dict) or report.get('schema')!='simscene.articulation_inspection.v2' + or report.get('body_map')!=body_map or report.get('joint_map')!=manifest.get('joint_map') + or manifest.get('parameters',{}).get('source_physics_policy')!='preserve_valid' + or manifest.get('physics_repairs') is not None): + raise ValueError('two-DOF prepared maps must match the preserved inspected graph') + root_id=report.get('root_body_id') + if root_id not in body_map:raise ValueError('two-DOF prepared graph requires an explicit root body') + def body_path(local_id):return '/World/validation/'+_relative(body_map[local_id]['relative_prim_path'],allow_root=True) + joints={} + for local_id,entry in manifest.get('joint_map',{}).items(): + parent=entry.get('parent_body_id');child=entry.get('child_body_id') + if parent not in body_map or child not in body_map:raise ValueError('two-DOF joint references an undeclared body') + joints[local_id]=dict(runtime_joint(entry),joint_path='/World/validation/'+_relative(entry['relative_prim_path']), + parent_body=body_path(parent),child_body=body_path(child)) + TwoDofTensorState._validate_binding({'profile_id':'articulated_prop_v2','joints':joints, + 'motion_bodies':[body_path(name) for name in body_map],'root_body':body_path(root_id)}) + if require_dynamic and manifest.get('profile_id') not in {'articulated_prop_v1','articulated_prop_v2'}: if manifest.get('profile_id') != 'rigid_prop_v1' or set(body_map) != {'main'} or body_map['main'].get('role') != 'rigid': raise ValueError('dynamic imported assets require a prepared rigid_prop_v1 main body') if not all(body_map['main'].get(key) for key in ('visual_relative_prim_paths', 'collider_relative_prim_paths')): @@ -144,9 +233,18 @@ def resolve_body_bindings(stage, spec): anchor = stage.GetPrimAtPath(base) if not anchor or not anchor.IsActive(): raise ValueError('prepared asset instance is missing') - if manifest['profile_id']=='articulated_prop_v1': - from .preparation.articulation import resolve_instance - result[object_id]=resolve_instance(stage,anchor,manifest) + if manifest['profile_id'] in {'articulated_prop_v1','articulated_prop_v2'}: + if manifest['profile_id']=='articulated_prop_v1': + from .preparation.articulation import resolve_instance,verify_source_graph + verify_source_graph(package,manifest) + result[object_id]=resolve_instance(stage,anchor,manifest) + else: + from .preparation.articulation_v2 import resolve_instance_v2,verify_source_graph_v2 + verify_source_graph_v2(package,manifest) + result[object_id]=resolve_instance_v2(stage,anchor,manifest) + if manifest.get('physics_repairs') is not None: + result[object_id]['native_repairs_ref']={'manifest_path':binding['manifest_path'], + 'manifest_sha256':binding['manifest_sha256'],'json_pointer':'/physics_repairs'} for motion in result[object_id]['motion_bodies']: if motion in claimed:raise ValueError('duplicate prepared motion body') claimed.add(motion) diff --git a/src/simscene/preparation/articulation.py b/src/simscene/preparation/articulation.py index c98a696..d7f20b9 100644 --- a/src/simscene/preparation/articulation.py +++ b/src/simscene/preparation/articulation.py @@ -12,8 +12,12 @@ def _fail(message): def canonical_stage(stage): - from pxr import UsdGeom - if (not stage.HasAuthoredMetadata('metersPerUnit') or abs(UsdGeom.GetStageMetersPerUnit(stage)-1.) > 1e-9 + from pxr import UsdGeom, UsdPhysics + metres=UsdGeom.GetStageMetersPerUnit(stage) + kilograms=UsdPhysics.GetStageKilogramsPerUnit(stage) + if not math.isfinite(kilograms) or abs(kilograms-1.) > 1e-9: + _fail('native articulated physics requires kilogramsPerUnit=1; mass/inertia conversion unsupported') + if (not stage.HasAuthoredMetadata('metersPerUnit') or not math.isfinite(metres) or abs(metres-1.) > 1e-9 or not stage.HasAuthoredMetadata('upAxis') or UsdGeom.GetStageUpAxis(stage) != UsdGeom.Tokens.z): _fail('native articulated physics requires authored metres and Z-up; joint/inertia conversion unsupported') @@ -200,10 +204,120 @@ def transform_world_anchors(stage, root): return records +def _verify_physical_prims(source, prepared): + """Compare source-replayed and derived collider/joint physical inputs.""" + from pxr import Usd,UsdGeom,UsdPhysics,UsdShade + source_root=source.GetDefaultPrim();prepared_root=prepared.GetPrimAtPath('/Asset/Native') + if not source_root or not prepared_root:_fail('source/derived physical graph root is missing') + def nodes(root): + prefix=str(root.GetPath()) + return {str(prim.GetPath())[len(prefix):].lstrip('/'):prim for prim in Usd.PrimRange(root) + if (prim.HasAPI(UsdPhysics.RigidBodyAPI) or prim.HasAPI(UsdPhysics.CollisionAPI) + or prim.HasAPI(UsdPhysics.ArticulationRootAPI) or prim.IsA(UsdPhysics.Joint))} + left,right=nodes(source_root),nodes(prepared_root) + if set(left)!=set(right):_fail('source and derived physics prim closures differ') + geometry={'axis','doubleSided','extent','faceVertexCounts','faceVertexIndices','height', + 'holeIndices','orientation','points','radius','size','subdivisionScheme'} + def selected_attributes(prim): + return {attr.GetName():attr for attr in prim.GetAttributes() if attr.HasAuthoredValueOpinion() + and (attr.GetName() in geometry or attr.GetName()=='xformOpOrder' + or attr.GetName().startswith(('physics:','physx','drive:','xformOp:')))} + def schemas(prim): + raw=prim.GetMetadata('apiSchemas') + return sorted(str(item) for item in (raw.GetAppliedItems() if raw else []) + if str(item).lower().startswith(('physics','physx'))) + def targets(prim,root): + prefix=str(root.GetPath()) + def normalize(path): + value=str(path) + return value[len(prefix):] if value==prefix or value.startswith(prefix+'/') else value + return {rel.GetName():[normalize(path) for path in rel.GetTargets()] for rel in prim.GetRelationships() + if rel.GetName().startswith(('physics:','physx','material:binding:physics'))} + def material(prim,root): + if not prim.HasAPI(UsdPhysics.CollisionAPI):return None + value,_=UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial('physics') + if not value:return None + path=str(value.GetPath());prefix=str(root.GetPath()) + path=path[len(prefix):] if path==prefix or path.startswith(prefix+'/') else path + physical=selected_attributes(value.GetPrim()) + return path,schemas(value.GetPrim()),{name:(str(attr.GetTypeName()),attr.Get()) for name,attr in physical.items()} + for path in sorted(left): + a,b=left[path],right[path] + if a.GetTypeName()!=b.GetTypeName() or schemas(a)!=schemas(b) or targets(a,source_root)!=targets(b,prepared_root): + _fail('source and derived physics prim type, schema or relationships differ: '+path) + aa,bb=selected_attributes(a),selected_attributes(b) + if set(aa)!=set(bb):_fail('source and derived physics attributes differ: '+path) + for name in aa: + if aa[name].GetTypeName()!=bb[name].GetTypeName() or aa[name].Get()!=bb[name].Get(): + _fail('source and derived physics attribute differs: '+path+'/'+name) + xa,xb=UsdGeom.Xformable(a),UsdGeom.Xformable(b) + if bool(xa)!=bool(xb):_fail('source and derived physics transforms differ: '+path) + if xa and xa.ComputeLocalToWorldTransform(Usd.TimeCode.Default())!=xb.ComputeLocalToWorldTransform(Usd.TimeCode.Default()): + _fail('source and derived collider/body transform differs: '+path) + if material(a,source_root)!=material(b,prepared_root): + _fail('source and derived collision physics materials differ: '+path) + + +def verify_source_graph(package, manifest): + """Replay the declared preparation against the package's hashed source. + + This is a consistency check, not authentication of a caller-supplied pin. + It prevents a self-consistent derived graph from being mislabeled as the + original source when the immutable source snapshot says otherwise. + """ + import copy + from pathlib import Path + from pxr import Usd + package=Path(package) + source_root=manifest.get('source_root') + candidates=[item['path'] for item in manifest.get('files',[]) + if item.get('path','').startswith('source/') and item.get('sha256')==manifest.get('source_sha256')] + if source_root is not None: + if source_root not in candidates:_fail('source root differs from the hashed source snapshot') + candidates=[source_root] + if len(candidates)!=1:_fail('source snapshot does not uniquely identify its native USD root') + source=Usd.Stage.Open(str(package/candidates[0])) + if not source:_fail('source snapshot USD could not be opened') + repairs=manifest.get('parameters',{}).get('native_physics_repairs') + if repairs is not None: + from .native_repairs import apply_native_repairs + source=Usd.Stage.Open(source.Flatten()) + if apply_native_repairs(source,repairs)!=manifest.get('physics_repairs'): + _fail('source physics repair report differs from the hashed source') + graph=copy.deepcopy(inspect_articulation(source)) + def wrap(path):return 'Native'+('/'+path if path else '') + for entry in graph['body_map'].values(): + if entry['role']!='static': + entry['relative_prim_path']=wrap(entry['relative_prim_path']) + entry['visual_relative_prim_paths']=[wrap(p) for p in entry['visual_relative_prim_paths']] + entry['collider_relative_prim_paths']=[wrap(p) for p in entry['collider_relative_prim_paths']] + for entry in graph['joint_map'].values():entry['relative_prim_path']=wrap(entry['relative_prim_path']) + for name in ('fixed_joint_paths','articulation_root_paths'):graph[name]=[wrap(p) for p in graph[name]] + if repairs is not None: + from .native_repairs import annotate_repaired_graph + graph=annotate_repaired_graph(graph,repairs) + else: + # Older v1 reports predate the raw-attribute inventory. Their complete + # source and prepared USD physical attributes are still compared below. + recorded=manifest.get('articulation_report',{}).get('joint_map',{}).get('main',{}) + for key in ('native_authored_attributes','native_attribute_units'): + if key not in recorded:graph['joint_map']['main'].pop(key,None) + if graph!=manifest.get('articulation_report'): + _fail('prepared articulated graph differs from its hashed source and declared repairs') + prepared=Usd.Stage.Open(str(package/manifest['main'])) + if not prepared:_fail('prepared native USD could not be opened') + _verify_physical_prims(source,prepared) + return True + + def resolve_instance(stage, anchor, manifest): """Verify final loaded graph and return explicit body and joint bindings.""" from ..worker.mechanism import validate_binding actual=inspect_articulation(stage,anchor) + repairs=manifest.get('parameters',{}).get('native_physics_repairs') + if repairs is not None: + from .native_repairs import annotate_repaired_graph + actual=annotate_repaired_graph(actual,repairs) expected=manifest['articulation_report'] # World-frame values may differ due to documented rigid instance placement. for key in ('body_map','fixed_joint_paths','articulation_root_paths'): @@ -225,6 +339,12 @@ def path(relative):return base+('/'+relative if relative else '') 'visual_roots':[path(p) for p in entry['visual_relative_prim_paths']], 'collider_paths':[path(p) for p in entry['collider_relative_prim_paths']]} for local_id,entry in actual['body_map'].items()} + if repairs is not None: + for local_id,entry in actual['body_map'].items(): + if entry.get('physics_provenance') == 'native_link_with_explicit_experimental_mass': + bodies[local_id]['mass_provenance']='explicit_experimental_assumption' + elif entry.get('physics_provenance') == 'native_link_with_explicit_experimental_mass_overriding_source_material_density': + bodies[local_id]['mass_provenance']='explicit_experimental_assumption_overrides_source_material_density' joints={} for joint_id,entry in actual['joint_map'].items(): joints[joint_id]=dict(entry,joint_path=path(entry['relative_prim_path']), diff --git a/src/simscene/preparation/articulation_v2.py b/src/simscene/preparation/articulation_v2.py new file mode 100644 index 0000000..6967f3d --- /dev/null +++ b/src/simscene/preparation/articulation_v2.py @@ -0,0 +1,420 @@ +"""Conservative static inventory of a native two-coordinate articulation. + +This module does not prepare an asset or establish runtime PhysX independence. +Only a directed tree of two single-axis joints and three rigid links is admitted. +""" +import copy +import math + +from .articulation import _fail, _finite, canonical_stage + + +def _relative(root_path, path): + value = str(path) + if value != root_path and not value.startswith(root_path + '/'): + _fail('native articulation path escapes the selected root') + return value[len(root_path):].lstrip('/') + + +def _check_rigid_ancestors(prim): + """Reject unsafe local transforms even when ancestor scales cancel out.""" + from pxr import Usd, UsdGeom + + current = prim + while current and not current.IsPseudoRoot(): + if any(attr.GetNumTimeSamples() for attr in current.GetAttributes()): + _fail('native joint/body ancestors cannot have time-sampled attributes') + xformable = UsdGeom.Xformable(current) + if xformable: + matrix = xformable.GetLocalTransformation(Usd.TimeCode.Default()) + if not all(math.isfinite(matrix[i][j]) for i in range(4) for j in range(4)): + _fail('native joint/body ancestors require finite rigid transforms') + axes = [matrix.ExtractRotationMatrix().GetRow(i) for i in range(3)] + if (any(abs(axis.GetLength() - 1.) > 1e-6 for axis in axes) + or any(abs(axes[i] * axes[j]) > 1e-6 for i in range(3) for j in range(i)) + or matrix.GetDeterminant() <= 0): + _fail('native joint/body ancestors require unit scale, no shear or reflection') + current = current.GetParent() + + +def _native_value(value): + """Keep USD values JSON-safe, including authored infinity sentinels.""" + if value is None or isinstance(value, (str, bool, int)): + return value + if isinstance(value, float): + if math.isfinite(value): + return value + return {'USD_sentinel': 'nan' if math.isnan(value) else + 'positive_infinity' if value > 0 else 'negative_infinity'} + if hasattr(value, 'GetReal'): + return [_native_value(float(value.GetReal())), + *[_native_value(float(v)) for v in value.GetImaginary()]] + try: + return [_native_value(v) for v in value] + except TypeError: + _fail('unsupported native physics attribute value') + + +def _raw_attributes(prim): + return {attr.GetName(): _native_value(attr.Get()) for attr in prim.GetAttributes() + if attr.HasAuthoredValueOpinion() + and attr.GetName().startswith(('physics:', 'physx', 'drive:'))} + + +def _schemas(prim): + metadata = prim.GetMetadata('apiSchemas') + return [str(value) for value in metadata.GetAppliedItems()] if metadata else [] + + +def _joint_frames(joint): + result = {} + for suffix in ('0', '1'): + position = getattr(joint, 'GetLocalPos' + suffix + 'Attr')().Get() + rotation = getattr(joint, 'GetLocalRot' + suffix + 'Attr')().Get() + result['local_pos' + suffix + '_m'] = _finite(position, 'joint local position') + if rotation is None: + _fail('missing native joint local rotation') + q = _finite([rotation.GetReal(), *rotation.GetImaginary()], 'joint local rotation') + if abs(sum(value * value for value in q) - 1.) > 1e-5: + _fail('native joint local rotation must be normalized') + result['local_rot' + suffix + '_wxyz'] = q + return result + + +def _endpoints(joint, bodies): + endpoints = [] + for relationship in (joint.GetBody0Rel(), joint.GetBody1Rel()): + targets = list(relationship.GetTargets()) + if len(targets) > 1 or targets and str(targets[0]) not in bodies: + _fail('native joint endpoint must resolve to one preserved rigid body or world') + endpoints.append(str(targets[0]) if targets else None) + return endpoints + + +def _require_enabled(joint): + if joint.GetJointEnabledAttr().Get() is not True: + _fail('native joint is disabled') + if joint.GetExcludeFromArticulationAttr().Get() is not False: + _fail('native joint is excluded from the articulation') + + +def _drive(prim, instance): + from pxr import UsdPhysics + + schemas = _schemas(prim) + drives = [s for s in schemas if s.startswith('PhysicsDriveAPI:')] + if any(s != 'PhysicsDriveAPI:' + instance for s in drives): + _fail('native joint has an unsupported multiaxis drive') + if not drives: + return None + drive = UsdPhysics.DriveAPI(prim, instance) + kind = str(drive.GetTypeAttr().Get()) + if kind not in ('force', 'acceleration'): + _fail('native joint has an unsupported drive type') + values = {} + for key, suffix in [('stiffness', 'Stiffness'), ('damping', 'Damping'), + ('max_force', 'MaxForce'), ('target_position', 'TargetPosition'), + ('target_velocity', 'TargetVelocity')]: + try: + value = float(getattr(drive, 'Get' + suffix + 'Attr')().Get()) + except (TypeError, ValueError): + _fail('native drive has a missing parameter') + if not math.isfinite(value) and not (key == 'max_force' and value == math.inf): + _fail('native drive contains a nonfinite value') + if key in ('stiffness', 'damping', 'max_force') and value < 0: + _fail('native drive contains a negative gain or effort') + values[key] = _native_value(value) + return dict(values, instance=instance, type=kind, units='native_USD_schema_units', + authored_attributes=sorted(a.GetName() for a in prim.GetAttributes() + if a.GetName().startswith('drive:' + instance + ':') and a.HasAuthoredValueOpinion())) + + +def _body_properties(prim): + from pxr import UsdPhysics + + rigid = UsdPhysics.RigidBodyAPI(prim) + if rigid.GetRigidBodyEnabledAttr().Get() is not True or rigid.GetKinematicEnabledAttr().Get() is not False: + _fail('native links must be enabled nonkinematic rigid bodies') + _check_rigid_ancestors(prim) + mass = UsdPhysics.MassAPI(prim) + if not mass or not mass.GetMassAttr().HasAuthoredValueOpinion(): + _fail('native link lacks explicit mass') + value = _finite([mass.GetMassAttr().Get()], 'mass', positive=True)[0] + diagonal_value = mass.GetDiagonalInertiaAttr().Get() + center_value = mass.GetCenterOfMassAttr().Get() + orientation = mass.GetPrincipalAxesAttr().Get() + if diagonal_value is None or center_value is None or orientation is None: + _fail('native link mass properties cannot be blocked') + diagonal = list(diagonal_value) + if diagonal == [0., 0., 0.]: + inertia = None + else: + inertia = _finite(diagonal, 'diagonal inertia', positive=True) + if max(inertia) > sum(inertia) - max(inertia) + 1e-8: + _fail('native link inertia violates principal moment triangle inequality') + center = list(center_value) + center = None if center == [-math.inf] * 3 else _finite(center, 'center of mass') + orientation = [orientation.GetReal(), *orientation.GetImaginary()] + orientation = None if orientation == [0.] * 4 else _finite(orientation, 'inertia principal axes') + if orientation is not None and abs(sum(v * v for v in orientation) - 1.) > 1e-5: + _fail('native inertia principal axes must be normalized') + return {'mass_kg': value, 'diagonal_inertia_kg_m2': inertia, + 'center_of_mass_local_m': center, 'principal_axes_wxyz': orientation, + 'inertia_provenance': ('engine_computes_from_preserved_native_colliders_and_authored_mass' + if inertia is None else 'preserved_native_USD_authored_inertia'), + 'physics_provenance': 'preserved_native_USD_authored_values'} + + +def inspect_articulation_v2(stage, root=None): + """Return a stable static graph report; raise PreparationError if unsupported. + + Link and joint IDs are generated by sorted source-relative path. The report + describes two candidate joint coordinates, not a runtime DOF measurement. + """ + from pxr import Usd, UsdGeom, UsdPhysics + + canonical_stage(stage) + if not math.isfinite(UsdGeom.GetStageMetersPerUnit(stage)): + _fail('native articulated physics requires finite metres and Z-up') + mass_units = UsdPhysics.GetStageKilogramsPerUnit(stage) + if not math.isfinite(mass_units) or abs(mass_units - 1.) > 1e-9: + _fail('native articulated physics requires kilogramsPerUnit=1') + root = root or stage.GetDefaultPrim() + if not root: + _fail('native articulated source requires a default prim') + root_path = str(root.GetPath()) + prims = list(Usd.PrimRange(root)) + bodies, colliders, moving, fixed, articulation_roots = {}, {}, [], [], [] + for prim in prims: + if any(attr.GetNumTimeSamples() for attr in prim.GetAttributes()): + _fail('native articulated time-sampled attributes are unsupported') + schemas = _schemas(prim) + tokens = [prim.GetTypeName(), *schemas, *(p.GetName() for p in prim.GetProperties())] + if any(marker in token.lower() for token in tokens for marker in ('mimic', 'gear', 'tendon', 'coupl')): + _fail('native coupling, mimic, gear or tendon is unsupported') + if any(s.startswith('PhysicsLimitAPI:') for s in schemas): + _fail('native multi-axis limit schema is unsupported') + if prim.HasAPI(UsdPhysics.ArticulationRootAPI): + articulation_roots.append(str(prim.GetPath())) + if prim.HasAPI(UsdPhysics.RigidBodyAPI): + bodies[str(prim.GetPath())] = _body_properties(prim) + if prim.HasAPI(UsdPhysics.CollisionAPI): + if not UsdPhysics.CollisionAPI(prim).GetCollisionEnabledAttr().Get(): + _fail('disabled native collider cannot qualify an articulated link') + owner = prim + while owner and not owner.HasAPI(UsdPhysics.RigidBodyAPI): + owner = owner.GetParent() + owner_path = str(owner.GetPath()) if owner else None + if owner_path is not None: + _relative(root_path, owner_path) + colliders.setdefault(owner_path, []).append(str(prim.GetPath())) + if prim.IsA(UsdPhysics.Joint): + _check_rigid_ancestors(prim) + if prim.IsA(UsdPhysics.FixedJoint): + fixed.append(prim) + elif prim.IsA(UsdPhysics.RevoluteJoint) or prim.IsA(UsdPhysics.PrismaticJoint): + moving.append(prim) + else: + _fail('native multi-axis or unsupported joint type') + elif 'joint' in prim.GetTypeName().lower(): + _fail('unrecognized native joint type') + # Constraints outside the selected root must not silently connect into the + # inspected graph; unrelated scene joints remain outside this inventory. + for prim in stage.Traverse(): + path = str(prim.GetPath()) + if path == root_path or path.startswith(root_path + '/'): + continue + tokens = [prim.GetTypeName(), *_schemas(prim), *(p.GetName() for p in prim.GetProperties())] + is_constraint = (prim.IsA(UsdPhysics.Joint) or 'joint' in prim.GetTypeName().lower() + or any(marker in token.lower() for token in tokens + for marker in ('mimic', 'gear', 'tendon', 'coupl'))) + if is_constraint: + for relationship in prim.GetRelationships(): + for target in relationship.GetTargets(): + target_path = str(target.GetPrimPath()) + if target_path == root_path or target_path.startswith(root_path + '/'): + _fail('native articulation has a constraint outside the selected root') + if len(bodies) != 3 or len(moving) != 2 or len(fixed) > 1: + _fail('two-DOF profile requires three rigid links, two scalar joints and at most one world fixed joint') + for path in bodies: + parent = stage.GetPrimAtPath(path).GetParent() + while parent and not parent.IsPseudoRoot(): + if str(parent.GetPath()) in bodies: + _fail('nested native rigid bodies are unsupported') + parent = parent.GetParent() + if not colliders.get(path): + _fail('native articulated link lacks enabled collision') + paths = sorted(bodies) + ids = {path: 'link' + str(index) for index, path in enumerate(paths)} + body_map = {ids[path]: dict(bodies[path], relative_prim_path=_relative(root_path, path), role='rigid', + visual_relative_prim_paths=[_relative(root_path, path)], + collider_relative_prim_paths=sorted(_relative(root_path, p) for p in colliders[path])) + for path in paths} + incoming = {path: 0 for path in paths} + edges, joint_map = {}, {} + for index, prim in enumerate(sorted(moving, key=lambda item: str(item.GetPath()))): + joint = UsdPhysics.Joint(prim) + _require_enabled(joint) + parent, child = _endpoints(joint, bodies) + if parent is None or child is None or parent == child: + _fail('moving joint must connect two distinct preserved rigid links') + incoming[child] += 1 + edges.setdefault(parent, []).append(child) + angular = prim.IsA(UsdPhysics.RevoluteJoint) + typed = UsdPhysics.RevoluteJoint(prim) if angular else UsdPhysics.PrismaticJoint(prim) + if not typed.GetAxisAttr().HasAuthoredValueOpinion() or typed.GetAxisAttr().Get() not in ('X', 'Y', 'Z'): + _fail('native joint requires an explicitly authored X, Y or Z axis') + if not typed.GetLowerLimitAttr().HasAuthoredValueOpinion() or not typed.GetUpperLimitAttr().HasAuthoredValueOpinion(): + _fail('native joint requires authored finite limits') + limits = _finite([typed.GetLowerLimitAttr().Get(), typed.GetUpperLimitAttr().Get()], 'joint limits') + if limits[0] >= limits[1]: + _fail('native joint requires ordered nonlocked limits') + if angular: + limits = [math.radians(value) for value in limits] + native_drive = _drive(prim, 'angular' if angular else 'linear') + entry = {'relative_prim_path': _relative(root_path, prim.GetPath()), + 'parent_body_id': ids[parent], 'child_body_id': ids[child], + 'type': 'revolute' if angular else 'prismatic', 'axis': str(typed.GetAxisAttr().Get()), + 'limits': limits, 'position_unit': 'rad' if angular else 'm', + 'joint_enabled': True, 'exclude_from_articulation': False, + 'drive': native_drive, 'passive': native_drive is None, + 'native_authored_attributes': _raw_attributes(prim), + 'native_attribute_units': 'preserved_USD_schema_units', + 'physics_provenance': 'preserved_native_USD_joint_not_synthesized'} + entry.update(_joint_frames(joint)) + joint_map['joint' + str(index)] = entry + roots = [path for path, count in incoming.items() if count == 0] + if len(roots) != 1 or any(count > 1 for count in incoming.values()): + _fail('native articulation requires one root and one incoming joint per nonroot link') + graph_root = roots[0] + visited, pending = set(), [graph_root] + while pending: + current = pending.pop() + if current in visited: + _fail('native articulation graph contains a cycle') + visited.add(current) + pending.extend(edges.get(current, [])) + if visited != set(paths): + _fail('native articulation graph must be connected and acyclic') + fixed_map = {} + for prim in fixed: + joint = UsdPhysics.Joint(prim) + _require_enabled(joint) + if any(schema.startswith('PhysicsDriveAPI:') for schema in _schemas(prim)): + _fail('world fixed joint cannot have a drive') + if _endpoints(joint, bodies) != [None, graph_root]: + _fail('only one world-to-root fixed joint is supported') + entry = {'relative_prim_path': _relative(root_path, prim.GetPath()), 'type': 'fixed', + 'parent_body_id': None, 'child_body_id': ids[graph_root], 'drive': None, + 'joint_enabled': True, 'exclude_from_articulation': False, + 'native_authored_attributes': _raw_attributes(prim)} + entry.update(_joint_frames(joint)) + fixed_map['fixed0'] = entry + if len(articulation_roots) != 1: + _fail('native articulation requires one explicit articulation root') + declared_root = articulation_roots[0] + valid_root = (declared_root == graph_root or graph_root.startswith(declared_root + '/') + or fixed and declared_root == str(fixed[0].GetPath())) + if not valid_root: + _fail('native articulation root does not identify the graph root') + return {'schema': 'simscene.articulation_inspection.v2', 'schema_version': 2, + 'body_map': body_map, 'joint_map': joint_map, 'root_body_id': ids[graph_root], + 'fixed_joint_paths': sorted(_relative(root_path, p.GetPath()) for p in fixed), + 'fixed_joint_map': fixed_map, + 'articulation_root_paths': [_relative(root_path, declared_root)], + 'static_collider_paths': sorted(_relative(root_path, p) for p in colliders.get(None, [])), + 'scope': 'static native tree with two candidate coordinates; not runtime DOF or independence verification'} + + +def runtime_joint(entry): + """Convert a supported native force drive to the existing SI contract.""" + result=copy.deepcopy(entry);drive=entry.get('drive') + if drive is None:return result + effort=drive.get('max_force');stiffness=drive.get('stiffness');damping=drive.get('damping') + target=drive.get('target_position');velocity=drive.get('target_velocity') + if (drive.get('type')!='force' or any(type(v) not in (int,float) or not math.isfinite(v) + for v in (effort,stiffness,damping,target,velocity)) or effort<=0 or stiffness<0 or damping<0): + _fail('two-DOF runtime requires a finite native force drive or no drive') + angular=entry['type']=='revolute';gain=180/math.pi if angular else 1.;position=math.pi/180 if angular else 1. + result['drive']={'stiffness':stiffness*gain,'damping':damping*gain,'max_effort':effort, + 'target_position':target*position,'target_velocity':velocity*position, + 'provenance':'preserved_native_force_drive_normalized_to_SI'} + return result + + +def verify_source_graph_v2(package,manifest): + """Compare a preserved source and its prepared physical graph and geometry.""" + from pathlib import Path + from pxr import Usd + from .articulation import _verify_physical_prims + package=Path(package);source_root=manifest.get('source_root') + candidates=[item['path'] for item in manifest.get('files',[]) + if item.get('path','').startswith('source/') and item.get('sha256')==manifest.get('source_sha256')] + if source_root is not None: + if source_root not in candidates:_fail('two-DOF source root differs from its hashed snapshot') + candidates=[source_root] + if len(candidates)!=1:_fail('two-DOF source snapshot must identify one native USD root') + source=Usd.Stage.Open(str(package/candidates[0]));prepared=Usd.Stage.Open(str(package/manifest['main'])) + if not source or not prepared:_fail('two-DOF source or prepared USD could not be opened') + graph=inspect_articulation_v2(source) + def wrap(path):return 'Native'+('/'+path if path else '') + for entry in graph['body_map'].values(): + entry['relative_prim_path']=wrap(entry['relative_prim_path']) + for key in ('visual_relative_prim_paths','collider_relative_prim_paths'): + entry[key]=[wrap(p) for p in entry[key]] + for mapping in ('joint_map','fixed_joint_map'): + for entry in graph[mapping].values():entry['relative_prim_path']=wrap(entry['relative_prim_path']) + for key in ('fixed_joint_paths','articulation_root_paths','static_collider_paths'): + graph[key]=[wrap(p) for p in graph[key]] + if graph!=manifest.get('articulation_report'):_fail('two-DOF prepared graph differs from its source') + _verify_physical_prims(source,prepared) + return True + + +def resolve_instance_v2(stage,anchor,manifest): + """Resolve and re-inspect a single composed two-coordinate native tree.""" + from pxr import Gf,Usd,UsdGeom + actual=inspect_articulation_v2(stage,anchor);expected=manifest['articulation_report'] + # A documented instance placement transforms only the world end of a fixed + # anchor. Compare all other fixed-joint properties and the complete tree. + comparable=copy.deepcopy(actual) + matrix=UsdGeom.Xformable(anchor).ComputeLocalToWorldTransform(Usd.TimeCode.Default()) + rotation=matrix.RemoveScaleShear().ExtractRotationQuat() + for key,fixed in comparable['fixed_joint_map'].items(): + previous=expected['fixed_joint_map'].get(key,{}) + if not previous:_fail('loaded two-DOF world anchor is not in the prepared graph') + source_position=Gf.Vec3d(*previous['local_pos0_m']) + source_q=previous['local_rot0_wxyz'];source_quat=Gf.Quatd(source_q[0],Gf.Vec3d(*source_q[1:])) + expected_position=matrix.Transform(source_position);expected_quat=rotation*source_quat + actual_position=fixed['local_pos0_m'];actual_quat=fixed['local_rot0_wxyz'] + wanted_q=[expected_quat.GetReal(),*expected_quat.GetImaginary()] + if (max(abs(actual_position[i]-expected_position[i]) for i in range(3))>1e-5 + or min(max(abs(actual_quat[i]-wanted_q[i]) for i in range(4)), + max(abs(actual_quat[i]+wanted_q[i]) for i in range(4)))>1e-5): + _fail('loaded two-DOF world anchor differs from its instance placement') + for field in ('local_pos0_m','local_rot0_wxyz'): + if field in previous:fixed[field]=previous[field] + attrs=fixed.get('native_authored_attributes',{});old=previous.get('native_authored_attributes',{}) + for field in ('physics:localPos0','physics:localRot0'): + if field in old:attrs[field]=old[field] + else:attrs.pop(field,None) + if comparable!=expected:_fail('loaded two-DOF articulation differs from its prepared graph') + base=str(anchor.GetPath()) + def path(relative):return base+('/'+relative if relative else '') + bodies={name:{'motion_body':path(entry['relative_prim_path']),'role':entry['role'], + 'visual_roots':[path(p) for p in entry['visual_relative_prim_paths']], + 'collider_paths':[path(p) for p in entry['collider_relative_prim_paths']]} + for name,entry in actual['body_map'].items()} + joints={name:dict(runtime_joint(entry),joint_path=path(entry['relative_prim_path']), + parent_body=bodies[entry['parent_body_id']]['motion_body'],child_body=bodies[entry['child_body_id']]['motion_body']) + for name,entry in actual['joint_map'].items()} + result={'profile_id':'articulated_prop_v2','bodies':bodies,'joints':joints, + 'root_body':bodies[actual['root_body_id']]['motion_body'], + 'motion_bodies':[entry['motion_body'] for entry in bodies.values()], + 'contact_bodies':[entry['motion_body'] for entry in bodies.values()], + 'visual_roots':list(dict.fromkeys(p for entry in bodies.values() for p in entry['visual_roots'])), + 'collider_paths':[p for entry in bodies.values() for p in entry['collider_paths']]+[path(p) for p in actual['static_collider_paths']], + 'articulation_roots':[path(p) for p in actual['articulation_root_paths']]} + from ..worker.mechanism import validate_binding + validate_binding(result) + return result diff --git a/src/simscene/preparation/contracts.py b/src/simscene/preparation/contracts.py index c5ddbd9..90ea643 100644 --- a/src/simscene/preparation/contracts.py +++ b/src/simscene/preparation/contracts.py @@ -95,11 +95,15 @@ def reference(pointer): 'runtime_dependency_count': dependency_count, 'runtime_dependency_evidence': 'inspected' if dependency_count is not None else 'unknown'} mass = parameters.get('mass_kg') if profile == 'rigid_prop_v1' else None - collision_applied = profile in {'rigid_prop_v1', 'static_fixture_v1', 'container_v1', 'articulated_prop_v1'} + native_repairs = parameters.get('native_physics_repairs') + if native_repairs is not None: + from .native_repairs import validate_repair_report + validate_repair_report(native_repairs, manifest.get('physics_repairs')) + collision_applied = profile in {'rigid_prop_v1', 'static_fixture_v1', 'container_v1', 'articulated_prop_v1', 'articulated_prop_v2'} collision_method = parameters.get('collision_method') approximate = collision_applied and collision_method in {'convex_hull', 'box_proxy'} physics_report = {'collision_method': collision_method, 'collision_applied': collision_applied, - 'mass_assumption_kg': mass, 'experimental_mass': mass is not None, + 'mass_assumption_kg': mass, 'experimental_mass': mass is not None or bool(native_repairs and native_repairs['missing_masses_kg']), 'experimental_material': profile == 'rigid_prop_v1' or (profile == 'static_fixture_v1' and collision_method == 'box_proxy'), 'collision_approximation': approximate, 'collision_report_ref': reference('/collision_report') if manifest.get('collision_report') is not None else None, @@ -114,6 +118,15 @@ def reference(pointer): warnings.append('runtime_mdl_dependency_requires_target_environment') if mass is not None: warnings.append('experimental_mass_assumption_not_manufacturer_data') + if native_repairs is not None: + physics_report['native_repairs_ref'] = reference('/physics_repairs') + if native_repairs['missing_masses_kg']: + warnings.append('experimental_native_link_masses') + if native_repairs['neutralize_drives']: + warnings.append('source_native_drive_neutralized') + if native_repairs['material_density_overrides']: + physics_report['source_material_densities_overridden'] = True + warnings.append('experimental_body_mass_overrides_source_material_density') if material_count is None: warnings.append('material_count_unknown') if runtime['status'] not in {'runtime_verified', 'verified', 'pass'}: @@ -132,7 +145,7 @@ def reference(pointer): 'bounds': deepcopy(manifest.get('bounds')), 'body_map': deepcopy(body_map), 'material_report': material_report, 'physics_report': physics_report, 'warnings': warnings, 'runtime_validation': runtime} - if profile=='articulated_prop_v1': + if profile in {'articulated_prop_v1','articulated_prop_v2'}: result['joint_map']=deepcopy(manifest.get('joint_map',{})) if profile=='container_v1': result['physics_report']['container_report_ref']=reference('/container_report') diff --git a/src/simscene/preparation/native_repairs.py b/src/simscene/preparation/native_repairs.py new file mode 100644 index 0000000..8755134 --- /dev/null +++ b/src/simscene/preparation/native_repairs.py @@ -0,0 +1,284 @@ +"""Explicit, bounded repairs to a derived USD layer; never edit the source.""" +import copy +import math +import re +import struct + +from .profiles import PreparationError + + +def _fail(message): + raise PreparationError('physics_profile_unsupported', message) + + +def _path(value): + if (not isinstance(value, str) or not 1 <= len(value) <= 256 or + value != '.' and not re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]*(?:/[A-Za-z_][A-Za-z0-9_]*)*', value)): + _fail('repair paths must be safe relative USD prim paths') + return value + + +def _positive(value, label): + if type(value) not in (int, float) or not math.isfinite(value) or not 0 < value <= 10000: + _fail(label + ' must be finite, positive and at most 10000') + return float(value) + + +def validate_native_repairs(value): + required={'missing_masses_kg', 'neutralize_drives', 'reason'} + if not isinstance(value, dict) or not required <= set(value) or set(value)-required-{'material_density_overrides'}: + _fail('native repairs require missing_masses_kg, neutralize_drives and reason') + reason = value['reason'] + if not isinstance(reason, str) or not reason.strip() or len(reason) > 1024: + _fail('native repairs require a bounded reason describing experimental assumptions') + masses, drives = value['missing_masses_kg'], value['neutralize_drives'] + if not isinstance(masses, dict) or not isinstance(drives, dict) or len(masses) > 16 or len(drives) > 16 or not (masses or drives): + _fail('native repairs require 1..16 bounded body or joint edits') + overrides=value.get('material_density_overrides',{}) + if not isinstance(overrides,dict) or len(overrides)>256: + _fail('material density overrides must be a bounded collider mapping') + normalized_overrides={} + for path,entry in overrides.items(): + if not isinstance(entry,dict) or set(entry)!={'material_path','density_kg_m3'}: + _fail('material density overrides require a material path and measured source density') + density=entry['density_kg_m3'] + if type(density) not in (int,float) or not math.isfinite(density) or not 0 0 else 'negative_infinity' if value < 0 else 'nan'} + if value is None or type(value) in (bool, int, float): + return value + return str(value) + + +def apply_native_repairs(stage, repairs): + """Apply only requested missing masses and neutral drives to a derived layer. + + Validate every proposed edit before writing anything. The caller must pass + a private derived stage, then run normal graph admission and hash both the + immutable source closure and the repaired output separately. + """ + from pxr import Usd, UsdPhysics, UsdShade + from .articulation import canonical_stage + repairs = validate_native_repairs(repairs) + canonical_stage(stage) + root = stage.GetDefaultPrim() + if not root: + _fail('native repairs require a default prim') + prims = list(Usd.PrimRange(root)) + if any(prim.IsInstance() or prim.IsInstanceable() for prim in prims): + _fail('native repairs do not support instanced prims') + root_path = str(root.GetPath()) + + def relative(prim): + path = str(prim.GetPath()) + return '.' if path == root_path else path[len(root_path) + 1:] + + bodies = {relative(prim): prim for prim in prims if prim.HasAPI(UsdPhysics.RigidBodyAPI)} + missing = set() + for name, prim in bodies.items(): + mass = UsdPhysics.MassAPI(prim) + attr = mass.GetMassAttr() if mass else None + if not attr or not attr.HasAuthoredValueOpinion(): + missing.add(name) + ancestor=prim.GetParent() + while ancestor and not ancestor.IsPseudoRoot(): + if (ancestor.HasAPI(UsdPhysics.MassAPI) + and UsdPhysics.MassAPI(ancestor).GetDensityAttr().HasAuthoredValueOpinion()): + _fail('cannot add body mass over inherited authored density') + ancestor=ancestor.GetParent() + # A parent mass takes precedence over explicit descendant mass or + # density in USD. Refuse to silently erase those authored inputs. + for descendant in Usd.PrimRange(prim): + owner=descendant + while owner and not owner.HasAPI(UsdPhysics.RigidBodyAPI): + owner=owner.GetParent() + if owner != prim or not descendant.HasAPI(UsdPhysics.MassAPI): + continue + child_mass=UsdPhysics.MassAPI(descendant) + if (child_mass.GetDensityAttr().HasAuthoredValueOpinion() or + descendant != prim and child_mass.GetMassAttr().HasAuthoredValueOpinion()): + _fail('cannot add missing body mass when descendant mass or density is explicitly authored') + else: + _positive(attr.Get(), 'authored source mass') + requested_masses = repairs['missing_masses_kg'] + if not bodies or set(requested_masses) != missing: + _fail('missing_masses_kg must name exactly every body without an authored mass; existing masses cannot be overwritten') + + # Even with no body mass, a bound physics material may supply a source + # density. A body mass takes precedence; require explicit per-collider + # acknowledgment of that behavioral change, including inherited bindings. + material_overrides={} + for name in sorted(missing): + body=bodies[name] + for prim in Usd.PrimRange(body): + if not prim.HasAPI(UsdPhysics.CollisionAPI):continue + owner=prim + while owner and not owner.HasAPI(UsdPhysics.RigidBodyAPI):owner=owner.GetParent() + if owner != body:continue + material,_=UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial('physics') + if not material or not material.GetPrim().HasAPI(UsdPhysics.MaterialAPI):continue + density=UsdPhysics.MaterialAPI(material.GetPrim()).GetDensityAttr() + if not density.HasAuthoredValueOpinion():continue + material_path=str(material.GetPath()) + if material_path != root_path and not material_path.startswith(root_path+'/'): + _fail('physics material density outside the selected source root is unsupported') + number=density.Get() + if type(number) not in (int,float) or not math.isfinite(number) or number<=0: + _fail('authored physics material density must be finite and positive') + material_overrides[relative(prim)]={'material_path':relative(material.GetPrim()),'density_kg_m3':float(number)} + if material_overrides != repairs['material_density_overrides']: + _fail('explicit material density overrides must exactly match source collider/material bindings') + + joints = {relative(prim): prim for prim in prims if prim.IsA(UsdPhysics.Joint)} + requested_drives = repairs['neutralize_drives'] + if not set(requested_drives) <= set(joints): + _fail('neutralize_drives must name existing native joints') + pending_drives = [] + for name, prim in joints.items(): + if prim.IsA(UsdPhysics.RevoluteJoint): + instance = 'angular' + elif prim.IsA(UsdPhysics.PrismaticJoint): + instance = 'linear' + else: + if name in requested_drives: + _fail('only native hinge or slider drives can be neutralized') + continue + schemas = [schema for schema in prim.GetAppliedSchemas() if schema.startswith('PhysicsDriveAPI:')] + if any(schema != 'PhysicsDriveAPI:' + instance for schema in schemas): + _fail('coupled or multiaxis source drives are unsupported') + if name in requested_drives and not schemas: + _fail('a neutralized drive must already exist in the source') + if not schemas: + continue + drive = UsdPhysics.DriveAPI(prim, instance) + get = lambda name: getattr(drive, 'Get' + name + 'Attr')().Get() + source = {'type': _record_value(get('Type')), 'stiffness': _record_value(get('Stiffness')), + 'damping': _record_value(get('Damping')), 'max_effort': _record_value(get('MaxForce')), + 'target_position': _record_value(get('TargetPosition')), 'target_velocity': _record_value(get('TargetVelocity')), + 'units': 'original USD drive schema units'} + fields = [get(field) for field in ('Stiffness', 'Damping', 'MaxForce', 'TargetPosition', 'TargetVelocity')] + supported = (get('Type') == 'force' and all(type(v) in (int, float) and math.isfinite(v) for v in fields) + and fields[0] >= 0 and fields[1] >= 0 and fields[2] > 0) + if name not in requested_drives: + if not supported: + _fail('unsupported source drive must be explicitly neutralized') + continue + if supported: + _fail('source drive is already supported; preserve it rather than neutralizing it') + pending_drives.append((name, prim, instance, source, requested_drives[name])) + + masses = [] + for name, value in requested_masses.items(): + UsdPhysics.MassAPI.Apply(bodies[name]).CreateMassAttr(value) + masses.append({'relative_prim_path': name, 'source_status': 'body_mass_not_authored', 'mass_kg': value, + 'provenance': 'explicit_experimental_assumption'}) + drives = [] + for name, prim, instance, source, maximum in pending_drives: + drive = UsdPhysics.DriveAPI.Apply(prim, instance) + drive.CreateTypeAttr('force') + drive.CreateStiffnessAttr(0.) + drive.CreateDampingAttr(0.) + drive.CreateMaxForceAttr(maximum) + drive.CreateTargetPositionAttr(0.) + drive.CreateTargetVelocityAttr(0.) + drives.append({'relative_prim_path': name, 'instance': instance, 'source': source, + 'derived': {'type': 'force', 'stiffness': 0., 'damping': 0., 'max_effort': maximum, + 'target_position': 0., 'target_velocity': 0.}, + 'provenance': 'explicit_neutral_drive_not_original_behavior'}) + return {'schema': 'simscene.native_physics_repairs.v1', 'reason': repairs['reason'], + 'masses': masses, 'drives': drives, + 'material_density_overrides':[{'collider_path':path,**item, + 'provenance':'authored_material_density_overridden_by_explicit_body_mass'} + for path,item in sorted(material_overrides.items())], + 'scope': 'Only the derived layer is edited; source values and original drive behavior are not asserted for the repair.'} diff --git a/src/simscene/preparation/profiles.py b/src/simscene/preparation/profiles.py index b738b55..0f4bfeb 100644 --- a/src/simscene/preparation/profiles.py +++ b/src/simscene/preparation/profiles.py @@ -5,7 +5,7 @@ import math PROFILE_VERSION = 1 -PROFILES = frozenset({'visual_prop_v1', 'static_fixture_v1', 'rigid_prop_v1', 'articulated_prop_v1', 'container_v1', 'environment_v1'}) +PROFILES = frozenset({'visual_prop_v1', 'static_fixture_v1', 'rigid_prop_v1', 'articulated_prop_v1', 'articulated_prop_v2', 'container_v1', 'environment_v1'}) class PreparationError(ValueError): def __init__(self, code, message): @@ -42,11 +42,17 @@ def validate_parameters(profile, parameters): p = copy.deepcopy(parameters) allowed = {'source_physics_policy','scale_mode','target_longest_extent_m','mass_kg','mass_note', 'collision_method','static_friction','dynamic_friction','restitution','ccd', - 'proxy_tolerance_m','support_surfaces','static_proxy','container_proxy'} + 'proxy_tolerance_m','support_surfaces','static_proxy','container_proxy','native_physics_repairs'} if set(p) - allowed: _fail(f'unknown parameters: {sorted(set(p)-allowed)}') - if p.get('source_physics_policy') not in {'preserve_valid','replace_visual_only','reject_if_physics'}: + if p.get('source_physics_policy') not in {'preserve_valid','replace_visual_only','reject_if_physics','repair_explicit'}: _fail('source_physics_policy is required') + if p['source_physics_policy']=='repair_explicit': + if profile!='articulated_prop_v1':_fail('explicit native repairs apply only to articulated_prop_v1') + from .native_repairs import validate_native_repairs + p['native_physics_repairs']=validate_native_repairs(p.get('native_physics_repairs')) + elif 'native_physics_repairs' in p: + _fail('native_physics_repairs require source_physics_policy=repair_explicit') p.setdefault('scale_mode', 'preserve') if p['scale_mode'] not in {'preserve','fit_longest'}: _fail('scale_mode must be preserve or fit_longest') @@ -68,14 +74,15 @@ def validate_parameters(profile, parameters): p.setdefault('collision_method', 'convex_hull' if profile == 'rigid_prop_v1' else 'preserve') if p['collision_method'] not in {'preserve','convex_hull','box_proxy'}: _fail('invalid collision_method') - if profile in {'articulated_prop_v1','container_v1'}: + if profile in {'articulated_prop_v1','articulated_prop_v2','container_v1'}: if p['scale_mode'] != 'preserve': _fail('M2 physical profiles cannot rescale native physics or declared metric container geometry') - if profile == 'articulated_prop_v1': + if profile in {'articulated_prop_v1','articulated_prop_v2'}: if 'container_proxy' in p: _fail('container_proxy applies only to container_v1') - if p['source_physics_policy'] != 'preserve_valid' or p['collision_method'] != 'preserve': - _fail('articulated profile requires preserve_valid native physics/collision') + policies={'preserve_valid','repair_explicit'} if profile=='articulated_prop_v1' else {'preserve_valid'} + if p['source_physics_policy'] not in policies or p['collision_method'] != 'preserve': + _fail('articulated profile requires preserved native collision with valid or explicitly repaired physics') else: if p['source_physics_policy'] != 'replace_visual_only' or p['collision_method'] != 'box_proxy': _fail('container profile requires explicit opening-preserving wall proxies and replace_visual_only') diff --git a/src/simscene/preparation/usd_layers.py b/src/simscene/preparation/usd_layers.py index 7472e86..3a52066 100644 --- a/src/simscene/preparation/usd_layers.py +++ b/src/simscene/preparation/usd_layers.py @@ -175,12 +175,26 @@ def prepare_acquired(acquired, profile, parameters, target, output_dir, *, app=N for path in original['colliders']: if not UsdPhysics.CollisionAPI(source_stage.GetPrimAtPath(path)).GetCollisionEnabledAttr().Get(): raise PreparationError('physics_profile_unsupported','disabled native collider cannot qualify as preserved support') - if profile=='articulated_prop_v1': + if profile in {'articulated_prop_v1','articulated_prop_v2'}: if is_glb: raise PreparationError('physics_profile_unsupported','articulated profile requires a native USD joint, not GLB extras') - from .articulation import inspect_articulation - inspect_articulation(source_stage) + from .articulation import canonical_stage,inspect_articulation + canonical_stage(source_stage) + if parameters['source_physics_policy']=='preserve_valid': + if profile=='articulated_prop_v1':inspect_articulation(source_stage) + else: + from .articulation_v2 import inspect_articulation_v2,runtime_joint + native_graph=inspect_articulation_v2(source_stage) + if native_graph['static_collider_paths']: + raise PreparationError('physics_profile_unsupported','two-DOF profile does not yet support static colliders outside its rigid links') + for entry in native_graph['joint_map'].values():runtime_joint(entry) visual,runtime=_localize_flattened(source_stage,derived/'visual.usda',output) + physics_repairs=None + if profile=='articulated_prop_v1' and parameters['source_physics_policy']=='repair_explicit': + from .native_repairs import apply_native_repairs + physics_repairs=apply_native_repairs(visual,parameters['native_physics_repairs']) + inspect_articulation(visual) + visual.GetRootLayer().Save() if profile=='visual_prop_v1' and physics and parameters['source_physics_policy']!='replace_visual_only': raise PreparationError('physics_profile_unsupported','visual profile must explicitly replace source physics') if parameters['source_physics_policy']=='replace_visual_only': @@ -192,21 +206,24 @@ def prepare_acquired(acquired, profile, parameters, target, output_dir, *, app=N joint_map={};articulation_report=None;container_report=None body_map={};visual_path='/Asset/Body/Visual' if profile=='rigid_prop_v1' else '/Asset/Visual' if profile=='rigid_prop_v1':UsdGeom.Xform.Define(stage,'/Asset/Body') - if profile=='articulated_prop_v1': + if profile in {'articulated_prop_v1','articulated_prop_v2'}: visual_path='/Asset/Native' visual_xf=UsdGeom.Xform.Define(stage,visual_path) if source_axis=='Y':visual_xf.AddRotateXOp(opSuffix='sourceYUpToZUp').Set(90) scale_op=None - if profile!='articulated_prop_v1': + if profile not in {'articulated_prop_v1','articulated_prop_v2'}: scale_op=visual_xf.AddScaleOp(opSuffix='canonicalUnitsAndSize');scale_op.Set(Gf.Vec3f(source_units)) - source_prim=visual_xf.GetPrim() if profile=='articulated_prop_v1' else UsdGeom.Xform.Define(stage,visual_path+'/Source').GetPrim() + source_prim=visual_xf.GetPrim() if profile in {'articulated_prop_v1','articulated_prop_v2'} else UsdGeom.Xform.Define(stage,visual_path+'/Source').GetPrim() source_prim.GetReferences().AddReference('./derived/visual.usda') before=inspect_stage(stage);factor=1.0 if parameters['scale_mode']=='fit_longest':factor=parameters['target_longest_extent_m']/max(before['bounds']['dimensions']) if scale_op is not None:scale_op.Set(Gf.Vec3f(source_units*factor)) measured=inspect_stage(stage);shape_report=None;support_report=None - if profile=='articulated_prop_v1': - articulation_report=inspect_articulation(stage) + if profile in {'articulated_prop_v1','articulated_prop_v2'}: + articulation_report=inspect_articulation(stage) if profile=='articulated_prop_v1' else inspect_articulation_v2(stage) + if physics_repairs is not None: + from .native_repairs import annotate_repaired_graph + articulation_report=annotate_repaired_graph(articulation_report,parameters['native_physics_repairs']) body_map=articulation_report['body_map'];joint_map=articulation_report['joint_map'] elif profile=='container_v1': from .container import check_geometry,author_walls @@ -244,6 +261,7 @@ def prepare_acquired(acquired, profile, parameters, target, output_dir, *, app=N report={'schema':'simscene.prepared_asset.v1','schema_version':1,'prepared_id':identity,'profile_id':profile,'profile_version':PROFILE_VERSION, 'root':str(output),'asset_path':str(output/'main.usda'),'main':'main.usda','default_prim':'/Asset','parameters':parameters,'target':target, 'source_ref':acquired.get('source_ref',acquired.get('asset_ref')),'source_sha256':source_hash,'source_closure_sha256':closure_hash, + 'source_root':root.relative_to(output).as_posix(), 'source_manifest_sha256':acquired.get('manifest_sha256',acquired.get('source_manifest_hash')),'license':acquired.get('license','unknown'), 'provenance':acquired.get('provenance'),'toolchain':selected,'body_map':body_map,'bounds':measured['bounds'], 'source_to_output':{'source_axis':source_axis,'rotation_x_degrees':90 if source_axis=='Y' else 0,'source_meters_per_unit':source_units, @@ -251,8 +269,11 @@ def prepare_acquired(acquired, profile, parameters, target, output_dir, *, app=N 'runtime_dependencies':runtime,'collision_report':shape_report,'support_report':support_report,'support_surfaces':parameters.get('support_surfaces',{}), 'physical_material_assumption':'experimental recipe values; not manufacturer facts','inertia':{'status':'runtime_check_required','method':'engine computes from collision geometry and explicit mass'}, 'runtime_verification':'unverified','runtime_validation':{'status':'not_run','physical_steps':0},'physical_steps':0,'conversion':conversion} - if profile=='articulated_prop_v1': - report.update(joint_map=joint_map,articulation_report=articulation_report,physical_material_assumption='preserved native source values; no material or mass rewrite',inertia={'status':'native_mass_preserved_inertia_authored_or_engine_computed_runtime_check_required'}) + if profile in {'articulated_prop_v1','articulated_prop_v2'}: + report.update(joint_map=joint_map,articulation_report=articulation_report, + physical_material_assumption=('native materials preserved; explicitly listed experimental masses and neutral drives authored in derived layer' if physics_repairs else 'preserved native source values; no material or mass rewrite'), + inertia={'status':('explicit_experimental_mass_inertia_runtime_check_required' if physics_repairs else 'native_mass_preserved_inertia_authored_or_engine_computed_runtime_check_required')}) + if physics_repairs is not None:report['physics_repairs']=physics_repairs elif profile=='container_v1': report.update(container_report=container_report) report['files']=[{'path':f.relative_to(output).as_posix(),'size_bytes':f.stat().st_size,'sha256':_sha(f)} for f in sorted(output.rglob('*')) if f.is_file()] diff --git a/src/simscene/recipes/io.py b/src/simscene/recipes/io.py index a0854fe..a62f24e 100644 --- a/src/simscene/recipes/io.py +++ b/src/simscene/recipes/io.py @@ -40,17 +40,26 @@ def _files(files): def _generation_intent(identity,provenance): if not isinstance(identity,dict) or type(identity.get('seed')) is not int or identity['seed']!=0: raise ValueError('unsupported generated source: explicit trusted recipe and seed 0 required') - from ..generation.sand3d import parameters,COMMIT if not re.fullmatch('[0-9a-f]{64}',str(identity.get('template_sha256',''))):raise ValueError('trusted template content pin required') + generator=provenance.get('generator') + if generator=='sand3d': + from ..generation.sand3d import parameters,COMMIT + elif generator=='usdcraft_sdk': + from ..generation.usdcraft_sdk import parameters,COMMIT,validate_runtime + if identity.get('generation_contract_version')!=3:raise ValueError('unsupported generated source contract') + validate_runtime(identity.get('toolchain')) + else:raise ValueError('unsupported generated source runtime') recipe=identity.get('recipe_id');p=parameters(recipe,identity.get('parameters')) runtime=identity.get('toolchain') or {} - if provenance.get('generator')!='sand3d' or provenance.get('reviewed_commit')!=COMMIT or runtime.get('reviewed_commit')!=COMMIT: + if provenance.get('reviewed_commit')!=COMMIT or runtime.get('reviewed_commit')!=COMMIT: raise ValueError('unsupported generated source runtime') # Python executable locations are runtime configuration, not portable intent. observed=runtime.get('observed',{}) - return portable({'generator':'sand3d','recipe_id':recipe,'parameters':p,'seed':0, + result={'generator':generator,'recipe_id':recipe,'parameters':p,'seed':0, 'reviewed_commit':COMMIT,'template_sha256':identity.get('template_sha256'), - 'toolchain_intent':{key:value for key,value in observed.items() if key not in ('python','executable','python_executable','path')}}) + 'toolchain_intent':{key:value for key,value in observed.items() if key not in ('python','executable','python_executable','path','repository_path')}} + if generator=='usdcraft_sdk':result['generation_contract_version']=3 + return portable(result) def prepared_selection(manifest,acquired,*,manifest_sha256): @@ -65,9 +74,11 @@ def prepared_selection(manifest,acquired,*,manifest_sha256): 'previous_preparation':{'prepared_id':manifest['prepared_id'],'manifest_sha256':manifest_sha256, 'source_manifest_sha256':manifest.get('source_manifest_sha256'),'scope':'informational; rebuild may change absolute provenance; no physics verdict reused'}} if acquired.get('source_ref')!=manifest['source_ref']:raise ValueError('source attribution differs from prepared manifest') - if ref.source_id=='local-sand3d': + if ref.source_id in ('local-sand3d','local-usdcraft-sdk'): provenance=manifest.get('provenance') or {} result['generation']=_generation_intent(provenance.get('identity'),provenance) + if (ref.source_id,result['generation']['generator']) not in (('local-sand3d','sand3d'),('local-usdcraft-sdk','usdcraft_sdk')): + raise ValueError('generated source reference differs from its backend') if ref.asset_id!=result['generation']['recipe_id']:raise ValueError('generated source reference differs from trusted recipe') else: metadata=acquired.get('metadata') @@ -89,7 +100,8 @@ def validate_rebuilt(selection,binding): if manifest.get('source_ref')!=selection['source_ref']:raise ValueError('rebuilt source reference differs') else: actual_ref=AssetRef.from_dict(manifest.get('source_ref')) - if actual_ref.source_id!='local-sand3d' or actual_ref.asset_id!=selection['generation']['recipe_id']: + expected_source={'sand3d':'local-sand3d','usdcraft_sdk':'local-usdcraft-sdk'}.get(selection['generation'].get('generator')) + if not expected_source or actual_ref.source_id!=expected_source or actual_ref.asset_id!=selection['generation']['recipe_id']: raise ValueError('rebuilt generated source attribution differs') provenance=manifest.get('provenance') or {} if _generation_intent(provenance.get('identity'),provenance)!=selection['generation']: diff --git a/src/simscene/scene.py b/src/simscene/scene.py index 5d86967..b440e9f 100644 --- a/src/simscene/scene.py +++ b/src/simscene/scene.py @@ -59,13 +59,13 @@ def validate(scene): prepared_manifest = validate_asset_binding(obj['asset_binding'], require_dynamic=obj.get('dynamic') is True, asset_path=obj.get('asset_path')) profile = prepared_manifest.get('profile_id') - if profile not in ('rigid_prop_v1', 'static_fixture_v1', 'visual_prop_v1', 'articulated_prop_v1', 'container_v1', 'environment_v1'): + if profile not in ('rigid_prop_v1', 'static_fixture_v1', 'visual_prop_v1', 'articulated_prop_v1', 'articulated_prop_v2', 'container_v1', 'environment_v1'): raise ValueError('unsupported prepared asset profile') - if profile in ('rigid_prop_v1','articulated_prop_v1') and obj.get('dynamic') is not True: + if profile in ('rigid_prop_v1','articulated_prop_v1','articulated_prop_v2') and obj.get('dynamic') is not True: raise ValueError(f'prepared {profile} requires dynamic=true') - if profile not in ('rigid_prop_v1','articulated_prop_v1') and obj.get('dynamic', False) is not False: + if profile not in ('rigid_prop_v1','articulated_prop_v1','articulated_prop_v2') and obj.get('dynamic', False) is not False: raise ValueError('prepared static/visual profiles require dynamic=false') - if profile=='articulated_prop_v1' and (not observation.get('strict_start') or observation.get('sample_interval_steps')!=1): + if profile in ('articulated_prop_v1','articulated_prop_v2') and (not observation.get('strict_start') or observation.get('sample_interval_steps')!=1): raise ValueError('prepared articulated assets require strict_start and every-physics-step observation') colliders = any(entry.get('collider_relative_prim_paths') for entry in prepared_manifest.get('body_map', {}).values()) if 'collision' in obj and obj['collision'] is not bool(colliders): @@ -84,13 +84,23 @@ def validate(scene): prepared_manifest = None if 'mechanism' in obj: try: - if prepared_manifest is None or prepared_manifest.get('profile_id')!='articulated_prop_v1': - raise ValueError('mechanism requires a prepared articulated_prop_v1 asset binding') + if prepared_manifest is None or prepared_manifest.get('profile_id') not in ('articulated_prop_v1','articulated_prop_v2'): + raise ValueError('mechanism requires a prepared articulated asset binding') from .worker.mechanism import validate_config - joints={} + joints={};profile=prepared_manifest['profile_id'];bodies=prepared_manifest['body_map'] for local_id,entry in prepared_manifest['joint_map'].items(): - joints[local_id]=dict(entry,joint_path='/World/validation/Joint',parent_body='/World/validation/Parent' if entry.get('parent_body_id') else None,child_body='/World/validation/Child') - validate_config({'joints':joints},obj['mechanism']) + if profile=='articulated_prop_v2': + from .preparation.articulation_v2 import runtime_joint + entry=runtime_joint(entry) + parent=entry.get('parent_body_id');child=entry['child_body_id'] + joints[local_id]=dict(entry,joint_path='/World/validation/'+entry['relative_prim_path'], + parent_body='/World/validation/'+bodies[parent]['relative_prim_path'] if parent else None, + child_body='/World/validation/'+bodies[child]['relative_prim_path']) + binding={'joints':joints} + if profile=='articulated_prop_v2': + binding.update(profile_id=profile,motion_bodies=['/World/validation/'+b['relative_prim_path'] for b in bodies.values()], + root_body='/World/validation/'+bodies[prepared_manifest['articulation_report']['root_body_id']]['relative_prim_path']) + validate_config(binding,obj['mechanism']) if not observation.get('strict_start') or observation.get('sample_interval_steps')!=1: raise ValueError('mechanism requires strict_start and every-physics-step observation') except (ValueError,TypeError,KeyError) as error: diff --git a/src/simscene/usd_export.py b/src/simscene/usd_export.py index fdc67dc..e574df0 100644 --- a/src/simscene/usd_export.py +++ b/src/simscene/usd_export.py @@ -43,14 +43,14 @@ def export_scene(scene, destination): prims = list(asset_stage.Traverse()) from .preparation.inspect import reject_executable_graphs reject_executable_graphs(asset_stage) - if prepared['profile_id'] not in ('rigid_prop_v1','articulated_prop_v1') and any(prim.HasAPI(UsdPhysics.RigidBodyAPI) or prim.HasAPI(UsdPhysics.ArticulationRootAPI) or prim.IsA(UsdPhysics.Joint) for prim in prims): + if prepared['profile_id'] not in ('rigid_prop_v1','articulated_prop_v1','articulated_prop_v2') and any(prim.HasAPI(UsdPhysics.RigidBodyAPI) or prim.HasAPI(UsdPhysics.ArticulationRootAPI) or prim.IsA(UsdPhysics.Joint) for prim in prims): raise ValueError('prepared static/visual profile contains dynamic or articulated physics') expected = {prepared['default_prim'] + ('/' + relative if relative not in ('', '.') else '') for entry in prepared['body_map'].values() for relative in entry.get('collider_relative_prim_paths', [])} actual = {str(prim.GetPath()) for prim in prims if prim.HasAPI(UsdPhysics.CollisionAPI) and UsdPhysics.CollisionAPI(prim).GetCollisionEnabledAttr().Get()} if actual != expected: raise ValueError('prepared collider paths do not match the actual source profile') - if prepared['profile_id'] in ('rigid_prop_v1', 'static_fixture_v1', 'container_v1', 'articulated_prop_v1') and any(attr.GetNumTimeSamples() for prim in prims for attr in prim.GetAttributes()): + if prepared['profile_id'] in ('rigid_prop_v1', 'static_fixture_v1', 'container_v1', 'articulated_prop_v1','articulated_prop_v2') and any(attr.GetNumTimeSamples() for prim in prims for attr in prim.GetAttributes()): raise ValueError('prepared physical assets cannot contain time-sampled animation') prepared_manifests[name] = prepared except (OSError, ValueError, TypeError, KeyError, AttributeError) as error: @@ -277,7 +277,7 @@ def export_scene(scene, destination): from pxr import Sdf physics.GetPrim().CreateAttribute('physxScene:enableCCD',Sdf.ValueTypeNames.Bool,custom=False).Set(True) for name,prepared in prepared_manifests.items(): - if prepared['profile_id']=='articulated_prop_v1': + if prepared['profile_id'] in ('articulated_prop_v1','articulated_prop_v2'): from .preparation.articulation import transform_world_anchors transform_world_anchors(stage,stage.GetPrimAtPath('/World/'+name.replace('-','_')+'/Asset')) from .physics_binding import resolve_body_bindings diff --git a/src/simscene/verification/articulated_asset_two_joint.py b/src/simscene/verification/articulated_asset_two_joint.py new file mode 100644 index 0000000..97ea943 --- /dev/null +++ b/src/simscene/verification/articulated_asset_two_joint.py @@ -0,0 +1,513 @@ +"""Offline acceptance of one pinned two-DOF native tree, never command echoes. + +The two driven coordinates are compared to both path-keyed PhysX tensor q/v +and same-sample body frames. Link linear velocities are at each link's center +of mass; the recorded cooked COM is needed to reconstruct anchor velocities. +""" +import json +import math +from pathlib import Path +import re + +SCHEMA = 'simscene.articulated_asset_two_joint.v1' +_NATIVE = 'PhysX_articulation_tensor_DOF_readback_SI' +_RECONSTRUCTED = 'same_sample_PhysX_body_poses_joint_frame_reconstruction' +_JOINT_FIELDS = {'joint_path', 'parent_body', 'child_body', 'type', 'axis', 'limits', 'position_unit', + 'initial_position', 'initial_tolerance', 'coordinate_tolerance', 'velocity_tolerance', + 'anchor_tolerance_m', 'angular_tolerance_rad'} +_PHASE_FIELDS = {'joint_id', 'command_step', 'by_step', 'target_position', 'target_tolerance', 'min_travel', + 'other_target_position', 'other_target_tolerance', 'max_other_drift', + 'stiffness', 'damping', 'max_effort', 'hold_command'} +_BINDING_FIELDS = ('joint_path', 'parent_body', 'child_body', 'type', 'axis', 'limits', 'position_unit') + + +def _number(value): + return type(value) in (int, float) and math.isfinite(value) + + +def _strictly_below(value, upper): + return value < upper and not math.isclose(value, upper, rel_tol=1e-12, abs_tol=0.) + + +def validate_case(case): + """Validate a single object, exactly two joint identities and disjoint stages.""" + from ..catalog.models import AssetRef + from ..scene import _id + from ..worker.mechanism import _path + required = {'schema', 'schema_version', 'mode', 'physics_dt_s', 'objects'} + if (not isinstance(case, dict) or not required <= set(case) or set(case) - required - {'physics_device'} + or case['schema'] != SCHEMA or type(case['schema_version']) is not int or case['schema_version'] != 1 + or case['mode'] != 'driven' or not _number(case['physics_dt_s']) or case['physics_dt_s'] <= 0 + or 'physics_device' in case and case['physics_device'] not in ('default', 'cpu', 'gpu')): + raise ValueError('invalid versioned two-joint acceptance case') + objects = case['objects'] + if not isinstance(objects, dict) or len(objects) != 1: + raise ValueError('two-joint acceptance requires one selected object') + name, obj = next(iter(objects.items())) + _id(name) + if (not isinstance(obj, dict) or set(obj) != {'prepared_manifest_sha256', 'source_ref', 'joints', 'phases'} + or not isinstance(obj['prepared_manifest_sha256'], str) + or not re.fullmatch('[0-9a-f]{64}', obj['prepared_manifest_sha256'])): + raise ValueError('selected object requires a pinned prepared manifest') + AssetRef.from_dict(obj['source_ref']).validate_selection() + joints = obj['joints'] + if not isinstance(joints, dict) or len(joints) != 2: + raise ValueError('two distinct frozen joint identities are required') + paths = set() + asset_prefix = '/World/' + name.replace('-', '_') + '/Asset/' + for joint_id, joint in joints.items(): + _id(joint_id) + if not isinstance(joint, dict) or set(joint) != _JOINT_FIELDS: + raise ValueError('invalid frozen joint case fields') + if not all(_path(joint[key]) and joint[key].startswith(asset_prefix) + for key in ('joint_path', 'parent_body', 'child_body')): + raise ValueError('explicit absolute joint and link paths are required') + if joint['parent_body'] == joint['child_body'] or joint['joint_path'] in paths: + raise ValueError('joint paths and endpoints must be distinct') + paths.add(joint['joint_path']) + unit = {'revolute': 'rad', 'prismatic': 'm'}.get(joint['type']) + limits = joint['limits'] + if (unit is None or joint['position_unit'] != unit or joint['axis'] not in ('X', 'Y', 'Z') + or not isinstance(limits, list) or len(limits) != 2 or not all(_number(x) for x in limits) + or limits[0] >= limits[1] or not math.isfinite(limits[1] - limits[0]) + or unit == 'rad' and limits[1] - limits[0] >= 2 * math.pi): + raise ValueError('invalid scalar joint type, units, axis or limits') + for key in ('initial_position', 'initial_tolerance', 'coordinate_tolerance', 'velocity_tolerance', + 'anchor_tolerance_m', 'angular_tolerance_rad'): + if not _number(joint[key]) or key != 'initial_position' and joint[key] <= 0: + raise ValueError('invalid initial coordinate or tolerance') + span = limits[1] - limits[0] + speed_cap = .05 if unit == 'm' else .1 + if (joint['anchor_tolerance_m'] > .005 or joint['angular_tolerance_rad'] > .05 + or joint['velocity_tolerance'] > speed_cap + or not _strictly_below(joint['coordinate_tolerance'] / span, .01) + or not _strictly_below(joint['initial_tolerance'] / span, .01) + or not _strictly_below(joint['velocity_tolerance'] / span * case['physics_dt_s'], .01)): + raise ValueError('joint measurement tolerances exceed their physical-scale bounds') + if not limits[0] <= joint['initial_position'] <= limits[1]: + raise ValueError('initial coordinate outside frozen limits') + phases = obj['phases'] + if not isinstance(phases, list) or not 2 <= len(phases) <= 128: + raise ValueError('two or more bounded independent drive phases are required') + last_end = -1 + driven = set() + for phase in phases: + if (not isinstance(phase, dict) or set(phase) != _PHASE_FIELDS + or not isinstance(phase['joint_id'], str) or phase['joint_id'] not in joints): + raise ValueError('invalid two-joint drive phase') + start, end = phase['command_step'], phase['by_step'] + if type(start) is not int or type(end) is not int or start < 0 or end <= start or start < last_end: + raise ValueError('drive phases must be ordered and not overlap') + last_end = end + joint = joints[phase['joint_id']] + other_id = next(key for key in joints if key != phase['joint_id']) + other = joints[other_id] + for key in _PHASE_FIELDS - {'joint_id', 'command_step', 'by_step', 'hold_command'}: + if not _number(phase[key]): + raise ValueError('phase parameters must be finite') + for key in ('target_tolerance', 'min_travel', 'other_target_tolerance', 'stiffness', 'max_effort'): + if phase[key] <= 0: + raise ValueError('phase targets, motion and drive tolerances must be positive') + if phase['damping'] < 0 or phase['max_other_drift'] < 0: + raise ValueError('negative damping or drift is unsupported') + hold = phase['hold_command'] + if hold is not None and (not isinstance(hold, dict) or set(hold) != {'stiffness', 'damping', 'max_effort'} + or any(not _number(hold[key]) for key in hold) or hold['stiffness'] <= 0 + or hold['damping'] < 0 or hold['max_effort'] <= 0): + raise ValueError('invalid explicit other-joint holding drive') + if (not joint['limits'][0] <= phase['target_position'] <= joint['limits'][1] + or not other['limits'][0] <= phase['other_target_position'] <= other['limits'][1] + or phase['min_travel'] > joint['limits'][1] - joint['limits'][0]): + raise ValueError('phase target or travel outside joint limits') + # Compare held and moving tolerances as fractions of their respective + # joint spans, so a slider and hinge remain dimensionally comparable. + moving_span = joint['limits'][1] - joint['limits'][0] + other_span = other['limits'][1] - other['limits'][0] + relative_budget = .2 * phase['min_travel'] / moving_span + if (not _strictly_below(phase['target_tolerance'] / moving_span, relative_budget) + or not _strictly_below(phase['other_target_tolerance'] / other_span, relative_budget) + or not _strictly_below(phase['max_other_drift'] / other_span, relative_budget)): + raise ValueError('phase tolerances are too large relative to required travel') + motion = phase['min_travel'] + if (not _strictly_below(joint['coordinate_tolerance'] / motion, .1) + or not _strictly_below(joint['initial_tolerance'] / motion, .1) + or joint['type'] == 'prismatic' and not _strictly_below(joint['anchor_tolerance_m'] / motion, .1) + or joint['type'] == 'revolute' and not _strictly_below(joint['angular_tolerance_rad'] / motion, .1)): + raise ValueError('joint measurement tolerances are too large relative to required travel') + driven.add(phase['joint_id']) + if driven != set(joints): + raise ValueError('both independent coordinates must be driven in separate phases') + return case + + +def _sub(a, b): + return [x - y for x, y in zip(a, b)] + + +def _cross(a, b): + return [a[1]*b[2] - a[2]*b[1], a[2]*b[0] - a[0]*b[2], a[0]*b[1] - a[1]*b[0]] + + +def _instantaneous_velocity(joint, frame, coms): + """Reconstruct SI DOF speed from link poses and COM-relative tensor speeds.""" + from ..worker.mechanism import _mul, _quaternion, _rotate, _vector + anchors = [] + rotations = [] + angular = [] + velocities = [] + for suffix, body in (('0', joint['parent_body']), ('1', joint['child_body'])): + position = _vector(frame.get('positions', {}).get(body), 3, 'actual link position') + q = _quaternion(frame.get('orientations_wxyz', {}).get(body)) + linear = _vector(frame.get('linear_velocities_m_s', {}).get(body), 3, 'link COM linear velocity') + omega = _vector(frame.get('angular_velocities_rad_s', {}).get(body), 3, 'link angular velocity') + local_anchor = _vector(joint['local_pos' + suffix + '_m'], 3, 'joint anchor') + com = _vector(coms[body], 3, 'cooked link center of mass') + lever = _rotate(q, _sub(local_anchor, com)) + anchor = _rotate(q, local_anchor) + anchors.append([x + y for x, y in zip(position, anchor)]) + velocities.append([x + y for x, y in zip(linear, _cross(omega, lever))]) + angular.append(omega) + rotations.append(_mul(q, joint['local_rot' + suffix + '_wxyz'])) + axis = [0., 0., 0.] + axis[('X', 'Y', 'Z').index(joint['axis'])] = 1. + world_axis = _rotate(rotations[0], axis) + if joint['type'] == 'revolute': + difference = _sub(angular[1], angular[0]) + else: + # A moving parent joint frame rotates the translation basis as well. + difference = _sub(_sub(velocities[1], velocities[0]), + _cross(angular[0], _sub(anchors[1], anchors[0]))) + return sum(a * b for a, b in zip(world_axis, difference)) + + +def _commands(joints, phases): + commands = [] + for phase in phases: + joint_id = phase['joint_id'] + commands.append({'joint_id': joint_id, 'trigger': {'type': 'at_step', 'physics_step': phase['command_step']}, + 'target_position': phase['target_position'], 'position_unit': joints[joint_id]['position_unit'], + **{key: phase[key] for key in ('stiffness', 'damping', 'max_effort')}}) + if phase['hold_command'] is not None: + other = next(key for key in joints if key != phase['joint_id']) + commands.append({'joint_id': other, 'trigger': {'type': 'at_step', 'physics_step': phase['command_step']}, + 'target_position': phase['other_target_position'], 'position_unit': joints[other]['position_unit'], + **phase['hold_command']}) + return commands + + +def _check_events(frames, name, joints, phases): + from ..worker.mechanism import usd_drive_values + final = frames[-1]['mechanisms'][name]['command_events'] + commands = _commands(joints, phases) + if not isinstance(final, list) or len(final) != len(commands): + return False + for index, (event, command) in enumerate(zip(final, commands)): + if not isinstance(event, dict): + return False + joint_id = command['joint_id'] + step = command['trigger']['physics_step'] + target = command['target_position'] + joint = joints[joint_id] + if (type(event.get('command_index')) is not int or event['command_index'] != index or event.get('joint_id') != joint_id + or event.get('joint_path') != joint['joint_path'] or type(event.get('physics_step')) is not int + or event['physics_step'] != step or not isinstance(event.get('trigger'), dict) + or type(event['trigger'].get('physics_step')) is not int + or event.get('trigger') != {'type': 'at_step', 'physics_step': step} + or event.get('position_unit') != joint['position_unit'] + or event.get('cause') != 'declared_at_step_schedule' + or not _number(event.get('target_position')) + or abs(event['target_position'] - target) > 1e-12): + return False + expected = usd_drive_values(joint, command) + actual = event.get('drive_readback') + if not isinstance(actual, dict) or actual.get('scope') != 'loaded_USD_drive_attributes': + return False + for key, value in expected.items(): + observed = actual.get(key) + if isinstance(value, str): + if observed != value: + return False + elif not _number(observed) or abs(observed - value) > max(1e-6, abs(value) * 1e-5): + return False + for frame in frames: + step = frame['physics_steps'] + # Step zero is commanded during initialization. Later commands are + # applied after observing their named step and before the next step. + count = sum(command['trigger']['physics_step'] == 0 or command['trigger']['physics_step'] < step + for command in commands) + if frame['mechanisms'][name].get('command_events') != final[:count]: + return False + return True + + +def evaluate(run, case): + """Evaluate recorded frames; malformed or incomplete evidence fails closed.""" + validate_case(case) + try: + return _evaluate(run, case) + except (KeyError, TypeError, ValueError, AttributeError, IndexError) as error: + return {'schema_version': 1, 'passed': False, 'checks': {'valid_measurements': False}, + 'objects': {}, 'errors': [str(error)]} + + +def _evaluate(run, case): + from ..worker.mechanism import measure_joint + from ..worker.mechanism_v2 import TwoDofTensorState + if not isinstance(run, dict): + raise ValueError('run must be an object') + name, obj = next(iter(case['objects'].items())) + dt = case['physics_dt_s'] + steps = run.get('actual_physics_steps') + frames = [run.get('initial_observation')] + run.get('samples', []) + zero = run.get('run_zero_absolute_physics_step') + absolute_time = run.get('run_zero_absolute_simulation_time_s') + checks = { + 'full_physics_steps': type(steps) is int and steps > 0 and type(run.get('requested_physics_steps')) is int + and steps == run['requested_physics_steps'], + 'not_partial': run.get('partial') is False and run.get('evidence_incomplete', False) is False, + 'samples_not_truncated': run.get('samples_truncated') is False, + 'task_not_failed': run.get('task_status') in ('unverified', 'completed'), + 'no_followers': isinstance(run.get('followers'), dict) and not run['followers'], + 'complete_per_step_timeline': False, + 'observed_physics_timestep': False, + 'observed_device_configuration': False, + } + checks['complete_per_step_timeline'] = (checks['full_physics_steps'] and run.get('observation_interval_steps') == 1 + and type(zero) is int and zero >= 0 and _number(absolute_time) and len(frames) == steps + 1 + and all(isinstance(frame, dict) and type(frame.get('physics_steps')) is int and frame['physics_steps'] == i + and type(frame.get('absolute_physics_step')) is int and frame['absolute_physics_step'] == zero + i + and _number(frame.get('simulation_time_s')) + and abs(frame['simulation_time_s'] - i * dt) <= 1e-6 and _number(frame.get('absolute_simulation_time_s')) + and abs(frame['absolute_simulation_time_s'] - absolute_time - i * dt) <= 1e-5 + for i, frame in enumerate(frames)) and _number(run.get('simulation_time_s')) + and abs(run['simulation_time_s'] - steps * dt) <= 1e-6) + settings = run.get('physics_settings', {}) + checks['observed_physics_timestep'] = all( + isinstance(settings.get(key), dict) and _number(settings[key].get('authored_time_steps_per_second')) + and abs(settings[key]['authored_time_steps_per_second'] * dt - 1.) <= 1e-5 + for key in ('before_warmup', 'after_run')) if isinstance(settings, dict) else False + if isinstance(settings, dict): + devices = [] + valid_device = True + for key in ('before_warmup', 'after_run'): + info = settings.get(key) + if not isinstance(info, dict): + valid_device = False + break + requested = info.get('requested_device') + devices.append(requested) + if requested not in ('default', 'cpu', 'gpu') or ('physics_device' in case and requested != case['physics_device']): + valid_device = False + elif requested == 'default': + valid_device &= info.get('request_matches_observation') is None + else: + valid_device &= (info.get('request_matches_observation') is True + and info.get('enable_gpu_dynamics') is (requested == 'gpu')) + checks['observed_device_configuration'] = bool(valid_device and len(devices) == 2 and devices[0] == devices[1]) + if not checks['complete_per_step_timeline']: + return {'schema_version': 1, 'passed': False, 'checks': checks, 'objects': {}} + binding = run.get('body_bindings', {}).get(name) + TwoDofTensorState._validate_binding(binding) + if binding.get('profile_id') != 'articulated_prop_v2' or set(binding['joints']) != set(obj['joints']): + raise ValueError('binding is not the selected two-joint profile') + joints = binding['joints'] + if any(any(joints[joint_id].get(key) != expected[key] for key in _BINDING_FIELDS) + for joint_id, expected in obj['joints'].items()): + raise ValueError('runtime joint binding differs from the frozen case') + mass = run.get('mechanism_configuration', {}).get('mass_properties_by_prim_path', {}) + coms = {} + for body in binding['motion_bodies']: + data = mass.get(body) + if (not isinstance(data, dict) or type(data.get('observed_at_physics_step')) is not int + or data['observed_at_physics_step'] != 0 + or not isinstance(data.get('source'), str) or 'PhysX' not in data['source']): + raise ValueError('native cooked link center of mass is missing') + values = data.get('center_of_mass_local_m') + if not isinstance(values, (list, tuple)) or len(values) != 3 or not all(_number(v) for v in values): + raise ValueError('native cooked link center of mass is invalid') + coms[body] = values + actual = {key: [] for key in joints} + previous = {} + joint_reports = {key: {'max_anchor_error_m': 0., 'max_locked_rotation_error_rad': 0., 'max_native_position_error': 0., + 'max_native_velocity_error': 0.} for key in joints} + for frame in frames: + step = frame['physics_steps'] + mechanism = frame['mechanisms'][name] + if type(mechanism.get('physics_step')) is not int or mechanism['physics_step'] != step or set(mechanism['joints']) != set(joints): + raise ValueError('frame joint observations differ from the frozen binding') + if frame.get('native_joint_measurement_source') != _NATIVE: + raise ValueError('native tensor measurement source is missing') + for key, joint in joints.items(): + expected = obj['joints'][key] + path = joint['joint_path'] + native_position = frame['native_joint_positions'][path] + native_velocity = frame['native_joint_velocities'][path] + record = mechanism['joints'][key] + measured = measure_joint(joint, frame, previous.get(key), physics_step=step, physics_dt_s=dt, + require_unique_initial=True) + if (not _number(native_position) or not _number(native_velocity) or not isinstance(record, dict) + or record.get('joint_path') != path or record.get('parent_body') != joint['parent_body'] + or record.get('child_body') != joint['child_body'] or type(record.get('physics_step')) is not int + or record['physics_step'] != step + or record.get('position_unit') != joint['position_unit'] + or record.get('velocity_unit') != joint['position_unit'] + '/s' + or record.get('measurement_source') != _RECONSTRUCTED + or record.get('native_measurement_source') != _NATIVE + or not _number(record.get('position')) or abs(record['position'] - measured['position']) > 1e-6 + or not _number(record.get('native_position')) or abs(record['native_position'] - native_position) > 1e-9 + or not _number(record.get('native_velocity')) or abs(record['native_velocity'] - native_velocity) > 1e-9 + or not _number(record.get('anchor_error_m')) or abs(record['anchor_error_m'] - measured['anchor_error_m']) > 1e-6 + or not _number(record.get('locked_rotation_error_rad')) + or abs(record['locked_rotation_error_rad'] - measured['locked_rotation_error_rad']) > 1e-6): + raise ValueError('native DOF or reconstructed joint observation differs from its same-step paths') + if step == 0: + if record.get('velocity') is not None: + raise ValueError('initial finite-difference velocity must be unknown') + elif not _number(record.get('velocity')) or abs(record['velocity'] - measured['velocity']) > 1e-5: + raise ValueError('recorded finite-difference velocity differs from body frames') + instant = _instantaneous_velocity(joint, frame, coms) + q_error = abs(native_position - measured['position']) + v_error = abs(native_velocity - instant) + if (q_error > expected['coordinate_tolerance'] or v_error > expected['velocity_tolerance'] + or measured['anchor_error_m'] > expected['anchor_tolerance_m'] + or measured['locked_rotation_error_rad'] > expected['angular_tolerance_rad'] + or not expected['limits'][0] - expected['coordinate_tolerance'] <= native_position + <= expected['limits'][1] + expected['coordinate_tolerance']): + raise ValueError('native q/v, frame reconstruction, limits or anchor check failed') + previous[key] = measured + actual[key].append(native_position) + report = joint_reports[key] + report['max_anchor_error_m'] = max(report['max_anchor_error_m'], measured['anchor_error_m']) + report['max_locked_rotation_error_rad'] = max(report['max_locked_rotation_error_rad'], measured['locked_rotation_error_rad']) + report['max_native_position_error'] = max(report['max_native_position_error'], q_error) + report['max_native_velocity_error'] = max(report['max_native_velocity_error'], v_error) + phase_reports = [] + for phase in obj['phases']: + start, end = phase['command_step'], phase['by_step'] + if end >= len(frames): + raise ValueError('phase ends outside recorded physics timeline') + key = phase['joint_id'] + other = next(item for item in joints if item != key) + values = actual[key][start:end+1] + held = actual[other][start:end+1] + travel = max(values) - min(values) + displacement = abs(values[-1] - values[0]) + drift = max(abs(value - held[0]) for value in held) + phase_checks = { + 'target_reached': abs(values[-1] - phase['target_position']) <= phase['target_tolerance'], + 'measured_travel': travel >= phase['min_travel'] and displacement >= phase['min_travel'], + 'other_target_held': all(abs(value - phase['other_target_position']) <= phase['other_target_tolerance'] for value in held), + 'other_drift_within_limit': drift <= phase['max_other_drift'], + } + phase_reports.append({'joint_id': key, 'joint_path': joints[key]['joint_path'], 'other_joint_id': other, + 'command_step': start, 'by_step': end, 'observed_travel': travel, + 'observed_net_displacement': displacement, 'max_other_drift': drift, + 'final_position': values[-1], 'checks': phase_checks, + 'passed': all(phase_checks.values())}) + object_checks = { + 'initial_coordinates_match': all(abs(actual[key][0] - item['initial_position']) <= item['initial_tolerance'] + for key, item in obj['joints'].items()), + 'command_events_match': _check_events(frames, name, joints, obj['phases']), + 'all_phases_passed': all(phase['passed'] for phase in phase_reports), + 'full_actual_measurements': True, + } + result = {'checks': object_checks, 'joints': joint_reports, 'phases': phase_reports, + 'passed': all(object_checks.values())} + checks['all_objects_passed'] = result['passed'] + return {'schema_version': 1, 'passed': all(checks.values()), 'checks': checks, 'objects': {name: result}, + 'negative_control': {'status': 'not_evaluated', + 'scope': 'A matched frozen control run and its paired comparison must be verified externally.'}, + 'scope': 'one run of two scheduled coordinates, independent native and body-frame measurements; no paired-control, contact-triggered or robot-control claim'} + + +def _pin_manifest(manifest, binding, name): + """Match the whole resolved joint tree to the already hash-checked manifest.""" + from ..physics_binding import _relative + from ..preparation.articulation_v2 import runtime_joint + if manifest.get('profile_id') != 'articulated_prop_v2' or binding.get('profile_id') != 'articulated_prop_v2': + raise ValueError('selected object is not a two-DOF prepared profile') + body_map = manifest['body_map'] + joint_map = manifest['joint_map'] + report = manifest['articulation_report'] + if report.get('body_map') != body_map or report.get('joint_map') != joint_map: + raise ValueError('prepared joint graph differs from its inspected graph') + base = '/World/' + name.replace('-', '_') + '/Asset' + def path(relative): + relative = _relative(relative, allow_root=True) + return base + ('/' + relative if relative else '') + paths = {local_id: path(item['relative_prim_path']) for local_id, item in body_map.items()} + if (set(binding['motion_bodies']) != set(paths.values()) or binding['root_body'] != paths[report['root_body_id']] + or set(binding['joints']) != set(joint_map)): + raise ValueError('runtime link tree differs from the prepared manifest') + for key, item in joint_map.items(): + expected = dict(runtime_joint(item), joint_path=path(item['relative_prim_path']), + parent_body=paths[item['parent_body_id']], child_body=paths[item['child_body_id']]) + if binding['joints'][key] != expected: + raise ValueError('runtime joint tree differs from the prepared manifest') + + +def verify_run(directory, case_path=None): + """Check frozen case, selection, all inputs and complete evidence hashes.""" + from ..cache import _sha256 + from ..run_integrity import verify as verify_inputs + from ..evidence_integrity import verify as verify_evidence + from ..physics_binding import validate_asset_binding + root = Path(directory) + for name in ('run-lock.json', 'acceptance-case.json', 'spec.json', 'result.json'): + if (root / name).is_symlink(): + raise ValueError('two-joint acceptance requires ordinary frozen files') + lock = json.loads((root / 'run-lock.json').read_text()) + frozen = root / 'acceptance-case.json' + expected = lock.get('acceptance_case_sha256') + if (lock.get('acceptance_case_file') != 'acceptance-case.json' or not isinstance(expected, str) + or _sha256(frozen) != expected or case_path is not None and _sha256(Path(case_path)) != expected): + raise ValueError('two-joint acceptance case differs from the frozen case') + case = json.loads(frozen.read_text()) + validate_case(case) + run = json.loads((root / 'result.json').read_text()) + result = evaluate(run, case) + checks = result['checks'] + checks['bindings_pinned_to_run'] = (isinstance(lock.get('body_bindings'), dict) + and bool(lock['body_bindings']) and run.get('body_bindings') == lock['body_bindings']) + checks['timing_pinned_to_run'] = (_number(lock.get('physics_dt_s')) + and abs(lock['physics_dt_s'] - case['physics_dt_s']) <= 1e-12 + and type(lock.get('requested_physics_steps')) is int + and lock['requested_physics_steps'] == run.get('requested_physics_steps')) + settings = run.get('physics_settings', {}) + checks['device_pinned_to_run'] = (lock.get('physics_device') in ('default', 'cpu', 'gpu') + and isinstance(settings, dict) and all(isinstance(settings.get(key), dict) + and settings[key].get('requested_device') == lock['physics_device'] + for key in ('before_warmup', 'after_run')) + and ('physics_device' not in case or case['physics_device'] == lock['physics_device'])) + checks['prepared_selection_pinned'] = False + checks['commands_pinned_to_spec'] = False + errors = [] + try: + spec = json.loads((root / 'spec.json').read_text()) + name, item = next(iter(case['objects'].items())) + obj = spec['objects'][name] + if obj.get('kind') != 'asset' or obj.get('dynamic') is not True: + raise ValueError('selected object must be one dynamic prepared asset') + checks['commands_pinned_to_spec'] = obj.get('mechanism') == {'commands': _commands(item['joints'], item['phases'])} + selection = obj['asset_binding'] + if selection['manifest_sha256'] != item['prepared_manifest_sha256']: + raise ValueError('prepared manifest differs from the frozen case') + manifest = validate_asset_binding(selection, require_dynamic=True, asset_path=obj['asset_path']) + if manifest.get('source_ref') != item['source_ref']: + raise ValueError('source reference differs from the frozen case') + _pin_manifest(manifest, run['body_bindings'][name], name) + checks['prepared_selection_pinned'] = True + except (OSError, ValueError, KeyError, TypeError, AttributeError) as error: + errors.append(str(error)) + try: + inputs = verify_inputs(root) + except (OSError, ValueError, KeyError, TypeError, AttributeError) as error: + inputs = {'passed': False, 'errors': [str(error)]} + try: + evidence = verify_evidence(root) + except (OSError, ValueError, KeyError, TypeError, AttributeError) as error: + evidence = {'passed': False, 'partial': None, 'errors': [str(error)]} + result.update(input_integrity=inputs, evidence_integrity=evidence, case_pinned_to_run=True, errors=errors) + result['passed'] = bool(all(checks.values()) and inputs.get('passed') is True + and evidence.get('passed') is True and evidence.get('partial') is False) + return result diff --git a/src/simscene/verification/articulated_asset_two_joint_pair.py b/src/simscene/verification/articulated_asset_two_joint_pair.py new file mode 100644 index 0000000..a7fee77 --- /dev/null +++ b/src/simscene/verification/articulated_asset_two_joint_pair.py @@ -0,0 +1,229 @@ +"""Verify a driven two-joint run against its matched, frozen control run. + +The control omits only the second phase's drive command. Both input closures, +recorded evidence and every physical sample are checked by the single-run +verifier; its expected control failure is not, by itself, a control pass. +""" +import copy +import json +import os +from pathlib import Path +import re + +from . import articulated_asset_two_joint as single + + +_WORKER_FILES = frozenset({'worker/isaac_run.py', 'worker/initial_state.py', + 'worker/mechanism.py', 'worker/mechanism_v2.py'}) +_CONTROL_REQUIRED = frozenset({'full_physics_steps', 'not_partial', 'samples_not_truncated', + 'task_not_failed', 'no_followers', 'complete_per_step_timeline', 'observed_physics_timestep', + 'observed_device_configuration', 'bindings_pinned_to_run', 'timing_pinned_to_run', + 'device_pinned_to_run', 'prepared_selection_pinned'}) + + +def _document(root, name): + path = root / name + if path.is_symlink() or not path.is_file(): + raise ValueError('paired run requires an ordinary frozen file: ' + name) + value = json.loads(path.read_text(encoding='utf8')) + if not isinstance(value, dict): + raise ValueError('paired run document must be an object: ' + name) + return value + + +def _normalize(value, root): + """Keep semantic scene content, replacing only this run's storage prefix.""" + if isinstance(value, dict): + return {key: _normalize(item, root) for key, item in value.items()} + if isinstance(value, list): + return [_normalize(item, root) for item in value] + if isinstance(value, str): + prefix = str(root) + os.sep + if value.startswith(prefix): + return '${RUN}/' + value[len(prefix):] + return value + + +def _scene(spec, root): + result = copy.deepcopy(spec) + for key in ('scene_id', 'revision', 'requests'): + result.pop(key, None) + return _normalize(result, root) + + +def _stage(root): + path = root / 'scene.usda' + if path.is_symlink() or not path.is_file(): + raise ValueError('paired run requires an ordinary frozen stage') + return path.read_bytes().replace((str(root) + os.sep).encode(), b'${RUN}/') + + +def _same_runtime(first, second, positive, control): + """Compare identities that can change simulation while ignoring run IDs.""" + keys = ('runtime_version', 'runtime_python_sha256', 'worker_code_sha256', 'seed', + 'physics_device', 'physics_dt_s', 'requested_physics_steps') + if any(key not in first or key not in second or first[key] != second[key] for key in keys): + return False + if (not isinstance(first['runtime_version'], str) or not first['runtime_version'] + or not isinstance(first['runtime_python_sha256'], str) + or not re.fullmatch('[0-9a-f]{64}', first['runtime_python_sha256']) + or type(first['seed']) is not int or not 0 <= first['seed'] < 2**32 + or type(positive.get('seed')) is not int or type(control.get('seed')) is not int + or positive.get('seed') != first['seed'] or control.get('seed') != second['seed'] + or first['physics_device'] not in ('default', 'cpu', 'gpu') + or not single._number(first['physics_dt_s']) or first['physics_dt_s'] <= 0 + or type(first['requested_physics_steps']) is not int or first['requested_physics_steps'] <= 0): + return False + hashes = first['worker_code_sha256'] + if (not isinstance(hashes, dict) or not _WORKER_FILES <= set(hashes) + or any(not isinstance(value, str) or not re.fullmatch('[0-9a-f]{64}', value) + for value in hashes.values())): + return False + for key in ('queue_launcher_python_sha256', 'gpu_selection', + 'continue_on_controller_error', 'archive_verified_objects'): + if first.get(key) != second.get(key): + return False + return True + + +def _control_events(positive, control, name, omitted_index, commands): + """Require every observed control event to match the frozen command prefix.""" + positive_frames = [positive['initial_observation'], *positive['samples']] + control_frames = [control['initial_observation'], *control['samples']] + positive_events = positive_frames[-1]['mechanisms'][name]['command_events'] + if not isinstance(positive_events, list) or len(positive_events) != len(commands) + 1: + return False + expected = copy.deepcopy(positive_events) + expected.pop(omitted_index) + for index, event in enumerate(expected): + event['command_index'] = index + for frame in control_frames: + step = frame['physics_steps'] + count = sum(command['trigger']['physics_step'] == 0 or command['trigger']['physics_step'] < step + for command in commands) + if frame['mechanisms'][name].get('command_events') != expected[:count]: + return False + return True + + +def verify_pair(positive_directory, control_directory, case_path=None): + """Return a fail-closed comparison of two independent sealed runs. + + Exactly two phases are supported. The control must keep every first-phase + command, including an optional hold, and omit the unique second-phase + drive. Its second joint must remain within that phase's target tolerance of + its own starting value and fail the original target and minimum-travel + requirements. File hashes establish consistency, not signed authenticity. + """ + checks = {name: False for name in ('distinct_runs', 'same_frozen_case', 'positive_passed', + 'same_runtime_seed_device_and_steps', 'same_scene', 'same_stage', 'same_body_bindings', + 'control_input_and_evidence_valid', 'control_only_second_drive_removed', + 'control_command_events_match', 'control_first_phase_passed', 'control_other_joint_held', + 'control_target_stationary', 'control_target_not_reached', 'control_travel_insufficient')} + result = {'schema_version': 1, 'passed': False, 'checks': checks, 'errors': [], + 'scope': 'two sealed, matched runs; no claim of signed authenticity or contact causality'} + try: + positive_root = Path(positive_directory).expanduser().resolve() + control_root = Path(control_directory).expanduser().resolve() + positive_lock = _document(positive_root, 'run-lock.json') + control_lock = _document(control_root, 'run-lock.json') + positive_id, control_id = positive_lock.get('run_id'), control_lock.get('run_id') + checks['distinct_runs'] = (positive_root != control_root and isinstance(positive_id, str) + and isinstance(control_id, str) and bool(positive_id) and bool(control_id) and positive_id != control_id) + positive_case = _document(positive_root, 'acceptance-case.json') + control_case = _document(control_root, 'acceptance-case.json') + single.validate_case(positive_case) + single.validate_case(control_case) + from ..cache import _sha256 + case_hash = _sha256(positive_root / 'acceptance-case.json') + checks['same_frozen_case'] = (positive_case == control_case + and case_hash == _sha256(control_root / 'acceptance-case.json') + and positive_lock.get('acceptance_case_sha256') == case_hash + and control_lock.get('acceptance_case_sha256') == case_hash + and (case_path is None or _sha256(Path(case_path)) == case_hash)) + + positive_report = single.verify_run(positive_root, case_path=case_path) + control_report = single.verify_run(control_root, case_path=case_path) + result['positive'] = positive_report + result['control'] = control_report + checks['positive_passed'] = positive_report.get('passed') is True + positive = _document(positive_root, 'result.json') + control = _document(control_root, 'result.json') + positive_spec = _document(positive_root, 'spec.json') + control_spec = _document(control_root, 'spec.json') + checks['same_runtime_seed_device_and_steps'] = _same_runtime(positive_lock, control_lock, positive, control) + checks['same_body_bindings'] = (isinstance(positive.get('body_bindings'), dict) + and positive['body_bindings'] == control.get('body_bindings')) + checks['same_stage'] = _stage(positive_root) == _stage(control_root) + + name, obj = next(iter(positive_case['objects'].items())) + phases = obj['phases'] + if len(phases) != 2 or phases[0]['joint_id'] == phases[1]['joint_id']: + raise ValueError('paired control requires exactly two different joint phases') + positive_commands = positive_spec['objects'][name]['mechanism']['commands'] + control_commands = control_spec['objects'][name]['mechanism']['commands'] + if not isinstance(positive_commands, list) or not isinstance(control_commands, list): + raise ValueError('paired mechanism commands must be lists') + phase = phases[1] + matches = [index for index, command in enumerate(positive_commands) + if isinstance(command, dict) and command.get('joint_id') == phase['joint_id'] + and command.get('trigger') == {'type': 'at_step', 'physics_step': phase['command_step']}] + if len(matches) != 1: + raise ValueError('second phase must have one unique drive command') + omitted = matches[0] + expected_control = copy.deepcopy(positive_commands) + expected_control.pop(omitted) + checks['control_only_second_drive_removed'] = control_commands == expected_control + normalized_positive = copy.deepcopy(positive_spec) + normalized_positive['objects'][name]['mechanism']['commands'] = expected_control + checks['same_scene'] = _scene(normalized_positive, positive_root) == _scene(control_spec, control_root) + checks['control_command_events_match'] = _control_events(positive, control, name, omitted, expected_control) + + control_checks = control_report.get('checks', {}) + integrity = control_report.get('input_integrity', {}) + evidence = control_report.get('evidence_integrity', {}) + allowed_failures = {'all_objects_passed', 'commands_pinned_to_spec'} + checks['control_input_and_evidence_valid'] = ( + control_report.get('passed') is False and control_report.get('case_pinned_to_run') is True + and isinstance(control_checks, dict) and _CONTROL_REQUIRED <= set(control_checks) + and all(value is True for key, value in control_checks.items() if key not in allowed_failures) + and all(control_checks.get(key) is False for key in allowed_failures) + and integrity.get('passed') is True and integrity.get('checks', {}).get('worker_code_snapshot') is True + and evidence.get('passed') is True and evidence.get('partial') is False + and positive_report.get('input_integrity', {}).get('checks', {}).get('worker_code_snapshot') is True) + observed = control_report.get('objects', {}).get(name, {}) + object_checks = observed.get('checks', {}) + reports = observed.get('phases', []) + if (not isinstance(object_checks, dict) or object_checks.get('initial_coordinates_match') is not True + or object_checks.get('full_actual_measurements') is not True + or object_checks.get('command_events_match') is not False + or object_checks.get('all_phases_passed') is not False + or not isinstance(reports, list) or len(reports) != 2): + raise ValueError('control lacks complete independently measured two-phase evidence') + checks['control_first_phase_passed'] = reports[0].get('passed') is True + second_checks = reports[1].get('checks', {}) + checks['control_other_joint_held'] = (second_checks.get('other_target_held') is True + and second_checks.get('other_drift_within_limit') is True) + frames = [control['initial_observation'], *control['samples']] + path = obj['joints'][phase['joint_id']]['joint_path'] + values = [frame['native_joint_positions'][path] + for frame in frames[phase['command_step']:phase['by_step'] + 1]] + if not values or not all(single._number(value) for value in values): + raise ValueError('control second-phase native positions are missing or nonfinite') + deviation = max(abs(value - values[0]) for value in values) + travel = max(values) - min(values) + target_error = abs(values[-1] - phase['target_position']) + checks['control_target_stationary'] = deviation <= phase['target_tolerance'] + checks['control_target_not_reached'] = (target_error > phase['target_tolerance'] + and second_checks.get('target_reached') is False) + checks['control_travel_insufficient'] = (travel < phase['min_travel'] + and second_checks.get('measured_travel') is False) + result['negative_control'] = {'joint_id': phase['joint_id'], 'joint_path': path, + 'command_step': phase['command_step'], 'by_step': phase['by_step'], + 'start_position': values[0], 'final_position': values[-1], 'max_start_deviation': deviation, + 'observed_travel': travel, 'target_error': target_error, + 'stationary_tolerance': phase['target_tolerance'], 'minimum_travel': phase['min_travel']} + except (OSError, ValueError, TypeError, KeyError, AttributeError, IndexError, OverflowError) as error: + result['errors'].append(str(error)) + result['passed'] = all(value is True for value in checks.values()) + return result diff --git a/src/simscene/verification/case_runner.py b/src/simscene/verification/case_runner.py index f50ef37..d9b0c6d 100644 --- a/src/simscene/verification/case_runner.py +++ b/src/simscene/verification/case_runner.py @@ -9,6 +9,7 @@ TYPES={'contact':'contact_pick','suction':'suction_pick','moving':'moving_pick','repeated':'repeated_pick','domino':'domino','parallel':'parallel_probe','stream':'stream_probe','mechanism':'mechanism_adapter','passive_network':'passive_network'} TYPES['rigid_asset_smoke']='rigid_asset_smoke' TYPES['articulated_asset_smoke']='articulated_asset_smoke' +TYPES['articulated_asset_two_joint']='articulated_asset_two_joint' TYPES['container_asset_smoke']='container_asset_smoke' TYPES['asset_gallery']='asset_gallery' TYPES['handoff_chain']='handoff_chain' @@ -59,6 +60,7 @@ def evaluate(run_path,case_path=None,case_type=None,spec_path=None,mode='positiv if case_type is None: if case.get('schema')=='simscene.rigid_asset_smoke.v1':case_type='rigid_asset_smoke' elif case.get('schema')=='simscene.articulated_asset_smoke.v1':case_type='articulated_asset_smoke' + elif case.get('schema')=='simscene.articulated_asset_two_joint.v1':case_type='articulated_asset_two_joint' elif case.get('schema')=='simscene.container_asset_smoke.v1':case_type='container_asset_smoke' elif case.get('schema')=='simscene.asset_gallery.v1':case_type='asset_gallery' elif case.get('schema')=='simscene.handoff_chain.v1':case_type='handoff_chain' @@ -68,6 +70,13 @@ def evaluate(run_path,case_path=None,case_type=None,spec_path=None,mode='positiv elif 'objects' in case:case_type='parallel' else:raise ValueError('case type is required when it cannot be inferred') if case_type not in TYPES:raise ValueError('unsupported verification case type') + if case.get('schema')=='simscene.articulated_asset_two_joint.v1' and case_type!='articulated_asset_two_joint': + raise ValueError('two-joint case requires its dedicated imported-articulation verifier') + if case_type=='articulated_asset_two_joint' and mode=='missing_second_joint_drive': + if not directory or reference_run is None: + raise ValueError('two-joint paired verification requires a control and positive reference run') + pair=importlib.import_module('.articulated_asset_two_joint_pair',__package__) + return {**pair.verify_pair(reference_run,directory,case_path),'case_type':case_type,'mode':mode} module_name=TYPES[case_type] if case.get('schema')=='simscene.mechanism.v2': if case_type!='mechanism':raise ValueError('v2 D6 case requires mechanism verification') @@ -79,7 +88,7 @@ def evaluate(run_path,case_path=None,case_type=None,spec_path=None,mode='positiv if case_type=='handoff_chain': if not directory:raise ValueError('handoff verification requires the complete frozen run directory') return {**module.verify_run(directory,case_path,mode,reference_directory=reference_run),'case_type':case_type} - if case_type in ('rigid_asset_smoke','articulated_asset_smoke','container_asset_smoke','asset_gallery'): + if case_type in ('rigid_asset_smoke','articulated_asset_smoke','articulated_asset_two_joint','container_asset_smoke','asset_gallery'): if not directory or mode!='positive' or reference_run is not None: raise ValueError('imported asset verification requires a frozen run directory and its own case') return {**module.verify_run(directory,case_path),'case_type':case_type} diff --git a/src/simscene/worker/initial_state.py b/src/simscene/worker/initial_state.py index aaa5a88..fdcae38 100644 --- a/src/simscene/worker/initial_state.py +++ b/src/simscene/worker/initial_state.py @@ -60,11 +60,12 @@ def visual_bounds(stage, objects, body_bindings=None): return result class PassiveState: - def __init__(self,stage,objects,body_bindings=None,authored_state=None): + def __init__(self,stage,objects,body_bindings=None,authored_state=None,*,is_paused=None): self.delegate=None - if any(binding.get('articulation_roots') for binding in (body_bindings or {}).values()): + if any(binding.get('articulation_roots') or binding.get('profile_id')=='articulated_prop_v2' + for binding in (body_bindings or {}).values()): from .mechanism import PreparedArticulationState - self.delegate=PreparedArticulationState(stage,objects,body_bindings,authored_state) + self.delegate=PreparedArticulationState(stage,objects,body_bindings,authored_state,is_paused=is_paused) return import omni.physics.tensors as tensors import omni.usd @@ -77,6 +78,9 @@ def refresh(self): self.view=self.sim.create_rigid_body_view('/World/**' if self.body_bindings else '/World/*') self.paths=list(self.view.prim_paths) + def mark_task_started(self): + if getattr(self,'delegate',None) is not None:return self.delegate.mark_task_started() + def read(self): if getattr(self,'delegate',None) is not None:return self.delegate.read() transforms=np.asarray(self.view.get_transforms()).copy();velocities=np.asarray(self.view.get_velocities()).copy() diff --git a/src/simscene/worker/isaac_run.py b/src/simscene/worker/isaac_run.py index 4187cfc..b45ccea 100644 --- a/src/simscene/worker/isaac_run.py +++ b/src/simscene/worker/isaac_run.py @@ -251,7 +251,8 @@ def phase(name): app.update() # Complete the SDK's physics setup before restoring t0. app_utils.pause() from simscene.worker.initial_state import PassiveState - state_reader=PassiveState(stage,spec['objects'],body_bindings=body_bindings,authored_state=authored_initial_state);initialization_reset=state_reader.reset_before_task() + state_reader=PassiveState(stage,spec['objects'],body_bindings=body_bindings,authored_state=authored_initial_state, + is_paused=getattr(app_utils,'is_paused',None));initialization_reset=state_reader.reset_before_task() initialization_reset.update(before_warmup_absolute_physics_step=initialization_before_steps,before_warmup_absolute_simulation_time_s=initialization_before_time,after_warmup_absolute_physics_step=SimulationManager.get_num_physics_steps(),after_warmup_absolute_simulation_time_s=SimulationManager.get_simulation_time()) paused_steps=SimulationManager.get_num_physics_steps() for _ in range(3):app.update() @@ -290,6 +291,7 @@ def phase(name): if not binding.get('joints'):continue mechanism_controllers[name]=MechanismController(binding,spec['objects'][name].get('mechanism',{}),backend=UsdMechanismBackend(stage,state_reader)) if strict_start: + state_reader.mark_task_started() initial_native_state=state_reader.read() initial_joint_states=sample_joints(stage,spec['objects'],native_state=initial_native_state) mechanism_configuration['mass_properties_by_prim_path']=state_reader.mass_properties(0) diff --git a/src/simscene/worker/mechanism.py b/src/simscene/worker/mechanism.py index 25f27db..94fc60a 100644 --- a/src/simscene/worker/mechanism.py +++ b/src/simscene/worker/mechanism.py @@ -38,8 +38,12 @@ def _path(value): def validate_binding(binding): """Validate already-resolved canonical bindings, never infer joint paths.""" joints = binding.get('joints') if isinstance(binding, dict) else None - if not isinstance(joints, dict) or len(joints) != 1: + two_dof = isinstance(binding, dict) and binding.get('profile_id') == 'articulated_prop_v2' + if not isinstance(joints, dict) or len(joints) != (2 if two_dof else 1): raise ValueError('M2 mechanism requires exactly one declared single-DOF joint') + if two_dof: + from .mechanism_v2 import TwoDofTensorState + TwoDofTensorState._validate_binding(binding) for joint_id, joint in joints.items(): if not isinstance(joint_id, str) or not joint_id or not isinstance(joint, dict): raise ValueError('invalid mechanism joint identity') @@ -136,10 +140,13 @@ def step(self, physics_step, events=None): raise RuntimeError('missed mechanism command physics step; refusing a late target') joint_id = command['joint_id'] readback = self.backend.apply_drive(self.binding['joints'][joint_id], command) - self.events.append({'command_index': index, 'joint_id': joint_id, - 'physics_step': physics_step, 'trigger': copy.deepcopy(command['trigger']), - 'target_position': command['target_position'], 'position_unit': command['position_unit'], - 'drive_readback': readback, 'cause': 'declared_at_step_schedule'}) + event = {'command_index': index, 'joint_id': joint_id, + 'physics_step': physics_step, 'trigger': copy.deepcopy(command['trigger']), + 'target_position': command['target_position'], 'position_unit': command['position_unit'], + 'drive_readback': readback, 'cause': 'declared_at_step_schedule'} + if self.binding.get('profile_id') == 'articulated_prop_v2': + event['joint_path'] = self.binding['joints'][joint_id]['joint_path'] + self.events.append(event) self.targets[joint_id] = copy.deepcopy(command) self._executed.add(index) # Contact events are deliberately not interpreted as triggers in M2. @@ -152,7 +159,9 @@ def observe(self, physics_step=None, native_state=None): measured = self.backend.observe(self.binding, step, native_state=native_state) return {'physics_step': step, 'joints': measured, 'runtime_targets': copy.deepcopy(self.targets), 'command_events': copy.deepcopy(self.events), - 'control_scope': 'explicit single-DOF at_step drive targets; no body pose setters'} + 'control_scope': ('explicit two-DOF at_step drive targets; no body pose setters' + if self.binding.get('profile_id') == 'articulated_prop_v2' else + 'explicit single-DOF at_step drive targets; no body pose setters')} def _mul(a, b): @@ -168,7 +177,8 @@ def _rotate(q, p): return _mul(_mul(q, [0., *p]), _inverse(q))[1:] -def measure_joint(joint, native_state, previous=None, *, physics_step, physics_dt_s): +def measure_joint(joint, native_state, previous=None, *, physics_step, physics_dt_s, + require_unique_initial=False): """Reconstruct a signed coordinate from two same-sample body tensor poses.""" frames = [] for suffix, body in [('0', joint['parent_body']), ('1', joint['child_body'])]: @@ -187,6 +197,7 @@ def measure_joint(joint, native_state, previous=None, *, physics_step, physics_d if joint['type'] == 'prismatic': position = relative_p[axis] anchor_error = math.sqrt(sum(v*v for i, v in enumerate(relative_p) if i != axis)) + locked_rotation_error = 2 * math.atan2(math.sqrt(sum(v*v for v in relative_q[1:])), abs(relative_q[0])) else: position = 2 * math.atan2(relative_q[axis+1], relative_q[0]) position = (position + math.pi) % (2*math.pi) - math.pi @@ -194,12 +205,25 @@ def measure_joint(joint, native_state, previous=None, *, physics_step, physics_d last = previous['position'] position = last + (position - last + math.pi) % (2*math.pi) - math.pi else: - # Choose the unique representative inside the frozen finite range. - candidates = [position + 2*math.pi*k for k in (-1, 0, 1) - if joint['limits'][0]-1e-4 <= position+2*math.pi*k <= joint['limits'][1]+1e-4] - if len(candidates) == 1: - position = candidates[0] + # Find the unique integer turn inside the finite frozen range, + # without assuming the authored interval lies within one turn of 0. + period = 2 * math.pi + lower = math.ceil((joint['limits'][0] - position) / period) + upper = math.floor((joint['limits'][1] - position) / period) + if lower > upper: + # Permit the existing small endpoint tolerance only when no + # exact representative exists, without making one exact angle + # appear ambiguous in a near-single-turn interval. + lower = math.ceil((joint['limits'][0] - 1e-4 - position) / period) + upper = math.floor((joint['limits'][1] + 1e-4 - position) / period) + if lower == upper: + position += period * lower + elif require_unique_initial: + raise ValueError('joint pose has no unique initial angle in its frozen limits') anchor_error = math.sqrt(sum(v*v for v in difference)) + perpendicular = math.sqrt(sum(v*v for i, v in enumerate(relative_q[1:]) if i != axis)) + twist = math.hypot(relative_q[0], relative_q[axis+1]) + locked_rotation_error = 2 * math.atan2(perpendicular, twist) velocity = None if previous is not None: delta = physics_step - previous['physics_step'] @@ -213,7 +237,8 @@ def measure_joint(joint, native_state, previous=None, *, physics_step, physics_d velocity = (position - previous['position']) / (delta * physics_dt_s) return {'position': position, 'velocity': velocity, 'position_unit': joint['position_unit'], 'velocity_unit': joint['position_unit'] + '/s', 'physics_step': physics_step, - 'anchor_error_m': anchor_error, 'parent_body': joint['parent_body'], 'child_body': joint['child_body'], + 'anchor_error_m': anchor_error, 'locked_rotation_error_rad': locked_rotation_error, + 'parent_body': joint['parent_body'], 'child_body': joint['child_body'], 'joint_path': joint['joint_path'], 'measurement_source': 'same_sample_PhysX_body_poses_joint_frame_reconstruction'} @@ -273,6 +298,16 @@ def observe(self, binding, physics_step, native_state=None): for name, joint in binding['joints'].items(): result[name] = measure_joint(joint, native_state, self.previous.get(name), physics_step=physics_step, physics_dt_s=self.physics_dt_s) + if binding.get('profile_id') == 'articulated_prop_v2': + path = joint['joint_path'] + positions = native_state.get('native_joint_positions') + velocities = native_state.get('native_joint_velocities') + if (not isinstance(positions, dict) or not isinstance(velocities, dict) + or path not in positions or path not in velocities + or native_state.get('native_joint_measurement_source') != 'PhysX_articulation_tensor_DOF_readback_SI'): + raise RuntimeError('two-DOF observation requires native position and velocity for every frozen joint') + _number(positions[path], 'native DOF position') + _number(velocities[path], 'native DOF velocity') if joint['joint_path'] in native_state.get('native_joint_positions',{}): result[name].update(native_position=native_state['native_joint_positions'][joint['joint_path']],native_velocity=native_state['native_joint_velocities'][joint['joint_path']],native_measurement_source=native_state['native_joint_measurement_source']) self.previous = copy.deepcopy(result) @@ -285,30 +320,58 @@ class PreparedArticulationState: Setters exist only in reset_before_task(), once while paused before task zero. Runtime read() is read-only and includes independent native DOF readback. """ - def __init__(self, stage, objects, body_bindings, authored_state): + def __init__(self, stage, objects, body_bindings, authored_state, *, + simulation_view=None, root_link_type=None, is_paused=None): import numpy as np - import omni.physics.tensors as tensors - import omni.usd self.np=np;self.stage=stage;self.objects=objects;self.bindings=body_bindings - self.authored=authored_state;self.reset_count=0 + self.authored=authored_state;self.reset_count=0;self._is_paused=is_paused + self._reset_attempted=False;self._reset_verified=False;self._task_started=False if authored_state is None:raise RuntimeError('articulated strict reset requires pre-warmup authored state') - self.sim=tensors.create_simulation_view('numpy',stage_id=omni.usd.get_context().get_stage_id()) - self.sim.set_subspace_roots('/') - self.articulations=[];art_paths=set() + has_v2=any(binding.get('profile_id')=='articulated_prop_v2' for binding in body_bindings.values()) + if simulation_view is None: + import omni.physics.tensors as tensors + import omni.usd + self.sim=tensors.create_simulation_view('numpy',stage_id=omni.usd.get_context().get_stage_id()) + self.sim.set_subspace_roots('/') + if has_v2: + try:root_link_type=tensors.ObjectType.ArticulationRootLink + except AttributeError as error:raise RuntimeError('PhysX root-link enum is unavailable') from error + else: + self.sim=simulation_view + if has_v2 and (root_link_type is None or not callable(is_paused)): + raise RuntimeError('two-DOF state requires the engine root-link enum and a paused-state query') + self.articulations=[];self.two_dof_articulations=[];art_paths=set();joint_paths=set() for binding in body_bindings.values(): - for root in binding.get('articulation_roots',[]): + roots=binding.get('articulation_roots',[]) + is_v2=binding.get('profile_id')=='articulated_prop_v2' + if is_v2: + validate_binding(binding) + if not isinstance(roots,list) or len(roots)!=1: + raise RuntimeError('two-DOF articulation requires one explicit root view') + for root in roots: view=self.sim.create_articulation_view(root) - if view.count!=1 or view.max_dofs!=1: - raise RuntimeError('prepared native articulation must expose exactly one actual tensor DOF') - paths=list(view.link_paths[0]);dofs=list(view.dof_paths[0]) - if set(paths)!=set(binding['motion_bodies']) or set(dofs)!={j['joint_path'] for j in binding['joints'].values()}: - raise RuntimeError('native articulation tensor graph differs from frozen body/joint binding') - self.articulations.append((view,paths,dofs,binding));art_paths.update(paths) + if is_v2: + from .mechanism_v2 import TwoDofTensorState + adapter=TwoDofTensorState(view,binding,simulation_view=self.sim,root_link_type=root_link_type) + paths=list(adapter.link_paths);dofs=list(adapter.dof_paths) + self.two_dof_articulations.append(adapter) + else: + if view.count!=1 or view.max_dofs!=1: + raise RuntimeError('prepared native articulation must expose exactly one actual tensor DOF') + paths=list(view.link_paths[0]);dofs=list(view.dof_paths[0]) + if set(paths)!=set(binding['motion_bodies']) or set(dofs)!={j['joint_path'] for j in binding['joints'].values()}: + raise RuntimeError('native articulation tensor graph differs from frozen body/joint binding') + self.articulations.append((view,paths,dofs,binding)) + if (len(paths)!=len(set(paths)) or len(dofs)!=len(set(dofs)) + or art_paths.intersection(paths) or joint_paths.intersection(dofs)): + raise RuntimeError('duplicate native tensor body or DOF path across articulations') + art_paths.update(paths);joint_paths.update(dofs) expected=set(authored_state['bodies']) remaining=sorted(expected-art_paths) self.rigid=self.sim.create_rigid_body_view(remaining) if remaining else None self.rigid_paths=list(self.rigid.prim_paths) if self.rigid else [] - self.paths=self.rigid_paths+[p for _,paths,_,_ in self.articulations for p in paths] + self.paths=(self.rigid_paths+[p for _,paths,_,_ in self.articulations for p in paths] + +[p for adapter in self.two_dof_articulations for p in adapter.link_paths]) if len(set(self.paths))!=len(self.paths) or set(self.paths)!=expected: raise RuntimeError('strict articulated tensor body set differs from authored bodies') @@ -318,28 +381,57 @@ def refresh(self): def read(self): np=self.np;transforms=[];velocities=[];paths=[];positions={};speeds={} if self.rigid: - transforms.extend(np.asarray(self.rigid.get_transforms()).copy());velocities.extend(np.asarray(self.rigid.get_velocities()).copy());paths.extend(self.rigid_paths) + rt=np.asarray(self.rigid.get_transforms()).copy();rv=np.asarray(self.rigid.get_velocities()).copy() + if self.two_dof_articulations and (rt.shape!=(len(self.rigid_paths),7) or rv.shape!=(len(self.rigid_paths),6)): + raise RuntimeError('rigid tensor shape differs from frozen body paths') + transforms.extend(rt);velocities.extend(rv);paths.extend(self.rigid_paths) for view,links,dofs,_ in self.articulations: - transforms.extend(np.asarray(view.get_link_transforms())[0,:len(links)].copy()) - velocities.extend(np.asarray(view.get_link_velocities())[0,:len(links)].copy());paths.extend(links) - q=np.asarray(view.get_dof_positions())[0];v=np.asarray(view.get_dof_velocities())[0] + lt=np.asarray(view.get_link_transforms());lv=np.asarray(view.get_link_velocities()) + qa=np.asarray(view.get_dof_positions());va=np.asarray(view.get_dof_velocities()) + if self.two_dof_articulations and (lt.shape!=(1,len(links),7) or lv.shape!=(1,len(links),6) + or qa.shape!=(1,len(dofs)) or va.shape!=(1,len(dofs))): + raise RuntimeError('single-DOF tensor shape differs from frozen body or DOF paths') + transforms.extend(lt[0,:len(links)].copy()) + velocities.extend(lv[0,:len(links)].copy());paths.extend(links) + q=qa[0];v=va[0] positions.update({p:float(q[i]) for i,p in enumerate(dofs)});speeds.update({p:float(v[i]) for i,p in enumerate(dofs)}) transforms=np.asarray(transforms);velocities=np.asarray(velocities) if not np.isfinite(transforms).all() or not np.isfinite(velocities).all() or not all(math.isfinite(x) for x in list(positions.values())+list(speeds.values())): raise RuntimeError('nonfinite native articulation tensor state') - return {'positions':{p:[float(v) for v in transforms[i,:3]] for i,p in enumerate(paths)}, + result={'positions':{p:[float(v) for v in transforms[i,:3]] for i,p in enumerate(paths)}, 'orientations_wxyz':{p:[float(transforms[i,6]),*[float(v) for v in transforms[i,3:6]]] for i,p in enumerate(paths)}, 'linear_velocities_m_s':{p:[float(v) for v in velocities[i,:3]] for i,p in enumerate(paths)}, 'angular_velocities_rad_s':{p:[float(v) for v in velocities[i,3:]] for i,p in enumerate(paths)}, 'native_joint_positions':positions,'native_joint_velocities':speeds, 'native_joint_measurement_source':'PhysX_articulation_tensor_DOF_readback_SI'} + for adapter in self.two_dof_articulations: + observed=adapter.read() + for key in ('positions','orientations_wxyz','linear_velocities_m_s','angular_velocities_rad_s', + 'native_joint_positions','native_joint_velocities'): + if set(result[key]).intersection(observed[key]): + raise RuntimeError('duplicate native tensor path during readback') + result[key].update(observed[key]) + root_velocities=result.setdefault('native_root_velocities',{}) + if set(root_velocities).intersection(observed['native_root_velocities']): + raise RuntimeError('duplicate native root tensor path during readback') + root_velocities.update(observed['native_root_velocities']) + return result def mass_properties(self,physics_step): np=self.np;result={} + assumptions={} + for binding in self.bindings.values(): + for entry in binding.get('bodies',{}).values(): + if entry.get('mass_provenance'): + assumptions[entry['motion_body']]={'mass_provenance':entry['mass_provenance'], + 'native_repairs_ref':copy.deepcopy(binding.get('native_repairs_ref'))} groups=[] if self.rigid:groups.append((self.rigid_paths,np.asarray(self.rigid.get_masses()),np.asarray(self.rigid.get_coms()),np.asarray(self.rigid.get_inertias()))) for view,paths,_,_ in self.articulations: groups.append((paths,np.asarray(view.get_masses())[0,:len(paths)],np.asarray(view.get_coms())[0,:len(paths)],np.asarray(view.get_inertias())[0,:len(paths)])) + for adapter in self.two_dof_articulations: + view=adapter.view;paths=adapter.link_paths + groups.append((paths,np.asarray(view.get_masses())[0,:len(paths)],np.asarray(view.get_coms())[0,:len(paths)],np.asarray(view.get_inertias())[0,:len(paths)])) for paths,masses,coms,inertias in groups: masses=masses.reshape(len(paths));coms=coms.reshape(len(paths),7);inertias=inertias.reshape(len(paths),9) for i,path in enumerate(paths): @@ -350,11 +442,16 @@ def mass_properties(self,physics_step): result[path]={'mass_kg':float(masses[i]),'center_of_mass_local_m':[float(v) for v in coms[i,:3]], 'principal_axes_local_wxyz':[float(coms[i,6]),*[float(v) for v in coms[i,3:6]]], 'inertia_at_com_in_prim_axes_kg_m2':[[float(v) for v in row] for row in inertia], - 'observed_at_physics_step':physics_step,'source':'PhysX native articulation/rigid tensor cooked mass properties; source mass/collision preserved'} + 'observed_at_physics_step':physics_step,'source':'PhysX native articulation/rigid tensor cooked mass properties; see prepared manifest for authored or experimental assumptions'} + if path in assumptions:result[path].update(assumptions[path]) return result def reset_before_task(self): if self.reset_count:raise RuntimeError('strict articulated initialization reset may run only once') + if self.two_dof_articulations: + if self._reset_attempted or self._task_started:raise RuntimeError('two-DOF initialization is allowed only once before task start') + if self._is_paused() is not True:raise RuntimeError('two-DOF initialization requires a paused timeline') + self._reset_attempted=True np=self.np;expected=self.authored['bodies'] def transform(path): body=expected[path];q=body['orientation_wxyz'];return [*body['position'],*q[1:],q[0]] @@ -373,7 +470,11 @@ def transform(path): values.append(measure_joint(joint,authored_native,physics_step=0,physics_dt_s=1/60)['position']) view.set_dof_positions(np.asarray([values],dtype=np.float32),indices) view.set_dof_velocities(np.zeros((1,len(values)),dtype=np.float32),indices) + for adapter in self.two_dof_articulations: + adapter.reset_before_task(self.authored,is_paused=self._is_paused) self.sim.update_articulations_kinematic() + if self.two_dof_articulations and self._is_paused() is not True: + raise RuntimeError('timeline resumed during two-DOF initialization') from .initial_state import restore_local_ops restore_local_ops(self.stage,self.authored);self.reset_count=1 observed=self.read();position_error=0.;rotation_error=0.;speed=0. @@ -384,8 +485,15 @@ def transform(path): speed=max(speed,float(np.linalg.norm(observed['linear_velocities_m_s'][path])),float(np.linalg.norm(observed['angular_velocities_rad_s'][path]))) if position_error>1e-6 or rotation_error>1e-6 or speed>1e-7: raise RuntimeError('native articulation strict authored-pose/zero-velocity reset mismatch') + self._reset_verified=True return {'applied':True,'phase':'before_task_start','reset_count':1,'body_paths':self.paths, 'authored_pose_capture_phase':self.authored['phase'],'authored_pose_readback_max_error_m':position_error, 'max_quaternion_error':rotation_error,'max_speed':speed,'local_xform_ops_restored':True, 'setters_during_task':False,'native_articulation_joint_reset':True, 'scope':'one paused pre-task native articulation root/DOF reset; runtime readback only'} + + def mark_task_started(self): + if self.two_dof_articulations and not self._reset_verified: + raise RuntimeError('two-DOF task requires a successfully verified initialization') + for adapter in self.two_dof_articulations:adapter.mark_task_started() + self._task_started=True diff --git a/src/simscene/worker/mechanism_v2.py b/src/simscene/worker/mechanism_v2.py new file mode 100644 index 0000000..5eecf3c --- /dev/null +++ b/src/simscene/worker/mechanism_v2.py @@ -0,0 +1,242 @@ +"""Isolated two-single-axis articulation tensor adapter. + +The caller supplies an already-created NumPy PhysX view and its simulation view. +No Isaac integration or runtime physics validation is implied by this module. +""" +import copy +import math + +from .mechanism import _path, _quaternion, _vector, measure_joint + +RESET_LOCKED_ROTATION_TOLERANCE_RAD = 1e-4 + + +class TwoDofTensorState: + """Read a frozen two-DOF tree and reset it once while paused before a task. + + ``binding`` contains ``root_body``, three ``motion_bodies``, and two + single-axis ``joints`` with explicit absolute paths, frames and SI limits. + ``root_link_type`` must be the target engine's ArticulationRootLink enum; + the caller must call ``mark_task_started`` before starting task physics. + The view and authored poses must use the same world/subspace reference frame. + """ + + def __init__(self, view, binding, *, simulation_view, root_link_type): + import numpy as np + + self.np = np + self.view = view + self.simulation_view = simulation_view + self.root_link_type = root_link_type + if root_link_type is None or not callable(getattr(simulation_view, 'get_object_type', None)): + raise ValueError('an engine root-link type and object-type query are required') + self.binding = copy.deepcopy(binding) + self.root_body, expected_links, self.by_path = self._validate_binding(self.binding) + self.link_paths, self.dof_paths = self._current_graph() + if (len(set(self.link_paths)) != 3 or set(self.link_paths) != set(expected_links) + or len(set(self.dof_paths)) != 2 or set(self.dof_paths) != set(self.by_path)): + raise RuntimeError('tensor paths are not a bijection with the frozen articulation graph') + self._check_actual_root() + self._reset_attempted = False + self._reset_completed = False + self._task_started = False + + @staticmethod + def _validate_binding(binding): + if not isinstance(binding, dict): + raise ValueError('two-DOF binding must be a dictionary') + links = binding.get('motion_bodies') + root = binding.get('root_body') + joints = binding.get('joints') + if (not isinstance(links, (list, tuple)) or len(links) != 3 + or any(not _path(path) for path in links) or len(set(links)) != 3 or root not in links): + raise ValueError('two-DOF binding requires three distinct links and an explicit root') + if not isinstance(joints, dict) or len(joints) != 2: + raise ValueError('two-DOF binding requires exactly two named joints') + by_path = {} + incoming = {path: 0 for path in links} + edges = {} + for name, joint in joints.items(): + if not isinstance(name, str) or not name or not isinstance(joint, dict): + raise ValueError('invalid frozen joint identity') + path = joint.get('joint_path') + parent, child = joint.get('parent_body'), joint.get('child_body') + if not _path(path) or path in by_path: + raise ValueError('frozen joint paths must be distinct and absolute') + if parent not in incoming or child not in incoming or parent == child: + raise ValueError('frozen joint endpoints must be distinct links in this articulation') + unit = {'revolute': 'rad', 'prismatic': 'm'}.get(joint.get('type')) + if unit is None or joint.get('position_unit') != unit or joint.get('axis') not in ('X', 'Y', 'Z'): + raise ValueError('only single-axis SI revolute or prismatic joints are supported') + limits = _vector(joint.get('limits'), 2, 'joint limits') + if limits[0] >= limits[1] or unit == 'rad' and limits[1] - limits[0] >= 2 * math.pi: + raise ValueError('joint limits must be ordered and angular initialization unambiguous') + for suffix in ('0', '1'): + _vector(joint.get('local_pos' + suffix + '_m'), 3, 'joint local position') + _quaternion(joint.get('local_rot' + suffix + '_wxyz')) + by_path[path] = joint + incoming[child] += 1 + edges.setdefault(parent, []).append(child) + if [path for path, count in incoming.items() if count == 0] != [root] or any(v > 1 for v in incoming.values()): + raise ValueError('frozen articulation must have one explicit root and unique child links') + visited, pending = set(), [root] + while pending: + current = pending.pop() + if current in visited: + raise ValueError('frozen articulation contains a cycle') + visited.add(current) + pending.extend(edges.get(current, [])) + if visited != set(links): + raise ValueError('frozen articulation graph is disconnected') + return root, tuple(links), by_path + + def _current_graph(self): + try: + if self.view.count != 1 or self.view.max_dofs != 2: + raise RuntimeError('tensor view must contain one articulation with two DOFs') + metadata = self.view.get_metatype(0) + if metadata.dof_count != 2 or metadata.link_count != 3: + raise RuntimeError('actual tensor metatype must expose two DOFs and three links') + links, dofs = self.view.link_paths, self.view.dof_paths + if len(links) != 1 or len(dofs) != 1: + raise RuntimeError('tensor path arrays must contain exactly one articulation') + links, dofs = tuple(links[0]), tuple(dofs[0]) + if (len(links) != 3 or len(dofs) != 2 + or any(not _path(path) for path in links + dofs)): + raise RuntimeError('tensor link or DOF path array has an invalid shape') + return links, dofs + except (AttributeError, TypeError, IndexError) as error: + raise RuntimeError('tensor view does not expose a verifiable articulation graph') from error + + def _check_actual_root(self): + try: + roots = [path for path in self.link_paths + if self.simulation_view.get_object_type(path) == self.root_link_type] + except Exception as error: + raise RuntimeError('engine root-link identity could not be checked') from error + if roots != [self.root_body]: + raise RuntimeError('engine root link differs from the frozen explicit root body') + + def _check_current_graph(self): + if self._current_graph() != (self.link_paths, self.dof_paths): + raise RuntimeError('tensor path order or graph changed after binding') + self._check_actual_root() + + def _array(self, value, shape, name): + np = self.np + try: + array = np.asarray(value) + if (array.shape != shape or not np.issubdtype(array.dtype, np.number) + or np.issubdtype(array.dtype, np.complexfloating)): + raise RuntimeError(name + ' tensor has an invalid shape or type') + array = array.astype(np.float64, copy=True) + if not np.isfinite(array).all(): + raise RuntimeError(name + ' tensor contains a nonfinite value') + return array + except (TypeError, ValueError, OverflowError) as error: + raise RuntimeError(name + ' tensor is invalid') from error + + def read(self): + """Return per-path actual link poses and PhysX DOF q/v in SI units.""" + self._check_current_graph() + q = self._array(self.view.get_dof_positions(), (1, 2), 'DOF position')[0] + v = self._array(self.view.get_dof_velocities(), (1, 2), 'DOF velocity')[0] + transforms = self._array(self.view.get_link_transforms(), (1, 3, 7), 'link transform')[0] + velocities = self._array(self.view.get_link_velocities(), (1, 3, 6), 'link velocity')[0] + root = self._array(self.view.get_root_transforms(), (1, 7), 'root transform')[0] + root_velocity = self._array(self.view.get_root_velocities(), (1, 6), 'root velocity')[0] + for quat in [root[3:7], *(row[3:7] for row in transforms)]: + if abs(float(quat @ quat) - 1.) > 1e-4: + raise RuntimeError('tensor link/root quaternion is not normalized') + root_index = self.link_paths.index(self.root_body) + root_link = transforms[root_index] + rotation_error = min(self.np.linalg.norm(root[3:] - root_link[3:]), + self.np.linalg.norm(root[3:] + root_link[3:])) + if self.np.linalg.norm(root[:3] - root_link[:3]) > 1e-5 or rotation_error > 1e-5: + raise RuntimeError('root tensor transform differs from the verified root link') + return {'positions': {path: transforms[i, :3].tolist() for i, path in enumerate(self.link_paths)}, + 'orientations_wxyz': {path: [float(transforms[i, 6]), *transforms[i, 3:6].tolist()] + for i, path in enumerate(self.link_paths)}, + 'linear_velocities_m_s': {path: velocities[i, :3].tolist() for i, path in enumerate(self.link_paths)}, + 'angular_velocities_rad_s': {path: velocities[i, 3:].tolist() for i, path in enumerate(self.link_paths)}, + 'root_linear_velocity_m_s': root_velocity[:3].tolist(), + 'root_angular_velocity_rad_s': root_velocity[3:].tolist(), + 'native_root_velocities': {self.root_body: { + 'linear_velocity_m_s': root_velocity[:3].tolist(), + 'angular_velocity_rad_s': root_velocity[3:].tolist(), + 'source': 'PhysX_articulation_tensor_root_velocity_raw', + 'scope': 'raw root getter may be stale while sleeping; not an independent motion measurement'}}, + 'native_joint_positions': {path: float(q[i]) for i, path in enumerate(self.dof_paths)}, + 'native_joint_velocities': {path: float(v[i]) for i, path in enumerate(self.dof_paths)}, + 'native_joint_measurement_source': 'PhysX_articulation_tensor_DOF_readback_SI'} + + def mark_task_started(self): + """Prevent future reset as soon as the caller begins task physics.""" + if self._reset_attempted and not self._reset_completed: + raise RuntimeError('cannot start a task after an incomplete articulation reset') + self._task_started = True + + def reset_before_task(self, authored_state, *, is_paused): + """Reset once, in tensor order, then verify actual DOF and link readback.""" + if self._task_started or self._reset_attempted: + raise RuntimeError('articulation reset is allowed only once before the task') + if not callable(is_paused) or is_paused() is not True: + raise RuntimeError('articulation reset requires a paused simulation') + self._check_current_graph() + if not isinstance(authored_state, dict) or not isinstance(authored_state.get('bodies'), dict): + raise ValueError('reset requires frozen authored body poses') + bodies = authored_state['bodies'] + positions, orientations = {}, {} + for path in self.link_paths: + body = bodies.get(path) + if not isinstance(body, dict): + raise ValueError('missing frozen authored link pose') + positions[path] = _vector(body.get('position'), 3, 'authored link position') + orientations[path] = _quaternion(body.get('orientation_wxyz')) + authored = {'positions': positions, 'orientations_wxyz': orientations} + values = [] + for path in self.dof_paths: + joint = self.by_path[path] + measured = measure_joint(joint, authored, physics_step=0, physics_dt_s=1 / 60, + require_unique_initial=True) + position = measured['position'] + if (not math.isfinite(position) or measured['anchor_error_m'] > 1e-4 + or measured['locked_rotation_error_rad'] > RESET_LOCKED_ROTATION_TOLERANCE_RAD + or position < joint['limits'][0] - 1e-4 or position > joint['limits'][1] + 1e-4): + raise ValueError('authored joint frame or position is inconsistent with the frozen binding') + values.append(position) + np = self.np + root_q = orientations[self.root_body] + root_transform = np.asarray([[*positions[self.root_body], *root_q[1:], root_q[0]]], dtype=np.float32) + dof_positions = np.asarray([values], dtype=np.float32) + if not np.isfinite(root_transform).all() or not np.isfinite(dof_positions).all(): + raise ValueError('authored reset pose exceeds the tensor numeric range') + if is_paused() is not True: + raise RuntimeError('simulation resumed before the articulation reset') + self._reset_attempted = True # A partial write must never be retried. + indices = np.asarray([0], dtype=np.uint32) + self.view.set_root_transforms(root_transform, indices) + self.view.set_root_velocities(np.zeros((1, 6), dtype=np.float32), indices) + self.view.set_dof_positions(dof_positions, indices) + self.view.set_dof_velocities(np.zeros((1, 2), dtype=np.float32), indices) + self.simulation_view.update_articulations_kinematic() + if is_paused() is not True: + raise RuntimeError('simulation resumed during the articulation reset') + observed = self.read() + if (np.linalg.norm(observed['root_linear_velocity_m_s']) > 1e-7 + or np.linalg.norm(observed['root_angular_velocity_rad_s']) > 1e-7): + raise RuntimeError('native root reset velocity is not zero') + for index, path in enumerate(self.dof_paths): + if (abs(observed['native_joint_positions'][path] - values[index]) > 1e-6 + or abs(observed['native_joint_velocities'][path]) > 1e-7): + raise RuntimeError('native DOF reset readback differs from the authored coordinate') + for path in self.link_paths: + actual_q = np.asarray(observed['orientations_wxyz'][path]) + expected_q = np.asarray(orientations[path]) + if (np.linalg.norm(np.asarray(observed['positions'][path]) - positions[path]) > 1e-6 + or min(np.linalg.norm(actual_q - expected_q), np.linalg.norm(actual_q + expected_q)) > 1e-6 + or np.linalg.norm(observed['linear_velocities_m_s'][path]) > 1e-7 + or np.linalg.norm(observed['angular_velocities_rad_s'][path]) > 1e-7): + raise RuntimeError('native link reset readback differs from the authored pose or zero velocity') + self._reset_completed = True + return observed diff --git a/tests/agent/test_package.py b/tests/agent/test_package.py index 166b557..52f2f26 100644 --- a/tests/agent/test_package.py +++ b/tests/agent/test_package.py @@ -39,6 +39,9 @@ async def check_independent_metadata(root,plugin): from simscene.recipes.registry import list_recipes assert list_recipes()['recipes'] assert resources.files('simscene.generation.templates').joinpath('guide_plate_v1.py').is_file() +assert resources.files('simscene.generation.templates').joinpath('usdcraft_sdk_guide_plate_v1.py').is_file() +from simscene.verification.articulated_asset_two_joint_pair import verify_pair +from simscene.catalog.providers.artvip import ArtVIPProvider assert metadata.version('rosclaw-simscene')=='0.2.0.dev2' assert resources.files('simscene').joinpath('layout_synthesis_worker.py').is_file() from simscene.preparation.glb_convert import predecoder_fingerprint @@ -75,13 +78,22 @@ async def check_independent_metadata(root,plugin): members=set(archive.namelist()) for name in ('simscene/catalog/data/sources.yaml','simscene/recipes/data/recipes.json', 'simscene/preparation/data/package-lock.json','simscene/generation/templates/guide_plate_v1.py', - 'simscene/worker/isaac_run.py','simscene/preparation/worker.py', 'simscene/layout_synthesis_worker.py'): + 'simscene/worker/isaac_run.py','simscene/preparation/worker.py', 'simscene/layout_synthesis_worker.py', + 'simscene/generation/templates/usdcraft_sdk_guide_plate_v1.py', + 'simscene/generation/usdcraft_backend_worker.py','simscene/catalog/providers/artvip.py', + 'simscene/preparation/articulation_v2.py','simscene/worker/mechanism_v2.py', + 'simscene/verification/articulated_asset_two_joint_pair.py'): self.assertIn(name,members) self.assertFalse(any('__pycache__' in name or 'node_modules/' in name or name.endswith('.pyc') for name in members)) for kind in ('portable','claude','deepseek'): stage=root/kind;stage.mkdir() plugin=output/kind/'simscene' self.assertTrue((plugin/'README.md').is_file()) + for sample in ('examples/artvip_door/assets.lock.json', + 'examples/usdcraft_two_drawer/case.json', + 'examples/usdcraft_sdk_guide/assets.lock.json', + 'examples/usdcraft_sdk_guide/check_pair.py'): + self.assertEqual((plugin/sample).read_bytes(),(ROOT/sample).read_bytes(),sample) for reference in (plugin/'skills').rglob('*.md'): for link in re.findall(r'\]\(([^\s)]+)\)',reference.read_text()): target=link.split('#')[0] @@ -117,4 +129,9 @@ async def check_independent_metadata(root,plugin): self.assertTrue(result['codex_mcp_registered']) self.assertFalse(result['native_plugin_installed']) self.assertTrue((project/'.agents/skills/build-scene/SKILL.md').is_file()) + skill_root=project/'.agents/skills/build-scene' + installed_root=Path((skill_root/'.simscene-plugin-root').read_text().strip()) + self.assertEqual(installed_root,destination) + self.assertTrue((installed_root/'examples/usdcraft_two_drawer/case.json').is_file()) + self.assertTrue((installed_root/'examples/usdcraft_sdk_guide/check_pair.py').is_file()) asyncio.run(check(project,destination)) diff --git a/tests/test_articulated_asset_two_joint.py b/tests/test_articulated_asset_two_joint.py new file mode 100644 index 0000000..ad52774 --- /dev/null +++ b/tests/test_articulated_asset_two_joint.py @@ -0,0 +1,473 @@ +"""Two-joint checker consumes measured, path-keyed data, never command echoes.""" +import copy +import importlib.util +import json +import math +import sys +import unittest +from pathlib import Path +import tempfile +from unittest.mock import patch + +BASE = '/World/cabinet/Asset/Native/Links/base' +FIRST = '/World/cabinet/Asset/Native/Links/first' +SECOND = '/World/cabinet/Asset/Native/Links/second' +JOINT_A = '/World/cabinet/Asset/Native/Joints/slide' +JOINT_B = '/World/cabinet/Asset/Native/Joints/hinge' +SOURCE_REF = {'source_id': 'usdcraft', 'asset_id': 'fixture', 'revision': 'a' * 40, 'variant_id': None} + + +def binding_joint(path, child, kind, axis, limits, unit): + return {'joint_path': path, 'parent_body': BASE, 'child_body': child, + 'type': kind, 'axis': axis, 'position_unit': unit, 'limits': limits, + 'local_pos0_m': [0., 0., 0.], 'local_pos1_m': [0., 0., 0.], + 'local_rot0_wxyz': [1., 0., 0., 0.], 'local_rot1_wxyz': [1., 0., 0., 0.], + 'passive': True, 'drive': None} + + +def fixture(*, first=None, second=None): + first = first or [0., .1, .2, .3, .3, .3, .3, .3, .3] + second = second or [0., 0., 0., 0., 0., .1, .2, .3, .3] + joints = { + 'slide': binding_joint(JOINT_A, FIRST, 'prismatic', 'X', [-1., 1.], 'm'), + 'hinge': binding_joint(JOINT_B, SECOND, 'revolute', 'Z', [-1., 1.], 'rad'), + } + binding = {'profile_id': 'articulated_prop_v2', 'root_body': BASE, + 'motion_bodies': [BASE, FIRST, SECOND], 'joints': joints} + expectations = {} + for name, joint in joints.items(): + expectations[name] = {key: copy.deepcopy(joint[key]) for key in + ('joint_path', 'parent_body', 'child_body', 'type', 'axis', 'limits', 'position_unit')} + expectations[name].update(initial_position=0., initial_tolerance=.001, coordinate_tolerance=.00001, + velocity_tolerance=.00001, anchor_tolerance_m=.00001, angular_tolerance_rad=.01) + phases = [ + {'joint_id': 'slide', 'command_step': 0, 'by_step': 3, 'target_position': .3, 'target_tolerance': .005, + 'min_travel': .2, 'other_target_position': 0., 'other_target_tolerance': .01, 'max_other_drift': .005, + 'stiffness': 30., 'damping': 4., 'max_effort': 50., 'hold_command': None}, + {'joint_id': 'hinge', 'command_step': 4, 'by_step': 7, 'target_position': .3, 'target_tolerance': .005, + 'min_travel': .2, 'other_target_position': .3, 'other_target_tolerance': .02, 'max_other_drift': .005, + 'stiffness': 30., 'damping': 4., 'max_effort': 50., 'hold_command': None}, + ] + case = {'schema': 'simscene.articulated_asset_two_joint.v1', 'schema_version': 1, 'mode': 'driven', + 'physics_dt_s': .1, 'objects': {'cabinet': {'prepared_manifest_sha256': 'b' * 64, + 'source_ref': copy.deepcopy(SOURCE_REF), 'joints': expectations, 'phases': phases}}} + events = [ + {'command_index': 0, 'joint_id': 'slide', 'joint_path': JOINT_A, 'physics_step': 0, + 'trigger': {'type': 'at_step', 'physics_step': 0}, 'target_position': .3, 'position_unit': 'm', + 'cause': 'declared_at_step_schedule', 'drive_readback': {'type': 'force', 'target_position': .3, + 'target_velocity': 0., 'stiffness': 30., 'damping': 4., 'max_force': 50., + 'instance': 'linear', 'position_unit': 'm', 'scope': 'loaded_USD_drive_attributes'}}, + {'command_index': 1, 'joint_id': 'hinge', 'joint_path': JOINT_B, 'physics_step': 4, + 'trigger': {'type': 'at_step', 'physics_step': 4}, 'target_position': .3, 'position_unit': 'rad', + 'cause': 'declared_at_step_schedule', 'drive_readback': {'type': 'force', 'target_position': math.degrees(.3), + 'target_velocity': 0., 'stiffness': 30. * math.pi / 180., 'damping': 4. * math.pi / 180., 'max_force': 50., + 'instance': 'angular', 'position_unit': 'degree', 'scope': 'loaded_USD_drive_attributes'}}, + ] + frames = [] + for step, (a, b) in enumerate(zip(first, second)): + va = (a - first[step - 1]) / .1 if step else 0. + vb = (b - second[step - 1]) / .1 if step else 0. + positions = {BASE: [0., 0., 0.], FIRST: [a, 0., 0.], SECOND: [0., 0., 0.]} + orientations = {BASE: [1., 0., 0., 0.], FIRST: [1., 0., 0., 0.], + SECOND: [math.cos(b / 2), 0., 0., math.sin(b / 2)]} + linear = {BASE: [0., 0., 0.], FIRST: [va, 0., 0.], + SECOND: [-vb * math.sin(b), vb * math.cos(b), 0.]} + angular = {BASE: [0., 0., 0.], FIRST: [0., 0., 0.], SECOND: [0., 0., vb]} + measurements = {} + for name, value, velocity in (('slide', a, va), ('hinge', b, vb)): + joint = joints[name] + measurements[name] = {'position': value, 'velocity': velocity if step else None, + 'position_unit': joint['position_unit'], 'velocity_unit': joint['position_unit'] + '/s', + 'physics_step': step, 'anchor_error_m': 0., 'locked_rotation_error_rad': 0., + 'parent_body': BASE, 'child_body': joint['child_body'], + 'joint_path': joint['joint_path'], 'measurement_source': 'same_sample_PhysX_body_poses_joint_frame_reconstruction', + 'native_position': value, 'native_velocity': velocity, + 'native_measurement_source': 'PhysX_articulation_tensor_DOF_readback_SI'} + frames.append({'physics_steps': step, 'simulation_time_s': step * .1, + 'absolute_physics_step': 10 + step, 'absolute_simulation_time_s': 1. + step * .1, + 'positions': positions, 'orientations_wxyz': orientations, 'linear_velocities_m_s': linear, + 'angular_velocities_rad_s': angular, 'native_joint_positions': {JOINT_A: a, JOINT_B: b}, + 'native_joint_velocities': {JOINT_A: va, JOINT_B: vb}, + 'native_joint_measurement_source': 'PhysX_articulation_tensor_DOF_readback_SI', + 'mechanisms': {'cabinet': {'physics_step': step, 'joints': measurements, + # Step 4 is observed before the step-4 command runs; that + # command first appears after stepping into frame 5. + 'command_events': copy.deepcopy(events[:1 if step <= 4 else 2])}}}) + props = {path: {'center_of_mass_local_m': com, 'observed_at_physics_step': 0, + 'source': 'PhysX native articulation/rigid tensor cooked mass properties'} + for path, com in ((BASE, [0., 1., 0.]), (FIRST, [0., 2., 0.]), (SECOND, [1., 0., 0.]))} + run = {'initial_observation': frames[0], 'samples': frames[1:], 'body_bindings': {'cabinet': binding}, + 'actual_physics_steps': 8, 'requested_physics_steps': 8, 'observation_interval_steps': 1, + 'simulation_time_s': .8, 'run_zero_absolute_physics_step': 10, 'run_zero_absolute_simulation_time_s': 1., + 'partial': False, 'samples_truncated': False, 'followers': {}, 'task_status': 'unverified', + 'physics_settings': {'before_warmup': {'authored_time_steps_per_second': 10., 'requested_device': 'cpu', + 'enable_gpu_dynamics': False, 'request_matches_observation': True}, + 'after_run': {'authored_time_steps_per_second': 10., 'requested_device': 'cpu', + 'enable_gpu_dynamics': False, 'request_matches_observation': True}}, + 'mechanism_configuration': {'mass_properties_by_prim_path': props}} + return run, case + + +def frozen_run(directory): + """Build real input/evidence locks around a small local prepared closure.""" + from simscene.cache import _sha256 + from simscene.evidence_integrity import seal + root = Path(directory) + package = root / 'prepared' + (package / 'source').mkdir(parents=True) + main = package / 'main.usda' + main.write_text('#usda 1.0\n') + acquired = package / 'source' / 'acquired.json' + acquired.write_text(json.dumps({'source_ref': SOURCE_REF})) + run, case = fixture() + binding = run['body_bindings']['cabinet'] + body_map = {name: {'relative_prim_path': 'Native/Links/' + name, 'role': 'rigid', + 'visual_relative_prim_paths': [], 'collider_relative_prim_paths': []} + for name in ('base', 'first', 'second')} + joint_map = {} + for name, child in (('slide', 'first'), ('hinge', 'second')): + joint = copy.deepcopy(binding['joints'][name]) + joint.pop('joint_path'); joint.pop('parent_body'); joint.pop('child_body') + joint.update(relative_prim_path='Native/Joints/' + name, parent_body_id='base', child_body_id=child) + joint_map[name] = joint + binding['joints'][name].update(relative_prim_path=joint['relative_prim_path'], + parent_body_id='base', child_body_id=child) + report = {'schema': 'simscene.articulation_inspection.v2', 'schema_version': 2, + 'body_map': body_map, 'joint_map': joint_map, 'root_body_id': 'base'} + manifest = {'schema': 'simscene.prepared_asset.v1', 'schema_version': 1, + 'profile_id': 'articulated_prop_v2', 'main': 'main.usda', 'default_prim': '/Asset', + 'body_map': body_map, 'joint_map': joint_map, 'articulation_report': report, + 'parameters': {'source_physics_policy': 'preserve_valid'}, 'source_ref': SOURCE_REF, + 'files': [{'path': path.relative_to(package).as_posix(), 'size': path.stat().st_size, + 'sha256': _sha256(path)} for path in (main, acquired)]} + manifest_path = package / 'manifest.json' + manifest_path.write_text(json.dumps(manifest)) + manifest_hash = _sha256(manifest_path) + case['objects']['cabinet']['prepared_manifest_sha256'] = manifest_hash + commands = [{'joint_id': phase['joint_id'], 'trigger': {'type': 'at_step', 'physics_step': phase['command_step']}, + 'target_position': phase['target_position'], 'position_unit': case['objects']['cabinet']['joints'][phase['joint_id']]['position_unit'], + 'stiffness': phase['stiffness'], 'damping': phase['damping'], 'max_effort': phase['max_effort']} + for phase in case['objects']['cabinet']['phases']] + spec = {'objects': {'cabinet': {'kind': 'asset', 'dynamic': True, 'asset_path': str(main), + 'asset_binding': {'manifest_path': str(manifest_path), 'manifest_sha256': manifest_hash}, + 'mechanism': {'commands': commands}}}} + asset_lock = {'cabinet': {'kind': 'external', 'path': str(main), 'files': [ + {'path': str(path), 'size': path.stat().st_size, 'sha256': _sha256(path)} + for path in (main, acquired, manifest_path)]}} + for name, value in (('spec.json', spec), ('asset-lock.json', asset_lock), ('runtime-lock.json', {}), + ('result.json', run), ('acceptance-case.json', case)): + (root / name).write_text(json.dumps(value)) + (root / 'scene.usda').write_text('#usda 1.0\n') + launcher = str(Path(sys.executable).resolve()) + lock = {'spec_sha256': _sha256(root / 'spec.json'), 'stage_sha256': _sha256(root / 'scene.usda'), + 'asset_lock_sha256': _sha256(root / 'asset-lock.json'), 'runtime_lock_sha256': _sha256(root / 'runtime-lock.json'), + 'acceptance_case_file': 'acceptance-case.json', 'acceptance_case_sha256': _sha256(root / 'acceptance-case.json'), + 'runtime_python': launcher, 'runtime_python_sha256': _sha256(Path(launcher)), 'body_bindings': run['body_bindings'], + 'physics_device': 'cpu', 'physics_dt_s': .1, 'requested_physics_steps': 8} + (root / 'run-lock.json').write_text(json.dumps(lock)) + seal(root) + return root, run, case + + +class TwoJointAcceptanceTests(unittest.TestCase): + def checker(self): + spec = importlib.util.find_spec('simscene.verification.articulated_asset_two_joint') + self.assertIsNotNone(spec, 'two-joint acceptance checker is not implemented') + from simscene.verification import articulated_asset_two_joint + return articulated_asset_two_joint + + def test_two_phases_require_observed_travel_and_each_other_axis_holds(self): + run, case = fixture() + report = self.checker().evaluate(run, case) + self.assertTrue(report['passed'], report) + self.assertEqual(report['negative_control']['status'], 'not_evaluated') + phases = report['objects']['cabinet']['phases'] + self.assertEqual(len(phases), 2) + self.assertAlmostEqual(phases[0]['observed_travel'], .3) + self.assertAlmostEqual(phases[1]['observed_travel'], .3) + self.assertAlmostEqual(phases[0]['max_other_drift'], 0.) + self.assertAlmostEqual(phases[1]['max_other_drift'], 0.) + + def test_explicit_same_step_hold_command_is_frozen_and_does_not_supply_motion(self): + run, case = fixture() + phases = case['objects']['cabinet']['phases'] + phases[0]['hold_command'] = {'stiffness': 15., 'damping': 2., 'max_effort': 40.} + phases[1]['hold_command'] = None + for frame in [run['initial_observation'], *run['samples']]: + events = frame['mechanisms']['cabinet']['command_events'] + hold = {'command_index': 1, 'joint_id': 'hinge', 'joint_path': JOINT_B, 'physics_step': 0, + 'trigger': {'type': 'at_step', 'physics_step': 0}, 'target_position': 0., 'position_unit': 'rad', + 'cause': 'declared_at_step_schedule', 'drive_readback': {'type': 'force', 'target_position': 0., + 'target_velocity': 0., 'stiffness': 15. * math.pi / 180., 'damping': 2. * math.pi / 180., + 'max_force': 40., 'instance': 'angular', 'position_unit': 'degree', 'scope': 'loaded_USD_drive_attributes'}} + if len(events) == 2: + events[1]['command_index'] = 2 + events.insert(1, hold) + self.assertTrue(self.checker().evaluate(run, case)['passed']) + wrong = copy.deepcopy(run) + for frame in [wrong['initial_observation'], *wrong['samples']]: + frame['mechanisms']['cabinet']['command_events'][1]['joint_path'] = JOINT_A + self.assertFalse(self.checker().evaluate(wrong, case)['passed']) + wrong = copy.deepcopy(run) + for frame in [wrong['initial_observation'], *wrong['samples']]: + frame['mechanisms']['cabinet']['command_events'][1]['drive_readback']['stiffness'] = 0. + self.assertFalse(self.checker().evaluate(wrong, case)['passed']) + + def test_missing_native_q_or_velocity_and_missing_com_fail_closed(self): + for mutation in ('q', 'velocity', 'source', 'com'): + with self.subTest(mutation=mutation): + run, case = fixture() + frame = run['samples'][1] + if mutation == 'q': del frame['native_joint_positions'][JOINT_A] + elif mutation == 'velocity': del frame['native_joint_velocities'][JOINT_B] + elif mutation == 'source': frame['native_joint_measurement_source'] = 'command_echo' + else: del run['mechanism_configuration']['mass_properties_by_prim_path'][FIRST] + self.assertFalse(self.checker().evaluate(run, case)['passed']) + + def test_swapped_native_paths_and_wrong_command_path_fail(self): + run, case = fixture() + frame = run['samples'][1] + q = frame['native_joint_positions'] + q[JOINT_A], q[JOINT_B] = q[JOINT_B], q[JOINT_A] + self.assertFalse(self.checker().evaluate(run, case)['passed']) + run, case = fixture() + for frame in [run['initial_observation'], *run['samples']]: + frame['mechanisms']['cabinet']['command_events'][0]['joint_path'] = JOINT_B + self.assertFalse(self.checker().evaluate(run, case)['passed']) + + def test_unreached_driven_or_held_target_and_excess_drift_fail_independently(self): + run, case = fixture(second=[0., 0., 0., 0., 0., .04, .08, .12, .12]) + report = self.checker().evaluate(run, case) + self.assertFalse(report['passed']) + self.assertFalse(report['objects']['cabinet']['phases'][1]['checks']['target_reached']) + run, case = fixture() + case['objects']['cabinet']['phases'][0]['other_target_position'] = .1 + self.assertFalse(self.checker().evaluate(run, case)['objects']['cabinet']['phases'][0]['checks']['other_target_held']) + run, case = fixture(first=[0., .1, .2, .3, .3, .306, .312, .318, .318]) + report = self.checker().evaluate(run, case) + self.assertFalse(report['passed']) + self.assertTrue(report['objects']['cabinet']['phases'][1]['checks']['other_target_held']) + self.assertFalse(report['objects']['cabinet']['phases'][1]['checks']['other_drift_within_limit']) + + def test_synchronous_motion_cannot_be_accepted_by_large_holding_thresholds(self): + positions = [0., .1, .2, .3, .3, .4, .5, .6, .6] + run, case = fixture(first=positions, second=positions) + phases = case['objects']['cabinet']['phases'] + phases[1]['target_position'] = .6 + for phase in phases: + phase['other_target_tolerance'] = .5 + phase['max_other_drift'] = .5 + for frame in run['samples']: + events = frame['mechanisms']['cabinet']['command_events'] + if len(events) == 2: + events[1]['target_position'] = .6 + events[1]['drive_readback']['target_position'] = math.degrees(.6) + with self.assertRaisesRegex(ValueError, 'relative to'): + self.checker().evaluate(run, case) + + def test_weak_target_or_hold_tolerances_cannot_swallow_required_motion(self): + for key in ('target_tolerance', 'other_target_tolerance', 'max_other_drift'): + with self.subTest(tolerance=key): + run, case = fixture() + case['objects']['cabinet']['phases'][0][key] = .04 + with self.assertRaisesRegex(ValueError, 'relative to'): + self.checker().validate_case(case) + + def test_large_measurement_tolerances_cannot_hide_bad_native_or_frame_data(self): + for mutation in ('coordinate', 'velocity', 'anchor', 'initial', 'angular'): + with self.subTest(mutation=mutation): + run, case = fixture() + expected = case['objects']['cabinet']['joints']['slide' if mutation != 'angular' else 'hinge'] + frame = run['samples'][-1] + record = frame['mechanisms']['cabinet']['joints']['slide'] + if mutation == 'coordinate': + expected['coordinate_tolerance'] = 1000. + frame['native_joint_positions'][JOINT_A] = 10. + record['native_position'] = 10. + elif mutation == 'velocity': + expected['velocity_tolerance'] = 1000. + frame['native_joint_velocities'][JOINT_A] = 500. + record['native_velocity'] = 500. + elif mutation == 'anchor': + expected['anchor_tolerance_m'] = 1000. + frame['positions'][FIRST][1] = 1. + record['anchor_error_m'] = 1. + elif mutation == 'initial': + expected['initial_tolerance'] = 1000. + else: + expected['angular_tolerance_rad'] = .05 + with self.assertRaises(ValueError): + self.checker().evaluate(run, case) + + def test_missing_step_and_command_echo_without_motion_are_rejected(self): + run, case = fixture() + del run['samples'][2] + self.assertFalse(self.checker().evaluate(run, case)['passed']) + run, case = fixture(first=[0.] * 9, second=[0.] * 9) + report = self.checker().evaluate(run, case) + self.assertFalse(report['passed']) + self.assertFalse(report['objects']['cabinet']['phases'][0]['checks']['target_reached']) + + def test_default_device_allows_unknown_matching_flag_but_dt_remains_verified(self): + run, case = fixture() + for settings in run['physics_settings'].values(): + settings.update(requested_device='default', enable_gpu_dynamics=None, request_matches_observation=None) + self.assertTrue(self.checker().evaluate(run, case)['passed']) + run['physics_settings']['after_run']['authored_time_steps_per_second'] = 20. + self.assertFalse(self.checker().evaluate(run, case)['passed']) + + def test_explicit_device_case_requires_matching_observed_physics_configuration(self): + run, case = fixture() + case['physics_device'] = 'cpu' + self.assertTrue(self.checker().evaluate(run, case)['passed']) + run['physics_settings']['after_run']['enable_gpu_dynamics'] = True + self.assertFalse(self.checker().evaluate(run, case)['passed']) + + def test_incomplete_status_and_boolean_step_values_are_rejected(self): + for mutation in ('missing_status', 'missing_followers', 'incomplete_marker', 'boolean_event_step', 'boolean_record_step'): + with self.subTest(mutation=mutation): + run, case = fixture() + if mutation == 'missing_status': del run['task_status'] + elif mutation == 'missing_followers': del run['followers'] + elif mutation == 'incomplete_marker': run['evidence_incomplete'] = 'yes' + elif mutation == 'boolean_record_step': + run['initial_observation']['mechanisms']['cabinet']['joints']['slide']['physics_step'] = False + else: + for frame in [run['initial_observation'], *run['samples']]: + event = frame['mechanisms']['cabinet']['command_events'][0] + event['physics_step'] = False + event['trigger']['physics_step'] = False + self.assertFalse(self.checker().evaluate(run, case)['passed']) + + def test_same_sample_velocity_uses_rotated_center_of_mass_and_relative_frame(self): + run, case = fixture() + frame = run['samples'][0] # slide=0.1, native slide velocity=1 m/s + frame['angular_velocities_rad_s'] = {BASE: [0., 0., 1.], FIRST: [0., 0., 1.], SECOND: [0., 0., 1.]} + frame['linear_velocities_m_s'] = {BASE: [-1., 0., 0.], FIRST: [-1., .1, 0.], SECOND: [0., 1., 0.]} + self.assertTrue(self.checker().evaluate(run, case)['passed']) + frame['linear_velocities_m_s'][FIRST][0] += .1 + self.assertFalse(self.checker().evaluate(run, case)['passed']) + + def test_slider_rotation_and_hinge_swing_cannot_be_hidden_by_valid_scalar_position(self): + for joint, path in (('slide', FIRST), ('hinge', SECOND)): + with self.subTest(joint=joint): + run, case = fixture() + frame = run['initial_observation'] + # A 90 degree relative rotation around X is forbidden for a + # slider and is perpendicular swing for this Z hinge. + frame['orientations_wxyz'][path] = [math.sqrt(.5), math.sqrt(.5), 0., 0.] + frame['mechanisms']['cabinet']['joints'][joint]['locked_rotation_error_rad'] = math.pi / 2 + self.assertFalse(self.checker().evaluate(run, case)['passed']) + + def test_joint_case_requires_two_distinct_paths_and_unambiguous_disjoint_phases(self): + run, case = fixture() + second = case['objects']['cabinet']['joints']['hinge'] + second['joint_path'] = JOINT_A + with self.assertRaises(ValueError): self.checker().validate_case(case) + run, case = fixture() + case['objects']['cabinet']['phases'][1]['joint_id'] = 'slide' + with self.assertRaises(ValueError): self.checker().validate_case(case) + run, case = fixture() + case['objects']['cabinet']['phases'][1]['command_step'] = 2 + with self.assertRaises(ValueError): self.checker().validate_case(case) + run, case = fixture() + case['objects']['cabinet']['joints']['hinge']['child_body'] = '/World/other/Asset/Native/Links/second' + with self.assertRaises(ValueError): self.checker().validate_case(case) + + def test_verify_run_pins_case_manifest_input_and_evidence_contents(self): + checker = self.checker() + with tempfile.TemporaryDirectory() as directory: + root, _, _ = frozen_run(directory) + self.assertTrue(checker.verify_run(root)['passed']) + result = root / 'result.json' + result.write_text(result.read_text() + ' ') + report = checker.verify_run(root) + self.assertFalse(report['passed']) + self.assertFalse(report['evidence_integrity']['passed']) + with tempfile.TemporaryDirectory() as directory: + root, _, _ = frozen_run(directory) + spec = root / 'spec.json' + spec.write_text(spec.read_text() + ' ') + report = checker.verify_run(root) + self.assertFalse(report['passed']) + self.assertFalse(report['input_integrity']['passed']) + with tempfile.TemporaryDirectory() as directory: + root, _, _ = frozen_run(directory) + manifest = root / 'prepared' / 'manifest.json' + manifest.write_text(manifest.read_text() + ' ') + report = checker.verify_run(root) + self.assertFalse(report['passed']) + self.assertFalse(report['checks']['prepared_selection_pinned']) + with tempfile.TemporaryDirectory() as directory: + root, _, _ = frozen_run(directory) + case = root / 'acceptance-case.json' + case.write_text(case.read_text() + ' ') + with self.assertRaisesRegex(ValueError, 'frozen case'): + checker.verify_run(root) + + def test_verify_run_rejects_case_commands_not_present_in_the_frozen_spec(self): + from simscene.cache import _sha256 + with tempfile.TemporaryDirectory() as directory: + root, _, _ = frozen_run(directory) + path = root / 'spec.json' + spec = json.loads(path.read_text()) + spec['objects']['cabinet']['mechanism']['commands'][0]['target_position'] = .2 + path.write_text(json.dumps(spec)) + lock_path = root / 'run-lock.json' + lock = json.loads(lock_path.read_text()) + lock['spec_sha256'] = _sha256(path) + lock_path.write_text(json.dumps(lock)) + report = self.checker().verify_run(root) + self.assertTrue(report['input_integrity']['passed']) + self.assertFalse(report['passed']) + self.assertFalse(report['checks']['commands_pinned_to_spec']) + + def test_verify_run_rejects_run_lock_device_or_timestep_mismatch(self): + for field, value in (('physics_device', 'gpu'), ('physics_dt_s', .2), ('requested_physics_steps', 9)): + with self.subTest(field=field), tempfile.TemporaryDirectory() as directory: + root, _, _ = frozen_run(directory) + lock_path = root / 'run-lock.json' + lock = json.loads(lock_path.read_text()) + lock[field] = value + lock_path.write_text(json.dumps(lock)) + report = self.checker().verify_run(root) + self.assertTrue(report['input_integrity']['passed']) + self.assertFalse(report['passed']) + + def test_verify_run_rejects_binding_not_in_the_selected_manifest_even_when_all_hashes_match(self): + from simscene.cache import _sha256 + with tempfile.TemporaryDirectory() as directory: + root, _, _ = frozen_run(directory) + manifest_path = root / 'prepared' / 'manifest.json' + manifest = json.loads(manifest_path.read_text()) + manifest['joint_map']['slide']['local_pos0_m'] = [.1, 0., 0.] + manifest['articulation_report']['joint_map']['slide']['local_pos0_m'] = [.1, 0., 0.] + manifest_path.write_text(json.dumps(manifest)) + digest = _sha256(manifest_path) + case_path = root / 'acceptance-case.json' + case = json.loads(case_path.read_text()) + case['objects']['cabinet']['prepared_manifest_sha256'] = digest + case_path.write_text(json.dumps(case)) + spec_path = root / 'spec.json' + spec = json.loads(spec_path.read_text()) + spec['objects']['cabinet']['asset_binding']['manifest_sha256'] = digest + spec_path.write_text(json.dumps(spec)) + assets_path = root / 'asset-lock.json' + assets = json.loads(assets_path.read_text()) + entry = next(item for item in assets['cabinet']['files'] if item['path'] == str(manifest_path)) + entry.update(size=manifest_path.stat().st_size, sha256=digest) + assets_path.write_text(json.dumps(assets)) + lock_path = root / 'run-lock.json' + lock = json.loads(lock_path.read_text()) + lock.update(spec_sha256=_sha256(spec_path), asset_lock_sha256=_sha256(assets_path), + acceptance_case_sha256=_sha256(case_path)) + lock_path.write_text(json.dumps(lock)) + report = self.checker().verify_run(root) + self.assertTrue(report['input_integrity']['passed']) + self.assertTrue(report['evidence_integrity']['passed']) + self.assertFalse(report['checks']['prepared_selection_pinned']) + self.assertFalse(report['passed']) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_articulated_asset_two_joint_pair.py b/tests/test_articulated_asset_two_joint_pair.py new file mode 100644 index 0000000..85dced1 --- /dev/null +++ b/tests/test_articulated_asset_two_joint_pair.py @@ -0,0 +1,179 @@ +"""Paired acceptance requires the isolated missing second command, not any failure.""" +import copy +import json +import math + +import pytest + +from simscene.cache import _sha256 +from simscene.evidence_integrity import seal +from simscene.verification.articulated_asset_two_joint import verify_run +from test_articulated_asset_two_joint import JOINT_B, fixture, frozen_run + + +def write_json(path, value): + path.write_text(json.dumps(value), encoding='utf8') + + +def update_run(root, *, spec=None, result=None, case=None): + """Reseal actual fixture inputs and results, as a new frozen run would.""" + lock_path = root / 'run-lock.json' + lock = json.loads(lock_path.read_text()) + if spec is not None: + write_json(root / 'spec.json', spec) + lock['spec_sha256'] = _sha256(root / 'spec.json') + if case is not None: + write_json(root / 'acceptance-case.json', case) + lock['acceptance_case_sha256'] = _sha256(root / 'acceptance-case.json') + if result is not None: + write_json(root / 'result.json', result) + lock['body_bindings'] = result['body_bindings'] + write_json(lock_path, lock) + seal(root) + + +def paired_fixture(tmp_path): + positive = tmp_path / 'positive' + control = tmp_path / 'control' + positive.mkdir(); control.mkdir() + _, positive_run, case = frozen_run(positive) + _, control_run, control_case = frozen_run(control) + assert case == control_case + + # Keep an explicit first-phase hold on the second axis in both trials. + hold = {'stiffness': 15., 'damping': 2., 'max_effort': 40.} + case['objects']['cabinet']['phases'][0]['hold_command'] = hold + hold_command = {'joint_id': 'hinge', 'trigger': {'type': 'at_step', 'physics_step': 0}, + 'target_position': 0., 'position_unit': 'rad', **hold} + hold_event = {'command_index': 1, 'joint_id': 'hinge', 'joint_path': JOINT_B, + 'physics_step': 0, 'trigger': {'type': 'at_step', 'physics_step': 0}, + 'target_position': 0., 'position_unit': 'rad', 'cause': 'declared_at_step_schedule', + 'drive_readback': {'type': 'force', 'target_position': 0., 'target_velocity': 0., + 'stiffness': 15. * math.pi / 180., 'damping': 2. * math.pi / 180., + 'max_force': 40., 'instance': 'angular', 'position_unit': 'degree', + 'scope': 'loaded_USD_drive_attributes'}} + stationary, _ = fixture(second=[0.] * 9) + control_run['initial_observation'] = stationary['initial_observation'] + control_run['samples'] = stationary['samples'] + for run, is_control in ((positive_run, False), (control_run, True)): + run['seed'] = 42 + for frame in [run['initial_observation'], *run['samples']]: + events = frame['mechanisms']['cabinet']['command_events'] + if is_control: + del events[1:] + elif len(events) == 2: + events[1]['command_index'] = 2 + events.insert(1, copy.deepcopy(hold_event)) + + for root, run, is_control in ((positive, positive_run, False), (control, control_run, True)): + spec = json.loads((root / 'spec.json').read_text()) + spec.update(scene_id='control' if is_control else 'positive', revision=4 if is_control else 1, + requests={'different-id': 1} if is_control else {}) + commands = spec['objects']['cabinet']['mechanism']['commands'] + commands.insert(1, copy.deepcopy(hold_command)) + if is_control: + commands.pop(2) + lock = json.loads((root / 'run-lock.json').read_text()) + worker_root = root / 'runtime' / 'simscene' + hashes = {} + for name in ('worker/isaac_run.py', 'worker/initial_state.py', 'worker/mechanism.py', + 'worker/mechanism_v2.py'): + path = worker_root / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text('fixture worker: ' + name, encoding='utf8') + hashes[name] = _sha256(path) + lock.update(run_id=root.name, worker_code_sha256=hashes, runtime_version='fixture-version', seed=42) + write_json(root / 'run-lock.json', lock) + update_run(root, spec=spec, result=run, case=case) + assert verify_run(positive)['passed'] + return positive, control + + +def test_paired_control_passes_with_only_second_drive_removed_and_hold_preserved(tmp_path): + from simscene.verification.articulated_asset_two_joint_pair import verify_pair + positive, control = paired_fixture(tmp_path) + report = verify_pair(positive, control) + assert report['passed'], report + assert report['checks']['control_only_second_drive_removed'] + assert report['checks']['control_command_events_match'] + assert report['checks']['control_first_phase_passed'] + assert report['checks']['control_target_stationary'] + assert report['checks']['control_target_not_reached'] + assert report['checks']['control_travel_insufficient'] + + +@pytest.mark.parametrize('mutation', ['same_run', 'scene', 'wrong_command', 'missing_hold_event', + 'phase_two_motion', 'unsealed_evidence', 'unlocked_stage', 'case']) +def test_pair_rejects_unmatched_scene_commands_measurements_and_locks(tmp_path, mutation): + from simscene.verification.articulated_asset_two_joint_pair import verify_pair + positive, control = paired_fixture(tmp_path) + if mutation == 'same_run': + control = positive + elif mutation == 'scene': + spec = json.loads((control / 'spec.json').read_text()) + spec['objects']['cabinet']['position'] = [1., 0., 0.] + update_run(control, spec=spec) + elif mutation == 'wrong_command': + spec = json.loads((control / 'spec.json').read_text()) + spec['objects']['cabinet']['mechanism']['commands'].pop(0) + update_run(control, spec=spec) + elif mutation == 'missing_hold_event': + result = json.loads((control / 'result.json').read_text()) + for frame in [result['initial_observation'], *result['samples']]: + frame['mechanisms']['cabinet']['command_events'].pop(1) + update_run(control, result=result) + elif mutation == 'phase_two_motion': + result = json.loads((control / 'result.json').read_text()) + moving, _ = fixture(second=[0., 0., 0., 0., 0., .03, .03, .03, .03]) + for old, new in zip([result['initial_observation'], *result['samples']], + [moving['initial_observation'], *moving['samples']]): + for key in ('positions', 'orientations_wxyz', 'linear_velocities_m_s', 'angular_velocities_rad_s', + 'native_joint_positions', 'native_joint_velocities'): + old[key] = new[key] + old['mechanisms']['cabinet']['joints'] = new['mechanisms']['cabinet']['joints'] + update_run(control, result=result) + elif mutation == 'unsealed_evidence': + path = control / 'result.json' + path.write_text(path.read_text() + ' ') + elif mutation == 'unlocked_stage': + (control / 'scene.usda').write_text('#usda 1.0\n# changed\n') + else: + case = json.loads((control / 'acceptance-case.json').read_text()) + case['objects']['cabinet']['joints']['slide']['anchor_tolerance_m'] = .00002 + update_run(control, case=case) + assert verify_pair(positive, control)['passed'] is False + + +@pytest.mark.parametrize('key,value', [('seed', 43), ('runtime_version', 'other'), + ('physics_device', 'gpu'), ('requested_physics_steps', 7)]) +def test_pair_rejects_different_frozen_runtime_seed_device_or_step_count(tmp_path, key, value): + from simscene.verification.articulated_asset_two_joint_pair import verify_pair + positive, control = paired_fixture(tmp_path) + lock = json.loads((control / 'run-lock.json').read_text()) + lock[key] = value + write_json(control / 'run-lock.json', lock) + assert verify_pair(positive, control)['passed'] is False + + +def test_pair_rejects_different_but_independently_valid_worker_snapshot(tmp_path): + from simscene.verification.articulated_asset_two_joint_pair import verify_pair + positive, control = paired_fixture(tmp_path) + worker = control / 'runtime' / 'simscene' / 'worker' / 'mechanism_v2.py' + worker.write_text('different worker implementation') + lock = json.loads((control / 'run-lock.json').read_text()) + lock['worker_code_sha256']['worker/mechanism_v2.py'] = _sha256(worker) + write_json(control / 'run-lock.json', lock) + assert verify_pair(positive, control)['passed'] is False + + +def test_pair_rejects_boolean_result_seed_even_when_it_equals_locked_integer(tmp_path): + from simscene.verification.articulated_asset_two_joint_pair import verify_pair + positive, control = paired_fixture(tmp_path) + for root, actual in ((positive, True), (control, 1)): + lock = json.loads((root / 'run-lock.json').read_text()) + lock['seed'] = 1 + write_json(root / 'run-lock.json', lock) + result = json.loads((root / 'result.json').read_text()) + result['seed'] = actual + update_run(root, result=result) + assert verify_pair(positive, control)['passed'] is False diff --git a/tests/test_articulation_v2.py b/tests/test_articulation_v2.py new file mode 100644 index 0000000..f5c0884 --- /dev/null +++ b/tests/test_articulation_v2.py @@ -0,0 +1,323 @@ +import hashlib +import importlib.util +import math +import os +import unittest +from pathlib import Path +from unittest.mock import patch + +from simscene.preparation.profiles import PreparationError + +try: + from pxr import Gf, Sdf, Usd, UsdGeom, UsdPhysics +except ImportError: + Usd = None + + +@unittest.skipIf(Usd is None, 'requires OpenUSD') +class TwoDofInspectionTests(unittest.TestCase): + def stage(self, *, chain=False): + stage = Usd.Stage.CreateInMemory() + root = UsdGeom.Xform.Define(stage, '/Asset').GetPrim() + stage.SetDefaultPrim(root) + UsdGeom.SetStageMetersPerUnit(stage, 1.0) + UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z) + UsdGeom.Xform.Define(stage, '/Asset/Links') + UsdGeom.Xform.Define(stage, '/Asset/Joints') + for name, mass in (('Base', 10.0), ('First', 2.0), ('Second', 3.0)): + prim = UsdGeom.Xform.Define(stage, '/Asset/Links/' + name).GetPrim() + UsdPhysics.RigidBodyAPI.Apply(prim) + UsdPhysics.MassAPI.Apply(prim).CreateMassAttr(mass) + shape = UsdGeom.Cube.Define(stage, str(prim.GetPath()) + '/Collider') + UsdPhysics.CollisionAPI.Apply(shape.GetPrim()) + UsdPhysics.ArticulationRootAPI.Apply(stage.GetPrimAtPath('/Asset/Links/Base')) + slide = UsdPhysics.PrismaticJoint.Define(stage, '/Asset/Joints/Slide') + slide.CreateBody0Rel().SetTargets(['/Asset/Links/Base']) + slide.CreateBody1Rel().SetTargets(['/Asset/Links/First']) + slide.CreateAxisAttr('X') + slide.CreateLowerLimitAttr(0.0) + slide.CreateUpperLimitAttr(0.5) + slide.CreateLocalPos0Attr(Gf.Vec3f(0.1, 0.2, 0.3)) + drive = UsdPhysics.DriveAPI.Apply(slide.GetPrim(), 'linear') + drive.CreateTypeAttr('force') + drive.CreateStiffnessAttr(12.0) + drive.CreateDampingAttr(4.0) + drive.CreateMaxForceAttr(150.0) + drive.CreateTargetPositionAttr(0.25) + hinge = UsdPhysics.RevoluteJoint.Define(stage, '/Asset/Joints/Hinge') + hinge.CreateBody0Rel().SetTargets(['/Asset/Links/First' if chain else '/Asset/Links/Base']) + hinge.CreateBody1Rel().SetTargets(['/Asset/Links/Second']) + hinge.CreateAxisAttr('Z') + hinge.CreateLowerLimitAttr(-90.0) + hinge.CreateUpperLimitAttr(90.0) + hinge.CreateLocalRot0Attr(Gf.Quatf(0.70710678, Gf.Vec3f(0, 0, 0.70710678))) + return stage + + def inspect(self, stage): + spec = importlib.util.find_spec('simscene.preparation.articulation_v2') + self.assertIsNotNone(spec, 'two-DOF static inspector is not implemented') + from simscene.preparation.articulation_v2 import inspect_articulation_v2 + return inspect_articulation_v2(stage) + + def test_branch_records_actual_endpoints_limits_frames_and_raw_drive_without_mutating_stage(self): + stage = self.stage() + before = stage.GetRootLayer().ExportToString() + report = self.inspect(stage) + self.assertEqual(stage.GetRootLayer().ExportToString(), before) + self.assertEqual(report.get('schema'), 'simscene.articulation_inspection.v2') + self.assertEqual(report.get('schema_version'), 2) + self.assertEqual(len(report['body_map']), 3) + self.assertEqual(len(report['joint_map']), 2) + joints = {j['relative_prim_path']: j for j in report['joint_map'].values()} + self.assertEqual(set(joints), {'Joints/Slide', 'Joints/Hinge'}) + slide, hinge = joints['Joints/Slide'], joints['Joints/Hinge'] + for item, child in ((slide, 'Links/First'), (hinge, 'Links/Second')): + self.assertEqual(report['body_map'][item['parent_body_id']]['relative_prim_path'], 'Links/Base') + self.assertEqual(report['body_map'][item['child_body_id']]['relative_prim_path'], child) + self.assertEqual(slide['type'], 'prismatic') + self.assertIs(slide.get('joint_enabled'), True) + self.assertIs(slide.get('exclude_from_articulation'), False) + self.assertEqual(slide['limits'], [0.0, 0.5]) + self.assertEqual(slide['position_unit'], 'm') + self.assertAlmostEqual(slide['local_pos0_m'][1], 0.2, places=6) + self.assertEqual(slide['drive']['type'], 'force') + self.assertEqual(slide['drive']['stiffness'], 12.0) + self.assertEqual(slide['drive']['max_force'], 150.0) + self.assertEqual(slide['drive']['target_position'], 0.25) + self.assertEqual(hinge['type'], 'revolute') + self.assertEqual(hinge['position_unit'], 'rad') + self.assertAlmostEqual(hinge['limits'][0], -math.pi / 2) + self.assertAlmostEqual(hinge['limits'][1], math.pi / 2) + self.assertAlmostEqual(hinge['local_rot0_wxyz'][3], math.sqrt(0.5), places=6) + self.assertIsNone(hinge['drive']) + self.assertIn('not runtime', report['scope'].lower()) + + def test_series_graph_keeps_the_intermediate_body_as_parent(self): + report = self.inspect(self.stage(chain=True)) + hinge = next(j for j in report['joint_map'].values() if j['relative_prim_path'] == 'Joints/Hinge') + self.assertEqual(report['body_map'][hinge['parent_body_id']]['relative_prim_path'], 'Links/First') + self.assertEqual(report['body_map'][hinge['child_body_id']]['relative_prim_path'], 'Links/Second') + + def test_world_fixed_base_is_reported_but_is_not_a_dof(self): + stage = self.stage() + anchor = UsdPhysics.FixedJoint.Define(stage, '/Asset/Joints/Anchor') + anchor.CreateBody1Rel().SetTargets(['/Asset/Links/Base']) + report = self.inspect(stage) + self.assertEqual(len(report['joint_map']), 2) + self.assertEqual(report['fixed_joint_paths'], ['Joints/Anchor']) + + def test_world_fixed_joint_can_carry_the_articulation_root_api(self): + stage = self.stage() + anchor = UsdPhysics.FixedJoint.Define(stage, '/Asset/Joints/Anchor') + anchor.CreateBody1Rel().SetTargets(['/Asset/Links/Base']) + stage.GetPrimAtPath('/Asset/Links/Base').RemoveAPI(UsdPhysics.ArticulationRootAPI) + UsdPhysics.ArticulationRootAPI.Apply(anchor.GetPrim()) + report = self.inspect(stage) + self.assertEqual(report['articulation_root_paths'], ['Joints/Anchor']) + + def test_fixed_anchor_with_drive_is_not_misreported_as_undriven(self): + stage = self.stage() + anchor = UsdPhysics.FixedJoint.Define(stage, '/Asset/Joints/Anchor') + anchor.CreateBody1Rel().SetTargets(['/Asset/Links/Base']) + UsdPhysics.DriveAPI.Apply(anchor.GetPrim(), 'angular') + with self.assertRaises(PreparationError): + self.inspect(stage) + + def test_external_constraint_cannot_silently_change_the_selected_graph(self): + stage = self.stage() + UsdGeom.Xform.Define(stage, '/Outside') + foreign = UsdPhysics.FixedJoint.Define(stage, '/Outside/Anchor') + foreign.CreateBody1Rel().SetTargets(['/Asset/Links/Base']) + with self.assertRaises(PreparationError): + self.inspect(stage) + foreign.GetBody1Rel().SetTargets(['/Outside/Unrelated']) + self.assertEqual(len(self.inspect(stage)['joint_map']), 2) + + def test_rejects_graph_with_cycle_duplicate_child_world_endpoint_or_external_body(self): + for mutation in ('cycle', 'duplicate_child', 'world_endpoint', 'missing_body', 'self_edge', 'extra_joint'): + with self.subTest(mutation=mutation): + stage = self.stage() + hinge = UsdPhysics.Joint(stage.GetPrimAtPath('/Asset/Joints/Hinge')) + if mutation == 'cycle': + hinge.GetBody0Rel().SetTargets(['/Asset/Links/First']) + hinge.GetBody1Rel().SetTargets(['/Asset/Links/Base']) + elif mutation == 'duplicate_child': + hinge.GetBody1Rel().SetTargets(['/Asset/Links/First']) + elif mutation == 'world_endpoint': + hinge.GetBody0Rel().ClearTargets(True) + elif mutation == 'missing_body': + hinge.GetBody0Rel().SetTargets(['/Outside']) + elif mutation == 'self_edge': + hinge.GetBody1Rel().SetTargets(['/Asset/Links/Base']) + else: + extra = UsdPhysics.FixedJoint.Define(stage, '/Asset/Joints/Extra') + extra.CreateBody0Rel().SetTargets(['/Asset/Links/First']) + extra.CreateBody1Rel().SetTargets(['/Asset/Links/Second']) + with self.assertRaises(PreparationError): + self.inspect(stage) + + def test_rejects_world_fixed_joint_to_nonroot_or_multiple_world_anchors(self): + for multiple in (False, True): + with self.subTest(multiple=multiple): + stage = self.stage() + anchor = UsdPhysics.FixedJoint.Define(stage, '/Asset/Joints/Anchor') + anchor.CreateBody1Rel().SetTargets(['/Asset/Links/Base' if multiple else '/Asset/Links/First']) + if multiple: + extra = UsdPhysics.FixedJoint.Define(stage, '/Asset/Joints/Anchor2') + extra.CreateBody1Rel().SetTargets(['/Asset/Links/Base']) + with self.assertRaises(PreparationError): + self.inspect(stage) + + def test_rejects_disabled_excluded_invalid_limits_and_missing_axis(self): + for mutation in ('disabled', 'excluded', 'axis_missing', 'axis_invalid', 'limit_missing', + 'limit_infinite', 'limit_reversed', 'locked'): + with self.subTest(mutation=mutation): + stage = self.stage() + prim = stage.GetPrimAtPath('/Asset/Joints/Slide') + joint = UsdPhysics.PrismaticJoint(prim) + if mutation == 'disabled': + joint.CreateJointEnabledAttr(False) + elif mutation == 'excluded': + joint.CreateExcludeFromArticulationAttr(True) + elif mutation == 'axis_missing': + prim.RemoveProperty('physics:axis') + elif mutation == 'axis_invalid': + joint.GetAxisAttr().Set('Q') + elif mutation == 'limit_missing': + prim.RemoveProperty('physics:upperLimit') + elif mutation == 'limit_infinite': + joint.GetUpperLimitAttr().Set(float('inf')) + elif mutation == 'limit_reversed': + joint.GetUpperLimitAttr().Set(-1.0) + else: + joint.GetUpperLimitAttr().Set(0.0) + with self.assertRaises(PreparationError): + self.inspect(stage) + + def test_rejects_coupling_markers_and_unsupported_multi_axis_joints(self): + for mutation in ('mimic_schema', 'gear_attribute', 'coupling_relationship', 'spherical', 'extra_axis_drive'): + with self.subTest(mutation=mutation): + stage = self.stage() + prim = stage.GetPrimAtPath('/Asset/Joints/Slide') + if mutation == 'mimic_schema': + schemas = list(prim.GetMetadata('apiSchemas').GetAppliedItems()) + schemas.append('PhysxMimicJointAPI:linear') + prim.SetMetadata('apiSchemas', Sdf.TokenListOp.CreateExplicit(schemas)) + elif mutation == 'gear_attribute': + prim.CreateAttribute('physxGear:ratio', Sdf.ValueTypeNames.Float, custom=True).Set(2.0) + elif mutation == 'coupling_relationship': + prim.CreateRelationship('physxCoupling:joint', custom=True).SetTargets(['/Asset/Joints/Hinge']) + elif mutation == 'spherical': + UsdPhysics.SphericalJoint.Define(stage, '/Asset/Joints/Slide') + else: + UsdPhysics.DriveAPI.Apply(prim, 'angular') + with self.assertRaises(PreparationError): + self.inspect(stage) + + def test_rejects_missing_mass_disabled_body_missing_collision_or_unsafe_ancestors(self): + for mutation in ('mass_missing', 'mass_zero', 'body_disabled', 'kinematic', 'collider_missing', + 'collider_disabled', 'body_scaled', 'joint_ancestor_scaled', 'stage_units', 'nan_units'): + with self.subTest(mutation=mutation): + stage = self.stage() + prim = stage.GetPrimAtPath('/Asset/Links/First') + if mutation == 'mass_missing': + prim.RemoveProperty('physics:mass') + elif mutation == 'mass_zero': + UsdPhysics.MassAPI(prim).GetMassAttr().Set(0.0) + elif mutation == 'body_disabled': + UsdPhysics.RigidBodyAPI(prim).CreateRigidBodyEnabledAttr(False) + elif mutation == 'kinematic': + UsdPhysics.RigidBodyAPI(prim).CreateKinematicEnabledAttr(True) + elif mutation == 'collider_missing': + stage.RemovePrim('/Asset/Links/First/Collider') + elif mutation == 'collider_disabled': + UsdPhysics.CollisionAPI(stage.GetPrimAtPath('/Asset/Links/First/Collider')).CreateCollisionEnabledAttr(False) + elif mutation == 'body_scaled': + UsdGeom.Xformable(prim).AddScaleOp().Set(Gf.Vec3f(2, 1, 1)) + elif mutation == 'joint_ancestor_scaled': + UsdGeom.Xformable(stage.GetPrimAtPath('/Asset/Joints')).AddScaleOp().Set(Gf.Vec3f(2, 1, 1)) + elif mutation == 'stage_units': + UsdGeom.SetStageMetersPerUnit(stage, 0.01) + else: + UsdGeom.SetStageMetersPerUnit(stage, float('nan')) + with self.assertRaises(PreparationError): + self.inspect(stage) + + def test_rejects_non_normalized_joint_frame(self): + stage = self.stage() + joint = UsdPhysics.Joint(stage.GetPrimAtPath('/Asset/Joints/Slide')) + joint.CreateLocalRot0Attr(Gf.Quatf(2.0, Gf.Vec3f(0, 0, 0))) + with self.assertRaises(PreparationError): + self.inspect(stage) + + def test_mass_values_are_not_mislabeled_as_kg_with_noncanonical_stage_units(self): + for kilograms_per_unit in (0.1, 10.0, float('nan')): + with self.subTest(kilograms_per_unit=kilograms_per_unit): + stage = self.stage() + UsdPhysics.SetStageKilogramsPerUnit(stage, kilograms_per_unit) + # The legacy v1 canonical check did not validate mass units; + # v2 must retain this guard independently of that helper. + with patch('simscene.preparation.articulation_v2.canonical_stage'), self.assertRaises(PreparationError): + self.inspect(stage) + + def test_blocked_physics_defaults_are_rejected_as_unsupported(self): + for mutation in ('excluded', 'kinematic', 'joint_rotation', 'inertia', 'drive_target'): + with self.subTest(mutation=mutation): + stage = self.stage() + joint = UsdPhysics.Joint(stage.GetPrimAtPath('/Asset/Joints/Slide')) + link = stage.GetPrimAtPath('/Asset/Links/First') + if mutation == 'excluded': + joint.GetExcludeFromArticulationAttr().Block() + elif mutation == 'kinematic': + UsdPhysics.RigidBodyAPI(link).GetKinematicEnabledAttr().Block() + elif mutation == 'joint_rotation': + joint.GetLocalRot0Attr().Block() + elif mutation == 'inertia': + UsdPhysics.MassAPI(link).GetDiagonalInertiaAttr().Block() + else: + UsdPhysics.DriveAPI(joint.GetPrim(), 'linear').GetTargetPositionAttr().Block() + try: + self.inspect(stage) + except PreparationError: + pass + except Exception as error: + self.fail('unsupported blocked value raised wrong error: ' + repr(error)) + else: + self.fail('blocked native physics value was accepted') + + def test_rejects_animated_ancestor_outside_selected_root(self): + source = self.stage() + stage = Usd.Stage.CreateInMemory() + world = UsdGeom.Xform.Define(stage, '/World') + stage.SetDefaultPrim(world.GetPrim()) + UsdGeom.SetStageMetersPerUnit(stage, 1.0) + UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z) + world.AddTranslateOp().Set(Gf.Vec3d(2, 0, 0), Usd.TimeCode(1)) + selected = UsdGeom.Xform.Define(stage, '/World/Asset').GetPrim() + selected.GetReferences().AddReference(source.GetRootLayer().identifier) + from simscene.preparation.articulation_v2 import inspect_articulation_v2 + with self.assertRaises(PreparationError): + inspect_articulation_v2(stage, selected) + + def test_real_pinned_two_drawer_sample_remains_unchanged(self): + selected = os.environ.get('SIMSCENE_TWO_DOF_SAMPLE') + if not selected: + self.skipTest('set SIMSCENE_TWO_DOF_SAMPLE to the pinned USDCraft model.usdc') + path = Path(selected) + before = hashlib.sha256(path.read_bytes()).hexdigest() + self.assertEqual(before, 'e5070e0690c183629f0d24d2465d5ff0b53b88cd71b3682200650e05e009c7d0') + stage = Usd.Stage.Open(str(path)) + report = self.inspect(stage) + self.assertEqual(len(report['body_map']), 3) + joints = {j['relative_prim_path']: j for j in report['joint_map'].values()} + self.assertEqual(set(joints), {'Joints/slide_lower', 'Joints/slide_upper'}) + for joint in joints.values(): + self.assertEqual(joint['limits'], [0.0, 0.5]) + self.assertEqual(joint['drive']['type'], 'force') + self.assertEqual(joint['drive']['stiffness'], 0.0) + self.assertEqual(sum(len(b['collider_relative_prim_paths']) for b in report['body_map'].values()), 33) + self.assertEqual(hashlib.sha256(path.read_bytes()).hexdigest(), before) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_catalog_artvip.py b/tests/test_catalog_artvip.py new file mode 100644 index 0000000..2d00938 --- /dev/null +++ b/tests/test_catalog_artvip.py @@ -0,0 +1,225 @@ +"""Metadata-only ArtVIP admission and selected native package planning.""" +import copy +import json +from pathlib import Path +import tempfile +import unittest +from dataclasses import replace +from unittest.mock import patch + +from simscene.catalog import SearchRequest, load_registry +from simscene.catalog.providers.factory import make_provider +from simscene.catalog.network import MetadataError +from simscene.catalog.registry import Registry +from simscene.catalog.search import resolve_asset, search_assets +from simscene.catalog.store import CatalogStore +from simscene.acquisition.plans import make_plan +from simscene.acquisition.dispatch import acquire_selected +from test_asset_plans import config_fixture, runtime_fixture +from test_catalog_abo import metadata_server + +REVISION = 'd22f2095bc9db29fdd4b60f4a3c4f8177e1f5e9e' +FOLDER = 'Articulated_objects/small_furniture/door/door002' +ROOT = FOLDER + '/model_door.usd' +SHA = 'a5e596ad9be87033a4f9e02056d1b3baf125355ef0495a5c63b92d9004cec2be' +TREE_PATH = '/api/datasets/X-Humanoid/ArtVIP/tree/' + REVISION + '/' + FOLDER + '?recursive=false&expand=true&limit=100' + + +def tree_payload(): + # The official tree metadata describes the root file and directories only. + return json.dumps([ + {'type': 'directory', 'oid': 'a' * 40, 'size': 0, 'path': FOLDER + '/resource'}, + {'type': 'file', 'oid': 'b' * 40, 'size': 22536, 'path': ROOT, + 'lfs': {'oid': SHA, 'size': 22536, 'pointerSize': 130}}, + ]).encode() + + +class ArtVIPProviderTests(unittest.TestCase): + def test_artvip_is_available_only_by_explicit_source_selection(self): + registry = load_registry() + self.assertIn('artvip', {source.source_id for source in registry.select(('artvip',))}) + self.assertNotIn('artvip', {source.source_id for source in registry.select()}) + + def test_search_is_metadata_only_and_plan_freezes_root_without_claiming_closure(self): + payload = tree_payload() + with tempfile.TemporaryDirectory() as directory, metadata_server({TREE_PATH: {'payload': payload}}) as (url, trace): + source = load_registry().get('artvip') + config = config_fixture(directory) + provider = make_provider(CatalogStore(config['index_directory']), source, config) + provider.base_url = url + request = SearchRequest('door', source_ids=('artvip',), limit=10) + with patch('subprocess.Popen', side_effect=AssertionError('no runtime or downloader during metadata search')): + page = search_assets(request, providers={'artvip': provider}, index_directory=config['index_directory']) + warm = search_assets(request, providers={'artvip': provider}, index_directory=config['index_directory']) + self.assertEqual(page.status, 'ok') + self.assertEqual(len(page.items), 1) + self.assertEqual([item['path'] for item in trace], [TREE_PATH]) + self.assertEqual(page.budgets['metadata_bytes'], len(payload)) + self.assertEqual(page.budgets['model_bytes'], 0) + self.assertEqual(warm.budgets['metadata_bytes'], 0) + record = resolve_asset(page.items[0]['ref'], index_directory=config['index_directory']) + self.assertEqual(record.entry_path, ROOT) + self.assertEqual(record.ref.revision, REVISION) + self.assertIsNone(record.physics) + self.assertFalse(record.has_capability('declared_single_joint')) + self.assertEqual(record.license['basis'], 'pinned_ArtVIP_dataset_card') + self.assertEqual(record.license['card_sha256'], '3193c5d74ef7f1d4777fe0ff77d3f9f2f4c436969ea1802726da177897003f63') + self.assertTrue(record.license['card_url'].endswith('/' + REVISION + '/README.md')) + self.assertIsNone(record.availability['estimated_download_bytes']) + descriptor = record.availability['acquisition'] + self.assertEqual(descriptor['files'], [{'path': ROOT, 'size': 22536, 'sha256': SHA}]) + self.assertFalse(descriptor['files_complete']) + params = {'source_physics_policy': 'preserve_valid', 'proxy_tolerance_m': .002} + plan = make_plan(record.ref, 'articulated_prop_v1', params, record=record, + runtime=runtime_fixture(), config=config) + self.assertTrue(plan['ready_to_fetch']) + self.assertFalse(plan['files_complete']) + self.assertEqual(plan['content_identity'], 'pending_acquisition_content_lock') + with patch('simscene.acquisition.hf_package.acquire_hf_package', return_value={'routed': True}): + self.assertEqual(acquire_selected(plan, config=config), {'routed': True}) + + def test_invalid_tree_never_replaces_a_previous_good_index(self): + routes = {TREE_PATH: {'payload': tree_payload()}} + source = load_registry().get('artvip') + root = json.loads(tree_payload())[1] + cases = [ + [dict(root, lfs={'oid': 'not-a-sha', 'size': 22536})], + [dict(root, lfs={'oid': SHA, 'size': 1})], + [root, dict(root, path=FOLDER + '/another.usd')], + [dict(root, path=FOLDER + '/../outside.usd')], + [dict(root, path=FOLDER + '/resource/material.usd')], + ] + with tempfile.TemporaryDirectory() as directory, metadata_server(routes) as (url, _): + provider = make_provider(CatalogStore(directory), source, config_fixture(directory)) + provider.base_url = url + provider.refresh() + previous = provider.snapshot + record = provider.search(SearchRequest('door')).items[0] + for payload in cases: + routes[TREE_PATH]['payload'] = json.dumps(payload).encode() + with self.subTest(payload=payload), self.assertRaises(MetadataError): + provider.refresh() + self.assertEqual(provider.snapshot, previous) + self.assertEqual(provider.resolve(record.ref), record) + + def test_paginated_tree_is_rejected_instead_of_silently_indexing_a_partial_directory(self): + source = load_registry().get('artvip') + with tempfile.TemporaryDirectory() as directory: + provider = make_provider(CatalogStore(directory), source, config_fixture(directory)) + def truncated(_url, **kwargs): + kwargs['response_metadata']['link'] = '; rel="next"' + return tree_payload() + with patch('simscene.catalog.providers.artvip.fetch_metadata', side_effect=truncated): + with self.assertRaises(MetadataError): + provider.refresh() + self.assertEqual(provider.snapshot, 'index_not_refreshed') + + def test_changed_explicit_selection_cannot_resolve_stale_index(self): + source = load_registry().get('artvip') + with tempfile.TemporaryDirectory() as directory, metadata_server({TREE_PATH: {'payload': tree_payload()}}) as (url, _): + store = CatalogStore(directory) + old = make_provider(store, source, config_fixture(directory)) + old.base_url = url + record = old.search(SearchRequest('door')).items[0] + changed = replace(source, metadata_entries=(replace(source.metadata_entries[0], path=FOLDER + '_other'),)) + new = make_provider(store, changed, config_fixture(directory)) + self.assertEqual(new.snapshot, 'index_not_refreshed') + with self.assertRaisesRegex(ValueError, 'stale'): + new.resolve(record.ref) + + def test_removed_source_cannot_resolve_a_cached_artvip_record(self): + source = load_registry().get('artvip') + with tempfile.TemporaryDirectory() as directory, metadata_server({TREE_PATH: {'payload': tree_payload()}}) as (url, _): + provider = make_provider(CatalogStore(directory), source, config_fixture(directory)) + provider.base_url = url + record = provider.search(SearchRequest('door')).items[0] + with patch('simscene.catalog.search.load_registry', return_value=Registry(())): + with self.assertRaisesRegex(ValueError, 'configured registry'): + resolve_asset(record.ref, index_directory=directory) + + def test_frozen_plan_cannot_download_after_the_selected_registration_is_revoked(self): + source = load_registry().get('artvip') + selected = source.metadata_entries[0] + other = replace(selected, path=FOLDER + '_other') + original = replace(source, metadata_entries=(selected, other)) + with tempfile.TemporaryDirectory() as directory, metadata_server({TREE_PATH: {'payload': tree_payload()}}) as (url, _): + config = config_fixture(directory) + registry_path = Path(directory) / 'registry.json' + config['registry_path'] = str(registry_path) + registry_path.write_text(json.dumps(Registry((original,)).to_dict())) + provider = make_provider(CatalogStore(config['index_directory']), source, config) + provider.base_url = url + record = provider.search(SearchRequest('door')).items[0] + plan = make_plan(record.ref, 'articulated_prop_v1', + {'source_physics_policy': 'preserve_valid', 'proxy_tolerance_m': .002}, + record=record, runtime=runtime_fixture(), config=config) + self.assertTrue(plan['ready_to_fetch']) + with patch('simscene.acquisition.hf_package.acquire_hf_package', return_value={'routed': True}) as download: + self.assertEqual(acquire_selected(plan, config=config), {'routed': True}) + download.assert_called_once() + revised = 'f' * 40 + changes = { + 'removed': replace(original, metadata_entries=(other,)), + 'path_changed': replace(original, metadata_entries=(replace(selected, path=FOLDER + '_renamed'), other)), + 'revision_changed': replace(original, metadata_entries=(replace(selected, revision=revised), replace(other, revision=revised))), + 'adapter_changed_and_removed': replace(original, adapter='simready_package', metadata_entries=(other,)), + } + for name, changed in changes.items(): + with self.subTest(change=name): + registry_path.write_text(json.dumps(Registry((changed,)).to_dict())) + with patch('simscene.acquisition.hf_package.acquire_hf_package') as download: + with self.assertRaisesRegex(ValueError, 'ArtVIP'): + acquire_selected(plan, config=config) + download.assert_not_called() + + def test_plan_cannot_dispatch_a_package_or_root_outside_its_selected_directory(self): + source = load_registry().get('artvip') + with tempfile.TemporaryDirectory() as directory, metadata_server({TREE_PATH: {'payload': tree_payload()}}) as (url, _): + config = config_fixture(directory) + provider = make_provider(CatalogStore(config['index_directory']), source, config) + provider.base_url = url + record = provider.search(SearchRequest('door')).items[0] + for name in ('package_path', 'root_directory', 'noncanonical_root'): + with self.subTest(mismatch=name): + availability = copy.deepcopy(record.availability) + descriptor = availability['acquisition'] + root = ROOT + if name == 'package_path': + descriptor['package_path'] = FOLDER + '_other' + elif name == 'root_directory': + root = FOLDER + '/resource/material.usd' + else: + root = FOLDER + '//model_door.usd' + descriptor['path'] = root + descriptor['files'][0]['path'] = root + changed = replace(record, entry_path=root, availability=availability) + plan = make_plan(changed.ref, 'articulated_prop_v1', + {'source_physics_policy': 'preserve_valid', 'proxy_tolerance_m': .002}, + record=changed, runtime=runtime_fixture(), config=config) + self.assertTrue(plan['ready_to_fetch']) + with patch('simscene.acquisition.hf_package.acquire_hf_package') as download: + with self.assertRaisesRegex(ValueError, 'ArtVIP'): + acquire_selected(plan, config=config) + download.assert_not_called() + + def test_an_unreviewed_revision_does_not_inherit_the_pinned_card_license(self): + source = load_registry().get('artvip') + unknown_revision = 'f' * 40 + changed = replace(source, metadata_entries=(replace(source.metadata_entries[0], revision=unknown_revision),)) + tree = TREE_PATH.replace(REVISION, unknown_revision) + with tempfile.TemporaryDirectory() as directory, metadata_server({tree: {'payload': tree_payload()}}) as (url, _): + config = config_fixture(directory) + provider = make_provider(CatalogStore(config['index_directory']), changed, config) + provider.base_url = url + record = provider.search(SearchRequest('door')).items[0] + self.assertEqual(record.license['status'], 'unknown') + self.assertIsNone(record.license['license']) + plan = make_plan(record.ref, 'articulated_prop_v1', + {'source_physics_policy': 'preserve_valid', 'proxy_tolerance_m': .002}, + record=record, runtime=runtime_fixture(), config=config) + self.assertFalse(plan['ready_to_fetch']) + self.assertIn('license_unresolved', {reason['code'] for reason in plan['blocking_reasons']}) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_catalog_audit.py b/tests/test_catalog_audit.py index ab78164..5296c11 100644 --- a/tests/test_catalog_audit.py +++ b/tests/test_catalog_audit.py @@ -57,7 +57,7 @@ def test_license_conflict_nc_gating_layout_and_unknown_granularity_are_independe def test_new_registered_metadata_adapters_remain_disabled_static_candidates(self): registry = load_registry() - sources = [source for source in registry.sources if source.adapter in {'hf_manifest', 'usdcraft'}] + sources = [source for source in registry.sources if source.adapter in {'hf_manifest', 'usdcraft', 'artvip'}] for source in sources: with self.subTest(source=source.source_id): record = candidate(repository=source.repository, revision=source.metadata_entries[0].revision, @@ -112,6 +112,7 @@ def test_generated_sources_file_matches_registry_single_truth(self): changed = Registry(tuple(replace(source, checked_at='2099-01-01') for source in registry.sources)) self.assertNotEqual(build_source_list(changed), build_source_list(registry)) text = build_source_list(registry) + self.assertIn('[artvip](https://huggingface.co/datasets/X-Humanoid/ArtVIP) | audited | no | USD |', text) for state in ('enabled', 'audited', 'candidate', 'quarantined', 'reference_only'): self.assertIn('**' + state + '**', text) self.assertIn('B01DN8TB5U', text) diff --git a/tests/test_catalog_registry.py b/tests/test_catalog_registry.py index 469e447..0ed8c6a 100644 --- a/tests/test_catalog_registry.py +++ b/tests/test_catalog_registry.py @@ -1,6 +1,7 @@ """CPU contracts: admission, unknown facts, identity, and offline resource loading.""" from copy import deepcopy from dataclasses import replace +from datetime import date import json import os from pathlib import Path @@ -28,7 +29,7 @@ def test_packaged_registry_is_offline_and_independent_of_cwd(self): self.assertEqual(registry.schema_version, 1) self.assertTrue(all(s.state == 'enabled' and s.default_enabled for s in registry.select())) self.assertTrue(all(not s.default_enabled for s in registry.sources if s.state != 'enabled')) - self.assertTrue(all(s.checked_at == '2026-11-08' for s in registry.sources)) + self.assertTrue(all(date.fromisoformat(s.checked_at) for s in registry.sources)) abo = registry.get('abo-glb') self.assertEqual(abo.repository, 'codepawl/abo-glb') self.assertEqual(registry.select(['abo-glb']), (abo,)) diff --git a/tests/test_generation_reconnect_runtime.py b/tests/test_generation_reconnect_runtime.py new file mode 100644 index 0000000..3d6f472 --- /dev/null +++ b/tests/test_generation_reconnect_runtime.py @@ -0,0 +1,112 @@ +"""A request retry reconnects to its frozen runtime, even if config changes.""" +import hashlib +from importlib.resources import files +import json +from pathlib import Path +import shutil +from unittest.mock import patch + +import pytest + +from simscene.generation import jobs +from simscene.generation.sand3d import COMMIT, parameters +from simscene.recipes.io import _generation_intent + + +def _runtime(): + return {'schema_version':1,'python':'/old/runtime/python','reviewed_commit':COMMIT, + 'observed':{'sand3d_commit':COMMIT,'sand3d_fingerprint':'fixed'}} + + +def test_new_generation_replay_never_depends_on_current_runtime(tmp_path): + runtime=tmp_path/'runtime.json';runtime.write_text(json.dumps(_runtime())) + config={'home':str(tmp_path/'state'),'index_directory':str(tmp_path/'index'),'generation_runtime':str(runtime)} + with patch('simscene.generation.jobs.subprocess.Popen') as launch, patch('simscene.jobs._process_identity',return_value={'start_ticks':123}): + launch.return_value.pid=999 + first=jobs.start('guide_plate_v1',{},'reconnect',config=config) + replacement=_runtime();replacement['python']='/changed/runtime/python';runtime.write_text(json.dumps(replacement)) + assert jobs.start('guide_plate_v1',{},'reconnect',config=config)['job_id']==first['job_id'] + runtime.unlink() + assert jobs.start('guide_plate_v1',{},'reconnect',config=config)['replayed'] is True + with pytest.raises(ValueError,match='different job parameters'): + jobs.start('guide_plate_v1',{'length_m':.7},'reconnect',config=config) + with pytest.raises(ValueError,match='runtime_unavailable'): + jobs.start('guide_plate_v1',{},'new-request',config=config) + assert launch.call_count==1 + + +def test_legacy_request_replays_after_original_runtime_disappears(tmp_path): + home=tmp_path/'state';job_id='gen-'+'a'*32;root=home/'generation_jobs'/job_id;root.mkdir(parents=True) + payload={'operation':'asset_generate','recipe_id':'guide_plate_v1','parameters':parameters('guide_plate_v1',{}),'runtime':_runtime()} + digest=hashlib.sha256(json.dumps(payload,sort_keys=True,separators=(',',':'),allow_nan=False).encode()).hexdigest() + receipt={'job_id':job_id,'type':'asset_generation','recipe_id':'guide_plate_v1'} + (root/'task.json').write_text(json.dumps(payload)) + (root/'job.json').write_text(json.dumps(dict(receipt,state='queued',request_id='legacy',request_payload_sha256=digest))) + directory=home/'job-requests';directory.mkdir() + (directory/'legacy.json').write_text(json.dumps({'payload_sha256':digest,'state':'started','result':receipt})) + config={'home':str(home),'index_directory':str(tmp_path/'index'),'generation_runtime':str(tmp_path/'removed.json')} + with patch('simscene.generation.jobs.subprocess.Popen') as launch: + resumed=jobs.start('guide_plate_v1',{},'legacy',config=config) + assert resumed==dict(receipt,replayed=True) + with pytest.raises(ValueError,match='different job parameters'): + jobs.start('guide_plate_v1',{'length_m':.7},'legacy',config=config) + launch.assert_not_called() + + +def test_missing_reservation_does_not_prove_a_started_worker_never_existed(tmp_path): + runtime=tmp_path/'runtime.json';runtime.write_text(json.dumps(_runtime())) + home=tmp_path/'state';directory=home/'job-requests';directory.mkdir(parents=True) + payload={'operation':'asset_generate','recipe_id':'guide_plate_v1','parameters':parameters('guide_plate_v1',{})} + digest=hashlib.sha256(json.dumps(payload,sort_keys=True,separators=(',',':'),allow_nan=False).encode()).hexdigest() + (directory/'uncertain.json').write_text(json.dumps({'payload_sha256':digest,'state':'starting'})) + config={'home':str(home),'generation_runtime':str(runtime)} + with patch('simscene.generation.jobs.subprocess.Popen') as launch: + with pytest.raises(ValueError,match='outcome is uncertain'): + jobs.start('guide_plate_v1',{},'uncertain',config=config) + launch.assert_not_called() + assert json.loads((directory/'uncertain.json').read_text())['state']=='starting' + + +def test_missing_runtime_on_new_request_does_not_poison_a_retry(tmp_path): + runtime=tmp_path/'runtime.json' + config={'home':str(tmp_path/'state'),'generation_runtime':str(runtime)} + with patch('simscene.generation.jobs.subprocess.Popen') as launch, patch('simscene.jobs._process_identity',return_value={'start_ticks':123}): + launch.return_value.pid=999 + with pytest.raises(ValueError,match='runtime_unavailable'): + jobs.start('guide_plate_v1',{},'later',config=config) + runtime.write_text(json.dumps(_runtime())) + assert jobs.start('guide_plate_v1',{},'later',config=config)['replayed'] is False + assert launch.call_count==1 + + +def _portable_intent(runtime): + template=files('simscene.generation').joinpath('templates/guide_plate_v1.py').read_bytes() + identity={'recipe_id':'guide_plate_v1','parameters':parameters('guide_plate_v1',{}),'seed':0, + 'template_sha256':hashlib.sha256(template).hexdigest(),'toolchain':runtime} + return _generation_intent(identity,{'generator':'sand3d','reviewed_commit':COMMIT}) + + +def test_portable_lock_compared_to_runtime_actually_frozen_before_launch(tmp_path): + original=_runtime();intent=_portable_intent(original) + changed=_runtime();changed['observed']['sand3d_fingerprint']='changed' + runtime=tmp_path/'runtime.json';runtime.write_text(json.dumps(changed)) + config={'home':str(tmp_path/'state'),'generation_runtime':str(runtime)} + with patch('simscene.generation.jobs.subprocess.Popen') as launch: + with pytest.raises(ValueError,match='portable lock'): + jobs.start('guide_plate_v1',{},'changed-runtime',config=config,expected_intent=intent) + launch.assert_not_called() + + +def test_portable_lock_checks_the_copied_template_before_launch(tmp_path): + runtime=tmp_path/'runtime.json';runtime.write_text(json.dumps(_runtime())) + config={'home':str(tmp_path/'state'),'generation_runtime':str(runtime)} + intent=_portable_intent(_runtime());copytree=shutil.copytree + def changed_copy(src,dst,*args,**kwargs): + result=copytree(src,dst,*args,**kwargs) + template=Path(dst)/'generation/templates/guide_plate_v1.py' + if template.is_file():template.write_text('# altered after earlier preflight\n') + return result + with patch('simscene.generation.jobs.shutil.copytree',side_effect=changed_copy),patch('simscene.generation.jobs.subprocess.Popen') as launch: + with pytest.raises(ValueError,match='portable lock'): + jobs.start('guide_plate_v1',{},'changed-template',config=config,expected_intent=intent) + launch.assert_not_called() diff --git a/tests/test_jobs.py b/tests/test_jobs.py index 7d383f1..1f84bd6 100644 --- a/tests/test_jobs.py +++ b/tests/test_jobs.py @@ -6,6 +6,17 @@ from simscene.scene import SceneStore, SceneError class JobTests(unittest.TestCase): + def test_invalid_two_joint_case_is_rejected_before_worker_launch(self): + from pathlib import Path + with tempfile.TemporaryDirectory() as root: + runtime = Path(root) / 'python.sh' + runtime.write_text('runtime') + with patch.dict('os.environ', {'SIMSCENE_HOME': root, 'SIMSCENE_ISAAC_PYTHON': str(runtime)}): + SceneStore().open('s') + with self.assertRaisesRegex(SceneError, 'two-joint'): + jobs.start('s', 120, case={'schema': 'simscene.articulated_asset_two_joint.v1'}) + self.assertFalse((Path(root) / 'runs').exists()) + def test_incompatible_phase_speed_is_rejected_before_worker_launch(self): from pathlib import Path from unittest.mock import Mock diff --git a/tests/test_mechanism_two_dof.py b/tests/test_mechanism_two_dof.py new file mode 100644 index 0000000..527ef57 --- /dev/null +++ b/tests/test_mechanism_two_dof.py @@ -0,0 +1,667 @@ +import copy +import importlib.util +import math +import unittest +from types import SimpleNamespace +from unittest.mock import patch + +import numpy as np + + +BASE = '/World/cabinet/Asset/Native/Links/base' +FIRST = '/World/cabinet/Asset/Native/Links/first' +SECOND = '/World/cabinet/Asset/Native/Links/second' +JOINT_A = '/World/cabinet/Asset/Native/Joints/a' +JOINT_B = '/World/cabinet/Asset/Native/Joints/b' +ROOT_TYPE = 'engine-articulation-root-link' + + +def joint(path, child, axis): + return {'joint_path': path, 'parent_body': BASE, 'child_body': child, + 'type': 'prismatic', 'axis': axis, 'position_unit': 'm', + 'limits': [-1., 1.], 'local_pos0_m': [0., 0., 0.], + 'local_pos1_m': [0., 0., 0.], 'local_rot0_wxyz': [1., 0., 0., 0.], + 'local_rot1_wxyz': [1., 0., 0., 0.], 'passive': True, 'drive': None} + + +def binding(): + return {'profile_id': 'articulated_prop_v2', 'root_body': BASE, 'motion_bodies': [BASE, FIRST, SECOND], + 'articulation_roots': [BASE], + 'joints': {'alpha': joint(JOINT_A, FIRST, 'X'), 'beta': joint(JOINT_B, SECOND, 'Y')}} + + +def authored(): + return {'bodies': { + BASE: {'position': [1., 2., 3.], 'orientation_wxyz': [1., 0., 0., 0.]}, + FIRST: {'position': [1.2, 2., 3.], 'orientation_wxyz': [1., 0., 0., 0.]}, + SECOND: {'position': [1., 2.3, 3.], 'orientation_wxyz': [1., 0., 0., 0.]}, + }} + + +class FakeArticulationView: + def __init__(self): + self.count = 1 + self.max_dofs = 2 + self.dof_count = 2 + self.link_count = 3 + # The tensor orders deliberately disagree with the frozen dictionary. + self.dof_paths = [[JOINT_B, JOINT_A]] + self.link_paths = [[FIRST, BASE, SECOND]] + self.q = np.array([[.375, .125]], dtype=np.float32) + self.v = np.array([[.02, -.01]], dtype=np.float32) + self.root = np.array([[1., 2., 3., 0., 0., 0., 1.]], dtype=np.float32) + self.root_v = np.zeros((1, 6), dtype=np.float32) + self.link_velocities = np.zeros((1, 3, 6), dtype=np.float32) + self.transforms = None + self.calls = [] + self.ignore_dof_set = False + self.ignore_root_velocity_set = False + self.angular_B = False + self.chain_B = False + self.update() + + def get_metatype(self, index): + assert index == 0 + return SimpleNamespace(dof_count=self.dof_count, link_count=self.link_count) + + def get_dof_positions(self): return self.q + def get_dof_velocities(self): return self.v + def get_link_transforms(self): return self.transforms + def get_link_velocities(self): return self.link_velocities + def get_root_transforms(self): return self.root + def get_root_velocities(self): return self.root_v + def get_masses(self): return np.array([[2., 10., 3.]], dtype=np.float32) + def get_coms(self): return np.tile([0., 0., 0., 0., 0., 0., 1.], (1, 3, 1)) + def get_inertias(self): return np.tile(np.eye(3).reshape(9), (1, 3, 1)) + + def set_root_transforms(self, values, indices): + self.calls.append(('root_transform', values.copy(), indices.copy())) + self.root = values.copy() + + def set_root_velocities(self, values, indices): + self.calls.append(('root_velocity', values.copy(), indices.copy())) + if not self.ignore_root_velocity_set: + self.root_v = values.copy() + + def set_dof_positions(self, values, indices): + self.calls.append(('dof_position', values.copy(), indices.copy())) + if not self.ignore_dof_set: + self.q = values.copy() + + def set_dof_velocities(self, values, indices): + self.calls.append(('dof_velocity', values.copy(), indices.copy())) + self.v = values.copy() + + def update(self): + p = self.root[0, :3] + values = {path: float(self.q[0, i]) for i, path in enumerate(self.dof_paths[0])} + first = [p[0] + values.get(JOINT_A, 0.), p[1], p[2]] + second_parent = first if self.chain_B else p + if self.angular_B: + angle = values.get(JOINT_B, 0.) + second = [*second_parent, 0., 0., math.sin(angle / 2), math.cos(angle / 2)] + else: + second = [second_parent[0], second_parent[1] + values.get(JOINT_B, 0.), + second_parent[2], 0., 0., 0., 1.] + by_link = {BASE: [*p, 0., 0., 0., 1.], + FIRST: [*first, 0., 0., 0., 1.], SECOND: second} + self.transforms = np.asarray([[by_link.get(path, [0., 0., 0., 0., 0., 0., 1.]) + for path in self.link_paths[0]]], dtype=np.float32) + self.link_velocities = np.zeros((1, len(self.link_paths[0]), 6), dtype=np.float32) + + +class FakeSimulationView: + def __init__(self, view): + self.view = view + self.roots = {BASE} + self.updates = 0 + + def get_object_type(self, path): + return ROOT_TYPE if path in self.roots else 'engine-articulation-link' + + def update_articulations_kinematic(self): + self.updates += 1 + self.view.update() + + +V1_BASE = '/World/single/Asset/Native/Base' +V1_CHILD = '/World/single/Asset/Native/Door' +V1_JOINT = '/World/single/Asset/Native/Slide' +RIGID = '/World/ball' + + +def single_binding(): + entry = joint(V1_JOINT, V1_CHILD, 'X') + entry['parent_body'] = V1_BASE + return {'profile_id': 'articulated_prop_v1', 'motion_bodies': [V1_BASE, V1_CHILD], + 'articulation_roots': [V1_BASE], 'joints': {'main': entry}} + + +def all_authored(): + result = authored() + result['phase'] = 'before_sdk_warmup' + for body in result['bodies'].values(): body['local_ops'] = {} + for path, p in ((V1_BASE, [4., 0., 0.]), (V1_CHILD, [4.4, 0., 0.]), (RIGID, [7., 0., 0.])): + result['bodies'][path] = {'position': p, 'orientation_wxyz': [1., 0., 0., 0.], 'local_ops': {}} + return result + + +class FakeSingleView: + def __init__(self): + self.count = 1 + self.max_dofs = 1 + self.link_paths = [[V1_BASE, V1_CHILD]] + self.dof_paths = [[V1_JOINT]] + self.root = np.array([[4., 0., 0., 0., 0., 0., 1.]], dtype=np.float32) + self.q = np.array([[.4]], dtype=np.float32) + self.v = np.zeros((1, 1), dtype=np.float32) + self.calls = [] + self.update() + + def update(self): + x = float(self.root[0, 0]); q = float(self.q[0, 0]) + self.transforms = np.array([[[x, 0., 0., 0., 0., 0., 1.], [x+q, 0., 0., 0., 0., 0., 1.]]], dtype=np.float32) + self.velocities = np.zeros((1, 2, 6), dtype=np.float32) + + def get_link_transforms(self): return self.transforms + def get_link_velocities(self): return self.velocities + def get_dof_positions(self): return self.q + def get_dof_velocities(self): return self.v + def get_masses(self): return np.array([[10., 4.]], dtype=np.float32) + def get_coms(self): return np.tile([0., 0., 0., 0., 0., 0., 1.], (1, 2, 1)) + def get_inertias(self): return np.tile(np.eye(3).reshape(9), (1, 2, 1)) + def set_root_transforms(self, data, indices): self.calls.append('root'); self.root = data.copy() + def set_root_velocities(self, data, indices): self.calls.append('root_v') + def set_dof_positions(self, data, indices): self.calls.append('q'); self.q = data.copy() + def set_dof_velocities(self, data, indices): self.calls.append('v'); self.v = data.copy() + + +class FakeRigidView: + def __init__(self, paths): + self.prim_paths = list(reversed(paths)) + self.transforms = np.array([[7., 0., 0., 0., 0., 0., 1.] for _ in paths], dtype=np.float32) + self.velocities = np.zeros((len(paths), 6), dtype=np.float32) + self.calls = [] + def get_transforms(self): return self.transforms + def get_velocities(self): return self.velocities + def get_masses(self): return np.full(len(self.prim_paths), 5., dtype=np.float32) + def get_coms(self): return np.tile([0., 0., 0., 0., 0., 0., 1.], (len(self.prim_paths), 1)) + def get_inertias(self): return np.tile(np.eye(3).reshape(9), (len(self.prim_paths), 1)) + def set_transforms(self, data, indices): self.calls.append('transforms'); self.transforms = data.copy() + def set_velocities(self, data, indices): self.calls.append('velocities'); self.velocities = data.copy() + + +class FakeMixedSimulation(FakeSimulationView): + def __init__(self): + super().__init__(FakeArticulationView()) + self.single = FakeSingleView() + self.rigid = None + + def create_articulation_view(self, root): + if root == BASE: return self.view + if root == V1_BASE: return self.single + raise AssertionError('unexpected articulation root: ' + root) + + def create_rigid_body_view(self, paths): + self.rigid = FakeRigidView(paths) + return self.rigid + + def update_articulations_kinematic(self): + self.updates += 1 + self.view.update() + self.single.update() + + +class FakePrim: + def GetAttributes(self): return [] + + +class FakeStage: + def GetPrimAtPath(self, path): return FakePrim() + def GetLayerStack(self): return [] + + +class TwoDofTensorTests(unittest.TestCase): + def adapter(self, view=None, frozen=None, simulation=None): + spec = importlib.util.find_spec('simscene.worker.mechanism_v2') + self.assertIsNotNone(spec, 'two-DOF tensor adapter is not implemented') + from simscene.worker.mechanism_v2 import TwoDofTensorState + view = view or FakeArticulationView() + simulation = simulation or FakeSimulationView(view) + return TwoDofTensorState(view, frozen or binding(), simulation_view=simulation, root_link_type=ROOT_TYPE) + + def test_read_uses_tensor_dof_order_and_explicit_link_paths(self): + state = self.adapter().read() + self.assertAlmostEqual(state['native_joint_positions'][JOINT_A], .125) + self.assertAlmostEqual(state['native_joint_positions'][JOINT_B], .375) + self.assertAlmostEqual(state['native_joint_velocities'][JOINT_A], -.01, places=6) + self.assertAlmostEqual(state['native_joint_velocities'][JOINT_B], .02, places=6) + self.assertEqual(state['positions'][BASE], [1., 2., 3.]) + self.assertEqual(state['orientations_wxyz'][BASE], [1., 0., 0., 0.]) + self.assertEqual(state['native_joint_measurement_source'], 'PhysX_articulation_tensor_DOF_readback_SI') + + def test_rejects_bad_actual_dof_count_duplicate_missing_or_extra_paths(self): + for mutation in ('view_count', 'max_dofs', 'actual_dofs', 'missing', 'extra', 'duplicate', 'wrong_path'): + with self.subTest(mutation=mutation): + view = FakeArticulationView() + if mutation == 'view_count': view.count = 2 + elif mutation == 'max_dofs': view.max_dofs = 3 + elif mutation == 'actual_dofs': view.dof_count = 1 + elif mutation == 'missing': view.dof_paths = [[JOINT_A]] + elif mutation == 'extra': view.dof_paths = [[JOINT_A, JOINT_B, '/World/other']] + elif mutation == 'duplicate': view.dof_paths = [[JOINT_A, JOINT_A]] + else: view.dof_paths = [[JOINT_A, '/World/other']] + with self.assertRaises((ValueError, RuntimeError)): + self.adapter(view) + + def test_rejects_invalid_frozen_joint_and_body_graph(self): + for mutation in ('duplicate_joint_path', 'bad_type', 'same_child', 'bad_parent', 'bad_root', 'duplicate_link'): + with self.subTest(mutation=mutation): + frozen = binding() + if mutation == 'duplicate_joint_path': frozen['joints']['beta']['joint_path'] = JOINT_A + elif mutation == 'bad_type': frozen['joints']['beta']['type'] = 'spherical' + elif mutation == 'same_child': frozen['joints']['beta']['child_body'] = FIRST + elif mutation == 'bad_parent': frozen['joints']['beta']['parent_body'] = '/World/elsewhere' + elif mutation == 'bad_root': frozen['root_body'] = FIRST + else: frozen['motion_bodies'] = [BASE, FIRST, FIRST] + with self.assertRaises((ValueError, RuntimeError)): + self.adapter(frozen=frozen) + + def test_actual_root_is_not_inferred_from_first_link_or_static_binding(self): + view = FakeArticulationView() + sim = FakeSimulationView(view) + self.adapter(view, simulation=sim) # root is link_paths[0][1], not [0] + for roots in ({FIRST}, set(), {BASE, SECOND}): + with self.subTest(roots=roots): + sim.roots = roots + with self.assertRaises((ValueError, RuntimeError)): + self.adapter(view, simulation=sim) + + def test_rejects_wrong_or_duplicate_tensor_link_paths(self): + for paths in ([FIRST, BASE], [FIRST, BASE, SECOND, '/World/extra'], + [FIRST, BASE, FIRST], [FIRST, BASE, '/World/elsewhere']): + with self.subTest(paths=paths): + view = FakeArticulationView() + view.link_paths = [paths] + with self.assertRaises((ValueError, RuntimeError)): + self.adapter(view) + + def test_rejects_nonfinite_wrong_shape_and_nonunit_quaternion_readbacks(self): + for mutation in ('q_shape', 'v_shape', 'q_nan', 'v_inf', 'links_shape', 'links_nan', + 'velocities_shape', 'root_shape', 'root_nan', 'quaternion'): + with self.subTest(mutation=mutation): + view = FakeArticulationView() + adapter = self.adapter(view) + if mutation == 'q_shape': view.q = np.zeros((2,)) + elif mutation == 'v_shape': view.v = np.zeros((1, 3)) + elif mutation == 'q_nan': view.q[0, 0] = np.nan + elif mutation == 'v_inf': view.v[0, 1] = np.inf + elif mutation == 'links_shape': view.transforms = np.zeros((3, 7)) + elif mutation == 'links_nan': view.transforms[0, 0, 0] = np.nan + elif mutation == 'velocities_shape': view.link_velocities = np.zeros((1, 2, 6)) + elif mutation == 'root_shape': view.root = np.zeros((7,)) + elif mutation == 'root_nan': view.root[0, 0] = np.nan + else: view.transforms[0, 0, 6] = 2. + with self.assertRaises((ValueError, RuntimeError)): + adapter.read() + + def test_sleeping_root_getter_can_be_stale_and_both_raw_velocities_are_preserved(self): + view = FakeArticulationView() + # Observed Isaac 6.2 sleeping-root behavior: link state is zero while + # the independent root getter retains its last nonzero six-vector. + view.root_v[0] = [9.8421653e-5, -8.3967261e-6, .002321278, + -1.6199634e-5, .0001086288, -.00020209] + try: + result = self.adapter(view).read() + except RuntimeError as error: + self.fail('stale root getter should remain recorded, not abort sampling: ' + str(error)) + raw = result['native_root_velocities'][BASE] + self.assertAlmostEqual(raw['linear_velocity_m_s'][2], .002321278, places=8) + self.assertEqual(result['linear_velocities_m_s'][BASE], [0., 0., 0.]) + self.assertIn('stale', raw['scope']) + + def test_rejects_changed_tensor_order_after_binding(self): + view = FakeArticulationView() + adapter = self.adapter(view) + view.dof_paths = [[JOINT_A, JOINT_B]] + with self.assertRaises((ValueError, RuntimeError)): + adapter.read() + + def test_reset_uses_frozen_frames_but_writes_tensor_order_and_reads_back_once(self): + view = FakeArticulationView() + sim = FakeSimulationView(view) + adapter = self.adapter(view, simulation=sim) + state = authored() + before = copy.deepcopy(state) + result = adapter.reset_before_task(state, is_paused=lambda: True) + self.assertEqual(state, before) + self.assertEqual(sim.updates, 1) + writes = {name: values for name, values, indices in view.calls} + np.testing.assert_allclose(writes['root_transform'], [[1., 2., 3., 0., 0., 0., 1.]]) + np.testing.assert_allclose(writes['dof_position'], [[.3, .2]], atol=1e-6) + np.testing.assert_allclose(writes['root_velocity'], np.zeros((1, 6))) + np.testing.assert_allclose(writes['dof_velocity'], np.zeros((1, 2))) + self.assertAlmostEqual(result['native_joint_positions'][JOINT_A], .2, places=6) + self.assertAlmostEqual(result['native_joint_positions'][JOINT_B], .3, places=6) + with self.assertRaises((ValueError, RuntimeError)): + adapter.reset_before_task(state, is_paused=lambda: True) + self.assertEqual(len(view.calls), 4) + + def test_reset_requires_paused_pre_task_state_and_cannot_repeat_after_task_start(self): + view = FakeArticulationView() + adapter = self.adapter(view) + with self.assertRaises((ValueError, RuntimeError)): + adapter.reset_before_task(authored(), is_paused=lambda: False) + self.assertEqual(view.calls, []) + adapter.mark_task_started() + with self.assertRaises((ValueError, RuntimeError)): + adapter.reset_before_task(authored(), is_paused=lambda: True) + self.assertEqual(view.calls, []) + + def test_failed_reset_readback_cannot_be_retried_after_partial_write(self): + view = FakeArticulationView() + view.ignore_dof_set = True + adapter = self.adapter(view) + with self.assertRaises((ValueError, RuntimeError)): + adapter.reset_before_task(authored(), is_paused=lambda: True) + calls = len(view.calls) + self.assertGreater(calls, 0) + with self.assertRaises((ValueError, RuntimeError)): + adapter.reset_before_task(authored(), is_paused=lambda: True) + self.assertEqual(len(view.calls), calls) + + def test_reset_rejects_nonzero_root_velocity_even_if_link_velocity_is_zero(self): + for speed in (.25, .000001): + with self.subTest(speed=speed): + view = FakeArticulationView() + view.root_v[0, 0] = speed + view.ignore_root_velocity_set = True + adapter = self.adapter(view) + with self.assertRaises((ValueError, RuntimeError)): + adapter.reset_before_task(authored(), is_paused=lambda: True) + + def test_mixed_serial_slider_and_hinge_reset_in_tensor_order(self): + view = FakeArticulationView() + view.angular_B = True + view.chain_B = True + view.update() + frozen = binding() + frozen['joints']['beta'].update(parent_body=FIRST, type='revolute', axis='Z', position_unit='rad') + pose = authored() + pose['bodies'][SECOND]['position'] = [1.2, 2., 3.] + pose['bodies'][SECOND]['orientation_wxyz'] = [math.cos(.15), 0., 0., math.sin(.15)] + state = self.adapter(view, frozen=frozen).reset_before_task(pose, is_paused=lambda: True) + self.assertAlmostEqual(state['native_joint_positions'][JOINT_A], .2, places=6) + self.assertAlmostEqual(state['native_joint_positions'][JOINT_B], .3, places=6) + + def test_revolute_initialization_finds_unique_representative_across_many_turns(self): + for limits, angle in (([10., 11.], 10.5), ([-15., -14.], -14.5)): + with self.subTest(limits=limits): + view = FakeArticulationView(); view.angular_B = True; view.update() + frozen = binding() + frozen['joints']['beta'].update(type='revolute', axis='Z', position_unit='rad', limits=limits) + pose = authored(); pose['bodies'][SECOND]['position'] = [1., 2., 3.] + pose['bodies'][SECOND]['orientation_wxyz'] = [math.cos(angle / 2), 0., 0., math.sin(angle / 2)] + try: + state = self.adapter(view, frozen=frozen).reset_before_task(pose, is_paused=lambda: True) + except ValueError as error: + self.fail('valid multi-turn initial angle was rejected: ' + str(error)) + self.assertAlmostEqual(state['native_joint_positions'][JOINT_B], angle, places=5) + + def test_revolute_unwraps_across_pi_and_rejects_an_initial_pose_with_no_solution(self): + from simscene.worker.mechanism import measure_joint + item = joint(JOINT_B, SECOND, 'Z') + item.update(type='revolute', position_unit='rad', limits=[9.3, 9.8]) + def state(angle): + return {'positions': {BASE: [0., 0., 0.], SECOND: [0., 0., 0.]}, + 'orientations_wxyz': {BASE: [1., 0., 0., 0.], + SECOND: [math.cos(angle/2), 0., 0., math.sin(angle/2)]}} + first = measure_joint(item, state(9.4), physics_step=0, physics_dt_s=.1) + second = measure_joint(item, state(9.5), first, physics_step=1, physics_dt_s=.1) + self.assertAlmostEqual(first['position'], 9.4) + self.assertAlmostEqual(second['position'], 9.5) + self.assertAlmostEqual(second['velocity'], 1.) + item['limits'] = [10., 11.] + view = FakeArticulationView(); view.angular_B = True; view.update() + graph = binding(); graph['joints']['beta'].update(item) + pose = authored(); pose['bodies'][SECOND]['position'] = [1., 2., 3.] + pose['bodies'][SECOND]['orientation_wxyz'] = [math.cos(8./2), 0., 0., math.sin(8./2)] + with self.assertRaises(ValueError): + self.adapter(view, frozen=graph).reset_before_task(pose, is_paused=lambda: True) + self.assertEqual(view.calls, []) + + def test_exact_unique_angle_near_single_turn_boundary_is_not_made_ambiguous_by_tolerance(self): + angle = math.pi - 2e-5 + view = FakeArticulationView(); view.angular_B = True; view.update() + graph = binding() + graph['joints']['beta'].update(type='revolute', axis='Z', position_unit='rad', + limits=[-math.pi + 1e-5, math.pi - 1e-5]) + pose = authored(); pose['bodies'][SECOND]['position'] = [1., 2., 3.] + pose['bodies'][SECOND]['orientation_wxyz'] = [math.cos(angle/2), 0., 0., math.sin(angle/2)] + try: + result = self.adapter(view, frozen=graph).reset_before_task(pose, is_paused=lambda: True) + except ValueError as error: + self.fail('one exactly admissible angle should not be ambiguous: ' + str(error)) + self.assertAlmostEqual(result['native_joint_positions'][JOINT_B], angle, places=5) + + def test_tolerance_cannot_choose_between_two_near_limit_angle_representatives(self): + view = FakeArticulationView(); view.angular_B = True; view.update() + graph = binding() + graph['joints']['beta'].update(type='revolute', axis='Z', position_unit='rad', + limits=[-math.pi + 1e-5, math.pi - 1e-5]) + pose = authored(); pose['bodies'][SECOND]['position'] = [1., 2., 3.] + pose['bodies'][SECOND]['orientation_wxyz'] = [0., 0., 0., 1.] + with self.assertRaisesRegex(ValueError, 'unique initial angle'): + self.adapter(view, frozen=graph).reset_before_task(pose, is_paused=lambda: True) + self.assertEqual(view.calls, []) + + def test_locked_rotation_error_reports_slider_rotation_and_hinge_swing_in_radians(self): + from simscene.worker.mechanism import measure_joint + item = joint(JOINT_B, SECOND, 'Z') + frames = {'positions': {BASE: [0., 0., 0.], SECOND: [0., 0., 0.]}, + 'orientations_wxyz': {BASE: [1., 0., 0., 0.], SECOND: [math.sqrt(.5), math.sqrt(.5), 0., 0.]}} + slider = measure_joint(item, frames, physics_step=0, physics_dt_s=.1) + self.assertAlmostEqual(slider.get('locked_rotation_error_rad', -1.), math.pi/2) + item.update(type='revolute', axis='Z', position_unit='rad', limits=[-2., 2.]) + frames['orientations_wxyz'][SECOND] = [math.cos(.6), 0., 0., math.sin(.6)] + hinge = measure_joint(item, frames, physics_step=0, physics_dt_s=.1) + self.assertAlmostEqual(hinge.get('locked_rotation_error_rad', -1.), 0.) + # q = swing_x(0.4) * twist_z(1.2), independently expanded. + c, s, ct, st = math.cos(.2), math.sin(.2), math.cos(.6), math.sin(.6) + frames['orientations_wxyz'][SECOND] = [c*ct, s*ct, -s*st, c*st] + hinge = measure_joint(item, frames, physics_step=0, physics_dt_s=.1) + self.assertAlmostEqual(hinge.get('locked_rotation_error_rad', -1.), .4) + frames['orientations_wxyz'][SECOND] = [-v for v in frames['orientations_wxyz'][SECOND]] + antipodal = measure_joint(item, frames, physics_step=0, physics_dt_s=.1) + self.assertAlmostEqual(antipodal.get('locked_rotation_error_rad', -1.), .4) + + def test_reset_rejects_slider_rotation_and_hinge_swing_before_any_write(self): + for kind in ('slider', 'hinge'): + with self.subTest(kind=kind): + view = FakeArticulationView(); frozen = binding(); pose = authored() + path = FIRST if kind == 'slider' else SECOND + if kind == 'hinge': + frozen['joints']['beta'].update(type='revolute', axis='Z', position_unit='rad') + pose['bodies'][SECOND]['position'] = [1., 2., 3.] + pose['bodies'][path]['orientation_wxyz'] = [math.sqrt(.5), math.sqrt(.5), 0., 0.] + with self.assertRaises((ValueError, RuntimeError)): + self.adapter(view, frozen=frozen).reset_before_task(pose, is_paused=lambda: True) + self.assertEqual(view.calls, []) + + +class RuntimeIntegrationTests(unittest.TestCase): + @staticmethod + def command(joint_id, target, step=0): + return {'joint_id': joint_id, 'trigger': {'type': 'at_step', 'physics_step': step}, + 'target_position': target, 'position_unit': 'm', + 'stiffness': 20., 'damping': 3., 'max_effort': 50.} + + def mixed_state(self, *, paused=lambda: True, sim=None, bindings=None, root_type=ROOT_TYPE): + from simscene.worker.mechanism import PreparedArticulationState + sim = sim or FakeMixedSimulation() + if bindings is None: bindings = {'double': binding(), 'single': single_binding()} + try: + state = PreparedArticulationState(FakeStage(), {}, bindings, all_authored(), + simulation_view=sim, root_link_type=root_type, is_paused=paused) + except TypeError as error: + self.fail('prepared state cannot accept an injected tensor view: ' + str(error)) + return state, sim + + def test_v2_allows_two_commands_and_records_their_exact_joint_paths(self): + from simscene.worker.mechanism import MechanismController, validate_binding + class Backend: + def __init__(self): self.calls = [] + def apply_drive(self, selected, command): + self.calls.append((selected['joint_path'], command['target_position'])) + return {'target_position': command['target_position']} + def observe(self, selected, step, native_state=None): + return {name: {'physics_step': step, 'joint_path': item['joint_path']} + for name, item in selected['joints'].items()} + graph = binding() + try: + validate_binding(graph) + backend = Backend() + control = MechanismController(graph, {'commands': [self.command('beta', .3), self.command('alpha', .2)]}, backend=backend) + except ValueError as error: + self.fail('explicit v2 binding was rejected: ' + str(error)) + events = control.step(0) + self.assertEqual(backend.calls, [(JOINT_B, .3), (JOINT_A, .2)]) + self.assertEqual([(e['joint_id'], e.get('joint_path')) for e in events], [('beta', JOINT_B), ('alpha', JOINT_A)]) + self.assertEqual(set(control.observe(0)['joints']), {'alpha', 'beta'}) + single = MechanismController(single_binding(), {'commands': [self.command('main', .1)]}, backend=Backend()) + self.assertNotIn('joint_path', single.step(0)[0]) + + def test_only_explicit_v2_can_accept_two_joints(self): + from simscene.worker.mechanism import validate_binding + for profile in ('articulated_prop_v1', 'unknown', None): + graph = binding() + if profile is None: graph.pop('profile_id') + else: graph['profile_id'] = profile + with self.subTest(profile=profile), self.assertRaises(ValueError): validate_binding(graph) + + def test_v2_observation_requires_actual_native_q_and_v_for_both_joints(self): + from simscene.worker.mechanism import UsdMechanismBackend + graph = binding() + actual = self.adapter_state_for_observation() + backend = UsdMechanismBackend(None, None) + result = backend.observe(graph, 0, native_state=actual) + self.assertEqual(set(result), {'alpha', 'beta'}) + self.assertAlmostEqual(result['alpha']['native_position'], .125) + broken = copy.deepcopy(actual) + broken['native_joint_velocities'].pop(JOINT_B) + try: + UsdMechanismBackend(None, None).observe(graph, 0, native_state=broken) + except (ValueError, RuntimeError): + pass + except Exception as error: + self.fail('missing native readback raised the wrong error: ' + repr(error)) + else: + self.fail('missing native joint velocity was accepted') + + @staticmethod + def adapter_state_for_observation(): + from simscene.worker.mechanism_v2 import TwoDofTensorState + view = FakeArticulationView(); sim = FakeSimulationView(view) + return TwoDofTensorState(view, binding(), simulation_view=sim, root_link_type=ROOT_TYPE).read() + + def test_mixed_v1_v2_and_rigid_state_resets_once_then_reads_by_path(self): + state, sim = self.mixed_state() + initial = state.reset_before_task() + observed = state.read() + self.assertEqual(set(observed['positions']), {BASE, FIRST, SECOND, V1_BASE, V1_CHILD, RIGID}) + self.assertEqual(set(observed['native_joint_positions']), {JOINT_A, JOINT_B, V1_JOINT}) + self.assertAlmostEqual(observed['native_joint_positions'][JOINT_A], .2, places=6) + self.assertAlmostEqual(observed['native_joint_positions'][JOINT_B], .3, places=6) + self.assertAlmostEqual(observed['native_joint_positions'][V1_JOINT], .4, places=6) + masses = state.mass_properties(0) + self.assertEqual({p: masses[p]['mass_kg'] for p in (BASE, FIRST, SECOND, V1_BASE, V1_CHILD, RIGID)}, + {BASE: 10., FIRST: 2., SECOND: 3., V1_BASE: 10., V1_CHILD: 4., RIGID: 5.}) + self.assertEqual(initial['reset_count'], 1) + calls = (len(sim.view.calls), len(sim.single.calls), len(sim.rigid.calls)) + state.mark_task_started() + state.read() + with self.assertRaises(RuntimeError): state.reset_before_task() + self.assertEqual((len(sim.view.calls), len(sim.single.calls), len(sim.rigid.calls)), calls) + + def test_mixed_reset_fails_before_any_write_unless_actually_paused(self): + state, sim = self.mixed_state(paused=lambda: False) + with self.assertRaises(RuntimeError): state.reset_before_task() + self.assertEqual(sim.view.calls, []) + self.assertEqual(sim.single.calls, []) + self.assertEqual(sim.rigid.calls, []) + + def test_mixed_graph_rejects_duplicate_dof_and_link_paths(self): + for mutation in ('joint', 'link'): + sim = FakeMixedSimulation() + second = single_binding() + if mutation == 'joint': + second['joints']['main']['joint_path'] = JOINT_A + sim.single.dof_paths = [[JOINT_A]] + else: + second['motion_bodies'] = [BASE, V1_CHILD] + second['joints']['main']['parent_body'] = BASE + sim.single.link_paths = [[BASE, V1_CHILD]] + with self.subTest(mutation=mutation), self.assertRaises((ValueError, RuntimeError)): + self.mixed_state(sim=sim, bindings={'double': binding(), 'single': second}) + + def test_mixed_read_rejects_wrong_v1_or_rigid_tensor_shapes(self): + for mutation in ('v1_extra_q', 'v1_missing_link', 'rigid_extra_body'): + with self.subTest(mutation=mutation): + state, sim = self.mixed_state() + if mutation == 'v1_extra_q': sim.single.q = np.zeros((1, 2)) + elif mutation == 'v1_missing_link': sim.single.transforms = np.zeros((1, 1, 7)) + else: sim.rigid.transforms = np.zeros((2, 7)) + try: + state.read() + except (ValueError, RuntimeError): + pass + except Exception as error: + self.fail('invalid mixed tensor raised the wrong error: ' + repr(error)) + else: + self.fail('invalid mixed tensor shape was accepted') + + def test_mixed_runtime_retains_root_getter_separately_from_link_velocity(self): + state, sim = self.mixed_state() + state.reset_before_task(); state.mark_task_started() + sim.view.root_v[0, 2] = .002321278 + try: + result = state.read() + except RuntimeError as error: + self.fail('sleeping root raw readback aborted the mixed run: ' + str(error)) + self.assertAlmostEqual(result['native_root_velocities'][BASE]['linear_velocity_m_s'][2], .002321278, places=8) + self.assertEqual(result['linear_velocities_m_s'][BASE], [0., 0., 0.]) + self.assertEqual(set(result['native_joint_positions']), {JOINT_A, JOINT_B, V1_JOINT}) + + def test_missing_real_root_enum_fails_closed_for_v2(self): + with self.assertRaises((ValueError, RuntimeError)): + self.mixed_state(root_type=None) + + def test_missing_paused_query_fails_closed_for_v2(self): + with self.assertRaises((ValueError, RuntimeError)): + self.mixed_state(paused=None) + + def test_v2_only_state_resets_and_reads_without_rigid_or_v1_views(self): + from simscene.worker.mechanism import PreparedArticulationState + sim = FakeMixedSimulation(); pose = authored(); pose['phase'] = 'before_sdk_warmup' + for body in pose['bodies'].values(): body['local_ops'] = {} + state = PreparedArticulationState(FakeStage(), {}, {'double': binding()}, pose, + simulation_view=sim, root_link_type=ROOT_TYPE, is_paused=lambda: True) + self.assertIsNone(sim.rigid) + state.reset_before_task(); state.mark_task_started() + self.assertEqual(set(state.read()['positions']), {BASE, FIRST, SECOND}) + + def test_passive_state_forwards_pause_query_and_task_start_to_delegate(self): + from simscene.worker.initial_state import PassiveState + delegate, _ = self.mixed_state() + paused = lambda: True + with patch('simscene.worker.mechanism.PreparedArticulationState', return_value=delegate) as factory: + state = PassiveState(FakeStage(), {}, body_bindings={'double': binding()}, + authored_state=all_authored(), is_paused=paused) + self.assertIs(factory.call_args.kwargs['is_paused'], paused) + state.reset_before_task() + state.mark_task_started() + with self.assertRaises(RuntimeError): state.reset_before_task() + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_native_repairs.py b/tests/test_native_repairs.py new file mode 100644 index 0000000..39b0159 --- /dev/null +++ b/tests/test_native_repairs.py @@ -0,0 +1,391 @@ +"""Explicit derived-asset repairs must preserve source and fail closed.""" +import copy +import math + +import pytest + +from simscene.preparation.profiles import PreparationError, preparation_key, validate_parameters + + +def parameters(): + return {'source_physics_policy': 'repair_explicit', 'collision_method': 'preserve', + 'proxy_tolerance_m': .002, 'native_physics_repairs': { + 'missing_masses_kg': {'Base': 12., 'Door': 8.}, + 'neutralize_drives': {'Hinge': 50.}, + 'reason': 'Experimental masses and disabled source acceleration drive; not manufacturer data.'}} + + +def source_stage(): + from pxr import Usd, UsdGeom, UsdPhysics + stage = Usd.Stage.CreateInMemory() + root = UsdGeom.Xform.Define(stage, '/Native') + stage.SetDefaultPrim(root.GetPrim()) + UsdGeom.SetStageMetersPerUnit(stage, 1.) + UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z) + for name in ('Base', 'Door'): + body = UsdGeom.Xform.Define(stage, '/Native/' + name).GetPrim() + UsdPhysics.RigidBodyAPI.Apply(body) + shape = UsdGeom.Cube.Define(stage, '/Native/' + name + '/Collider') + UsdPhysics.CollisionAPI.Apply(shape.GetPrim()).CreateCollisionEnabledAttr(True) + joint = UsdPhysics.RevoluteJoint.Define(stage, '/Native/Hinge') + joint.CreateBody0Rel().SetTargets(['/Native/Base']) + joint.CreateBody1Rel().SetTargets(['/Native/Door']) + joint.CreateAxisAttr('Z') + joint.CreateLowerLimitAttr(-80.) + joint.CreateUpperLimitAttr(80.) + drive = UsdPhysics.DriveAPI.Apply(joint.GetPrim(), 'angular') + drive.CreateTypeAttr('acceleration') + drive.CreateStiffnessAttr(10.) + drive.CreateDampingAttr(4.) + drive.CreateMaxForceAttr(float('inf')) + drive.CreateTargetPositionAttr(30.) + return stage + + +def test_repairs_are_explicit_bounded_and_part_of_preparation_identity(): + chosen = parameters() + normalized = validate_parameters('articulated_prop_v1', chosen) + assert normalized['native_physics_repairs']['missing_masses_kg'] == {'Base': 12., 'Door': 8.} + target = {'engine': 'physx', 'version': 'fixture'} + first = preparation_key('a' * 64, 'articulated_prop_v1', chosen, target, {'backend': 'usd'}) + changed = copy.deepcopy(chosen) + changed['native_physics_repairs']['missing_masses_kg']['Door'] = 9. + assert preparation_key('a' * 64, 'articulated_prop_v1', changed, target, {'backend': 'usd'}) != first + for bad in ({'reason': '', 'missing_masses_kg': {'Door': 2}, 'neutralize_drives': {}}, + {'reason': 'test', 'missing_masses_kg': {'../Door': 2}, 'neutralize_drives': {}}, + {'reason': 'test', 'missing_masses_kg': {'Door': True}, 'neutralize_drives': {}}, + {'reason': 'test', 'missing_masses_kg': {'Door': float('nan')}, 'neutralize_drives': {}}, + {'reason': 'test', 'missing_masses_kg': {}, 'neutralize_drives': {}}, + {'reason': 'test', 'missing_masses_kg': {}, 'neutralize_drives': {'Hinge': -1}}): + with pytest.raises(PreparationError): + validate_parameters('articulated_prop_v1', dict(chosen, native_physics_repairs=bad)) + with pytest.raises(PreparationError): + validate_parameters('visual_prop_v1', chosen) + with pytest.raises(PreparationError): + validate_parameters('articulated_prop_v1', dict(chosen, source_physics_policy='preserve_valid')) + + +def test_repairs_apply_only_to_derived_stage_and_keep_native_joint(): + from pxr import Usd, UsdPhysics + from simscene.preparation.articulation import inspect_articulation + from simscene.preparation.native_repairs import apply_native_repairs + source = source_stage() + before = source.GetRootLayer().ExportToString() + with pytest.raises(PreparationError, match='lacks explicit mass'): + inspect_articulation(source) + derived = Usd.Stage.Open(source.Flatten()) + report = apply_native_repairs(derived, parameters()['native_physics_repairs']) + measured = inspect_articulation(derived) + assert source.GetRootLayer().ExportToString() == before + assert {item['relative_prim_path']: item['mass_kg'] for item in report['masses']} == {'Base': 12., 'Door': 8.} + assert report['drives'][0]['source']['type'] == 'acceleration' + assert report['drives'][0]['source']['max_effort'] == {'USD_sentinel': 'positive_infinity'} + assert report['drives'][0]['derived']['type'] == 'force' + assert measured['joint_map']['main']['limits'] == pytest.approx([-math.radians(80), math.radians(80)]) + assert measured['joint_map']['main']['drive']['stiffness'] == 0. + assert UsdPhysics.MassAPI(source.GetPrimAtPath('/Native/Door')).GetMassAttr().HasAuthoredValueOpinion() is False + + +def test_cooked_mass_readback_does_not_claim_source_mass_was_preserved(): + import numpy as np + from simscene.worker.mechanism import PreparedArticulationState + class FakeView: + def get_masses(self): return np.array([[8.]]) + def get_coms(self): return np.array([[[0., 0., 0., 0., 0., 0., 1.]]]) + def get_inertias(self): return np.array([[[1., 0., 0., 0., 1., 0., 0., 0., 1.]]]) + state=PreparedArticulationState.__new__(PreparedArticulationState) + state.np=np;state.rigid=None;state.articulations=[(FakeView(),['/World/door'],[],{})];state.two_dof_articulations=[] + state.bindings={'door': {'bodies': {'link1': {'motion_body': '/World/door', + 'mass_provenance': 'explicit_experimental_assumption'}}, + 'native_repairs_ref': {'manifest_sha256': 'a'*64, 'json_pointer': '/physics_repairs'}}} + observed=state.mass_properties(0)['/World/door'] + assert observed['mass_kg'] == 8. + assert 'source mass/collision preserved' not in observed['source'] + assert 'prepared manifest' in observed['source'] + assert observed['mass_provenance'] == 'explicit_experimental_assumption' + assert observed['native_repairs_ref']['manifest_sha256'] == 'a'*64 + + +@pytest.mark.parametrize('mutation', ['malformed_path', 'boolean_mass', 'nonzero_target', 'missing_source', 'empty_source']) +def test_repair_report_rejects_malformed_or_inconsistent_provenance(mutation): + from simscene.preparation.native_repairs import apply_native_repairs, validate_repair_report + repairs=parameters()['native_physics_repairs'] + report=apply_native_repairs(source_stage(),repairs) + if mutation == 'malformed_path': report['masses'][0]['relative_prim_path'] = ['Base'] + elif mutation == 'boolean_mass': report['masses'][0]['mass_kg'] = True + elif mutation == 'nonzero_target': report['drives'][0]['derived']['target_position'] = 1. + elif mutation == 'missing_source': report['drives'][0].pop('source') + else: report['drives'][0]['source']={} + with pytest.raises(ValueError, match='repair report'): + validate_repair_report(repairs,report) + + +def test_explicit_repair_wont_neutralize_an_otherwise_supported_source_drive(): + from pxr import UsdPhysics + from simscene.preparation.native_repairs import apply_native_repairs + stage=source_stage(); drive=UsdPhysics.DriveAPI(stage.GetPrimAtPath('/Native/Hinge'),'angular') + drive.GetTypeAttr().Set('force');drive.GetMaxForceAttr().Set(25.) + before=stage.GetRootLayer().ExportToString() + with pytest.raises(PreparationError, match='already supported'): + apply_native_repairs(stage,parameters()['native_physics_repairs']) + assert stage.GetRootLayer().ExportToString()==before + + +@pytest.mark.parametrize('units', [.1, 10., float('nan')]) +def test_native_mass_units_must_be_canonical_before_any_repair(units): + from pxr import UsdPhysics + from simscene.preparation.native_repairs import apply_native_repairs + stage=source_stage();UsdPhysics.SetStageKilogramsPerUnit(stage,units) + before=stage.GetRootLayer().ExportToString() + with pytest.raises(PreparationError,match='kilogram'): + apply_native_repairs(stage,parameters()['native_physics_repairs']) + assert stage.GetRootLayer().ExportToString()==before + + +@pytest.mark.parametrize('attribute', ['mass', 'density']) +def test_repair_rejects_authored_descendant_mass_or_density(attribute): + from pxr import UsdPhysics + from simscene.preparation.native_repairs import apply_native_repairs + stage=source_stage();api=UsdPhysics.MassAPI.Apply(stage.GetPrimAtPath('/Native/Door/Collider')) + (api.CreateMassAttr(99.) if attribute=='mass' else api.CreateDensityAttr(700.)) + before=stage.GetRootLayer().ExportToString() + with pytest.raises(PreparationError,match='descendant|density'): + apply_native_repairs(stage,parameters()['native_physics_repairs']) + assert stage.GetRootLayer().ExportToString()==before + + +def test_repair_rejects_inherited_mass_api_density(): + from pxr import UsdPhysics + from simscene.preparation.native_repairs import apply_native_repairs + stage=source_stage() + UsdPhysics.MassAPI.Apply(stage.GetDefaultPrim()).CreateDensityAttr(700.) + before=stage.GetRootLayer().ExportToString() + with pytest.raises(PreparationError,match='inherited.*density'): + apply_native_repairs(stage,parameters()['native_physics_repairs']) + assert stage.GetRootLayer().ExportToString()==before + + +def test_material_density_override_must_be_explicit_and_reported(): + from pxr import UsdPhysics, UsdShade + from simscene.preparation.native_repairs import apply_native_repairs, validate_repair_report + stage=source_stage();shape=stage.GetPrimAtPath('/Native/Door/Collider') + mat=UsdShade.Material.Define(stage,'/Native/Steel') + UsdPhysics.MaterialAPI.Apply(mat.GetPrim()).CreateDensityAttr(700.) + UsdShade.MaterialBindingAPI.Apply(shape).Bind(mat,materialPurpose='physics') + repairs=copy.deepcopy(parameters()['native_physics_repairs']) + before=stage.GetRootLayer().ExportToString() + with pytest.raises(PreparationError,match='material density'): + apply_native_repairs(stage,repairs) + assert stage.GetRootLayer().ExportToString()==before + repairs['material_density_overrides']={'Door/Collider':{'material_path':'Steel','density_kg_m3':700.}} + report=apply_native_repairs(stage,repairs) + validate_repair_report(repairs,report) + assert report['material_density_overrides'] == [{'collider_path':'Door/Collider','material_path':'Steel', + 'density_kg_m3':700.,'provenance':'authored_material_density_overridden_by_explicit_body_mass'}] + forged=copy.deepcopy(report);forged['material_density_overrides'][0]['density_kg_m3']=999. + with pytest.raises(ValueError,match='repair report'): + validate_repair_report(repairs,forged) + + +def test_repairs_accept_usd_float32_rounding_without_changing_requested_values(): + from simscene.preparation.articulation import inspect_articulation + from simscene.preparation.native_repairs import apply_native_repairs, annotate_repaired_graph + from pxr import Usd,UsdGeom + chosen=copy.deepcopy(parameters()['native_physics_repairs']) + chosen['missing_masses_kg']['Door']=8.3 + chosen['neutralize_drives']['Hinge']=50.1 + source=source_stage();report=apply_native_repairs(source,chosen) + stage=Usd.Stage.CreateInMemory();root=UsdGeom.Xform.Define(stage,'/Asset');stage.SetDefaultPrim(root.GetPrim()) + UsdGeom.SetStageMetersPerUnit(stage,1.);UsdGeom.SetStageUpAxis(stage,UsdGeom.Tokens.z) + # Nest a copy under the same Native wrapper used by the producer. + from pxr import Sdf + Sdf.CopySpec(source.GetRootLayer(),'/Native',stage.GetRootLayer(),'/Asset/Native') + graph=annotate_repaired_graph(inspect_articulation(stage),chosen) + door=next(item for item in graph['body_map'].values() if item['relative_prim_path']=='Native/Door') + assert door['mass_kg'] == pytest.approx(8.3,rel=1e-6) + assert graph['joint_map']['main']['drive']['max_effort'] == pytest.approx(50.1,rel=1e-6) + assert report['masses'][1]['mass_kg'] == 8.3 + + +@pytest.mark.parametrize('mutation', ['missing_mass', 'extra_mass', 'overwrite_mass', 'unknown_drive', 'unlisted_drive']) +def test_incomplete_or_unauthorized_repairs_do_not_partially_edit_derived_stage(mutation): + from pxr import UsdPhysics + from simscene.preparation.native_repairs import apply_native_repairs + stage = source_stage() + requested = copy.deepcopy(parameters()['native_physics_repairs']) + if mutation == 'missing_mass': + del requested['missing_masses_kg']['Door'] + elif mutation == 'extra_mass': + requested['missing_masses_kg']['Missing'] = 1. + elif mutation == 'overwrite_mass': + UsdPhysics.MassAPI.Apply(stage.GetPrimAtPath('/Native/Door')).CreateMassAttr(4.) + elif mutation == 'unknown_drive': + requested['neutralize_drives']['Missing'] = 1. + else: + requested['neutralize_drives'] = {} + before = stage.GetRootLayer().ExportToString() + with pytest.raises(PreparationError): + apply_native_repairs(stage, requested) + assert stage.GetRootLayer().ExportToString() == before + + +def test_prepared_native_package_records_repairs_and_preserves_source_bytes(tmp_path, monkeypatch): + import hashlib + import json + import pxr + from pxr import Usd, UsdGeom + from simscene.physics_binding import validate_asset_binding + from simscene.preparation.articulation import inspect_articulation + from simscene.preparation.usd_layers import prepare_acquired + stage = source_stage() + mesh = UsdGeom.Mesh.Define(stage, '/Native/Visual') + mesh.CreatePointsAttr([(0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1)]) + mesh.CreateFaceVertexCountsAttr([3, 3, 3, 3]) + mesh.CreateFaceVertexIndicesAttr([0, 2, 1, 0, 1, 3, 0, 3, 2, 1, 2, 3]) + source = tmp_path / 'original.usda' + stage.GetRootLayer().Export(str(source)) + before = source.read_bytes() + digest = hashlib.sha256(before).hexdigest() + dependency=tmp_path/'dependency.bin';dependency.write_bytes(b'original dependency bytes') + acquired = {'root': str(source), 'source_ref': {'source_id': 'fixture', 'asset_id': 'hinge', 'revision': 'v1'}, + 'files': [{'path': source.name, 'sha256': digest, 'size_bytes': len(before)}, + {'path':dependency.name,'sha256':hashlib.sha256(dependency.read_bytes()).hexdigest(), + 'size_bytes':dependency.stat().st_size}], 'license': 'CC0-1.0'} + acquired['manifest_sha256']=hashlib.sha256(json.dumps(acquired['files'],sort_keys=True,separators=(',',':'),ensure_ascii=False).encode()).hexdigest() + # Native USD preparation does not call PhysxSchema; the real Isaac worker + # supplies it. This CPU fixture tests the source-to-derived contract. + monkeypatch.setattr(pxr, 'PhysxSchema', object(), raising=False) + target = {'engine': 'physx', 'usd_version': '.'.join(map(str, Usd.GetVersion()))} + report = prepare_acquired(acquired, 'articulated_prop_v1', parameters(), target, tmp_path / 'prepared') + assert source.read_bytes() == before + manifest = validate_asset_binding({'manifest_path': report['manifest_path'], + 'manifest_sha256': report['manifest_sha256']}, require_dynamic=True, + asset_path=report['asset_path']) + assert manifest['physics_repairs']['reason'] == parameters()['native_physics_repairs']['reason'] + assert len(manifest['physics_repairs']['masses']) == 2 + assert len(manifest['physics_repairs']['drives']) == 1 + assert all(entry['physics_provenance'] == 'native_link_with_explicit_experimental_mass' + for entry in manifest['body_map'].values()) + assert manifest['joint_map']['main']['drive']['provenance'] == 'explicit_neutral_drive_not_original_behavior' + assert manifest['articulation_report']['scope'].startswith('inspected derived graph') + assert manifest['runtime_validation']['status'] == 'not_run' + from simscene.preparation.contracts import prepared_contract + summary = prepared_contract(manifest, manifest_path=report['manifest_path'], manifest_sha256=report['manifest_sha256']) + assert summary['physics_report']['experimental_mass'] is True + assert summary['physics_report']['native_repairs_ref']['json_pointer'] == '/physics_repairs' + assert 'experimental_native_link_masses' in summary['warnings'] + assert 'source_native_drive_neutralized' in summary['warnings'] + prepared = Usd.Stage.Open(report['asset_path']) + assert inspect_articulation(prepared)['joint_map']['main']['drive']['stiffness'] == 0. + # Resolved scene and every cooked mass readback carry the pinned repair + # disclosure, rather than making users infer provenance from a separate log. + from simscene.physics_binding import resolve_body_bindings + stage = Usd.Stage.CreateInMemory() + from pxr import UsdGeom + UsdGeom.SetStageMetersPerUnit(stage,1.);UsdGeom.SetStageUpAxis(stage,UsdGeom.Tokens.z) + UsdGeom.Xform.Define(stage,'/World/door/Asset').GetPrim().GetReferences().AddReference(report['asset_path']) + spec={'objects':{'door':{'kind':'asset','dynamic':True,'asset_path':report['asset_path'], + 'asset_binding':{'manifest_path':report['manifest_path'],'manifest_sha256':report['manifest_sha256']}}}} + binding=resolve_body_bindings(stage,spec)['door'] + assert binding['native_repairs_ref']['manifest_sha256'] == report['manifest_sha256'] + assert {item['mass_provenance'] for item in binding['bodies'].values()} == {'explicit_experimental_assumption'} + assert (tmp_path / 'prepared' / 'source' / source.name).read_bytes() == before + json.loads((tmp_path / 'prepared' / 'manifest.json').read_text()) + # A self-consistent replacement manifest and new pin cannot relabel a + # repaired source as a preservation-only package. Reinspect its hashed + # source snapshot, not only the prepared USD and manifest assertions. + manifest_path = tmp_path / 'prepared' / 'manifest.json' + clean_bytes=manifest_path.read_bytes() + forged=copy.deepcopy(manifest) + forged['source_ref']['revision']='f'*40 + manifest_path.write_text(json.dumps(forged)) + spec['objects']['door']['asset_binding']['manifest_sha256']=hashlib.sha256(manifest_path.read_bytes()).hexdigest() + with pytest.raises(ValueError,match='source attribution'): + validate_asset_binding(spec['objects']['door']['asset_binding']) + forged=copy.deepcopy(manifest) + forged['parameters']['source_physics_policy']='preserve_valid' + forged['parameters'].pop('native_physics_repairs') + forged.pop('physics_repairs') + forged['articulation_report']=inspect_articulation(prepared) + forged['body_map']=forged['articulation_report']['body_map'] + forged['joint_map']=forged['articulation_report']['joint_map'] + manifest_path.write_text(json.dumps(forged)) + spec['objects']['door']['asset_binding']['manifest_sha256']=hashlib.sha256(manifest_path.read_bytes()).hexdigest() + with pytest.raises(ValueError,match='source|mass'): + resolve_body_bindings(stage,spec) + forged=copy.deepcopy(manifest) + forged['physics_repairs']['drives'][0]['source']['type']='force' + manifest_path.write_text(json.dumps(forged)) + spec['objects']['door']['asset_binding']['manifest_sha256']=hashlib.sha256(manifest_path.read_bytes()).hexdigest() + with pytest.raises(ValueError,match='source physics repair report'): + resolve_body_bindings(stage,spec) + manifest_path.write_bytes(clean_bytes) + acquired_file=tmp_path/'prepared'/'source'/'acquired.json' + acquired_before=acquired_file.read_bytes();altered_acquired=json.loads(acquired_before) + altered_acquired['files']=altered_acquired['files'][:1];acquired_file.write_text(json.dumps(altered_acquired)) + forged=copy.deepcopy(manifest) + row=next(item for item in forged['files'] if item['path']=='source/acquired.json') + row.update(sha256=hashlib.sha256(acquired_file.read_bytes()).hexdigest(),size_bytes=acquired_file.stat().st_size) + manifest_path.write_text(json.dumps(forged)) + spec['objects']['door']['asset_binding']['manifest_sha256']=hashlib.sha256(manifest_path.read_bytes()).hexdigest() + with pytest.raises(ValueError,match='source acquisition'): + validate_asset_binding(spec['objects']['door']['asset_binding']) + acquired_file.write_bytes(acquired_before);manifest_path.write_bytes(clean_bytes) + # A changed collider transform must not be treated as preserved collision + # merely because its prim path and the updated file hash are consistent. + derived_file=tmp_path/'prepared'/'derived'/'visual.usda' + derived_before=derived_file.read_bytes() + modified=Usd.Stage.Open(str(derived_file)) + collider=modified.GetPrimAtPath('/Native/Door/Collider') + UsdGeom.Xformable(collider).AddTranslateOp().Set((10.,0.,0.)) + modified.GetRootLayer().Save() + forged=copy.deepcopy(manifest) + file_row=next(item for item in forged['files'] if item['path']=='derived/visual.usda') + file_row.update(sha256=hashlib.sha256(derived_file.read_bytes()).hexdigest(),size_bytes=derived_file.stat().st_size) + manifest_path.write_text(json.dumps(forged)) + spec['objects']['door']['asset_binding']['manifest_sha256']=hashlib.sha256(manifest_path.read_bytes()).hexdigest() + with pytest.raises(ValueError,match='source|collision|physics'): + resolve_body_bindings(stage,spec) + derived_file.write_bytes(derived_before) + modified.GetRootLayer().Reload() + manifest_path.write_bytes(clean_bytes) + # Re-hashing a changed source dependency cannot erase the frozen transfer + # record, even when that particular dependency does not alter the graph. + copied_dependency=tmp_path/'prepared'/'source'/'dependency.bin' + original_dependency=copied_dependency.read_bytes();copied_dependency.write_bytes(b'replaced dependency') + forged=copy.deepcopy(manifest) + file_row=next(item for item in forged['files'] if item['path']=='source/dependency.bin') + file_row.update(sha256=hashlib.sha256(copied_dependency.read_bytes()).hexdigest(),size_bytes=copied_dependency.stat().st_size) + manifest_path.write_text(json.dumps(forged)) + spec['objects']['door']['asset_binding']['manifest_sha256']=hashlib.sha256(manifest_path.read_bytes()).hexdigest() + with pytest.raises(ValueError,match='source.*(closure|attribution|acquisition)'): + validate_asset_binding(spec['objects']['door']['asset_binding']) + copied_dependency.write_bytes(original_dependency) + manifest_path.write_bytes(clean_bytes) + # Even if the local acquisition file list is also edited, its previously + # recorded acquisition-manifest hash must still describe that exact list. + copied_dependency.write_bytes(b'replaced dependency') + modified_acquired=json.loads(acquired_before) + dep_record=next(item for item in modified_acquired['files'] if item['path']=='dependency.bin') + dep_record.update(sha256=hashlib.sha256(copied_dependency.read_bytes()).hexdigest(),size_bytes=copied_dependency.stat().st_size) + acquired_file.write_text(json.dumps(modified_acquired)) + forged=copy.deepcopy(manifest) + for name,path in [('source/dependency.bin',copied_dependency),('source/acquired.json',acquired_file)]: + row=next(item for item in forged['files'] if item['path']==name) + row.update(sha256=hashlib.sha256(path.read_bytes()).hexdigest(),size_bytes=path.stat().st_size) + source_rows=[{'path':item['path'][len('source/'):],'sha256':item['sha256'],'size_bytes':item['size_bytes']} + for item in forged['files'] if item['path'].startswith('source/') and item['path']!='source/acquired.json'] + forged['source_closure_sha256']=hashlib.sha256(json.dumps(sorted(source_rows,key=lambda x:x['path']),sort_keys=True,separators=(',',':')).encode()).hexdigest() + manifest_path.write_text(json.dumps(forged)) + spec['objects']['door']['asset_binding']['manifest_sha256']=hashlib.sha256(manifest_path.read_bytes()).hexdigest() + with pytest.raises(ValueError,match='source acquisition manifest'): + validate_asset_binding(spec['objects']['door']['asset_binding']) + copied_dependency.write_bytes(original_dependency);acquired_file.write_bytes(acquired_before);manifest_path.write_bytes(clean_bytes) + # Scene admission cannot silently lose the derivation disclosures, even if + # the caller pins a freshly recalculated hash of the altered manifest. + manifest['physics_repairs']['masses'][0]['mass_kg'] = 99. + manifest_path.write_text(json.dumps(manifest)) + altered_sha = hashlib.sha256(manifest_path.read_bytes()).hexdigest() + with pytest.raises(ValueError, match='repair report'): + validate_asset_binding({'manifest_path': str(manifest_path), 'manifest_sha256': altered_sha}, + require_dynamic=True, asset_path=report['asset_path']) diff --git a/tests/test_preparation_articulation.py b/tests/test_preparation_articulation.py index 87eb158..bda760a 100644 --- a/tests/test_preparation_articulation.py +++ b/tests/test_preparation_articulation.py @@ -216,6 +216,8 @@ def package(self,directory): from pxr import Usd,UsdGeom from simscene.preparation.articulation import inspect_articulation root=Path(directory);native=self.stage();native.GetRootLayer().Export(str(root/'native.usda')) + (root/'source').mkdir();native.GetRootLayer().Export(str(root/'source'/'native.usda')) + (root/'source'/'acquired.json').write_text('{}') stage=Usd.Stage.CreateNew(str(root/'main.usda'));asset=UsdGeom.Xform.Define(stage,'/Asset');stage.SetDefaultPrim(asset.GetPrim()) UsdGeom.SetStageMetersPerUnit(stage,1.);UsdGeom.SetStageUpAxis(stage,UsdGeom.Tokens.z) UsdGeom.Xform.Define(stage,'/Asset/Native').GetPrim().GetReferences().AddReference('./native.usda') @@ -223,10 +225,22 @@ def package(self,directory): manifest={'schema':'simscene.prepared_asset.v1','schema_version':1,'profile_id':'articulated_prop_v1', 'main':'main.usda','default_prim':'/Asset','body_map':report['body_map'], 'joint_map':report['joint_map'],'articulation_report':report,'parameters':{'ccd':False}, - 'files':[{'path':p.name,'size_bytes':p.stat().st_size,'sha256':hashlib.sha256(p.read_bytes()).hexdigest()} for p in [root/'native.usda',root/'main.usda']]} + 'source_root':'source/native.usda','source_sha256':hashlib.sha256((root/'source'/'native.usda').read_bytes()).hexdigest(), + 'files':[{'path':p.relative_to(root).as_posix(),'size_bytes':p.stat().st_size,'sha256':hashlib.sha256(p.read_bytes()).hexdigest()} for p in [root/'native.usda',root/'main.usda',root/'source'/'native.usda',root/'source'/'acquired.json']]} path=root/'manifest.json';path.write_text(json.dumps(manifest));binding={'manifest_path':str(path),'manifest_sha256':hashlib.sha256(path.read_bytes()).hexdigest()} return {'kind':'asset','asset_path':str(root/'main.usda'),'asset_binding':binding,'dynamic':True,'position':[1.,2.,3.]} + def test_legacy_graph_without_new_native_attribute_inventory_remains_verifiable(self): + import json,tempfile + from pathlib import Path + from simscene.preparation.articulation import verify_source_graph + with tempfile.TemporaryDirectory() as tmp: + self.package(tmp) + manifest=json.loads((Path(tmp)/'manifest.json').read_text()) + joint=manifest['articulation_report']['joint_map']['main'] + joint.pop('native_authored_attributes');joint.pop('native_attribute_units') + self.assertTrue(verify_source_graph(Path(tmp),manifest)) + def test_export_multiple_real_links_and_joint_then_mutation_rejected(self): import tempfile from pathlib import Path diff --git a/tests/test_preparation_articulation_v2.py b/tests/test_preparation_articulation_v2.py new file mode 100644 index 0000000..05f867c --- /dev/null +++ b/tests/test_preparation_articulation_v2.py @@ -0,0 +1,118 @@ +"""Two-coordinate assets must prepare and bind without changing v1 semantics.""" +import hashlib + +import pytest + +from simscene.preparation.profiles import PreparationError, validate_parameters + + +def parameters(): + return {'source_physics_policy':'preserve_valid','collision_method':'preserve','proxy_tolerance_m':.002} + + +def source_stage(): + from test_articulation_v2 import TwoDofInspectionTests + from pxr import UsdGeom + stage=TwoDofInspectionTests().stage() + mesh=UsdGeom.Mesh.Define(stage,'/Asset/Visual') + mesh.CreatePointsAttr([(0,0,0),(1,0,0),(0,1,0),(0,0,1)]) + mesh.CreateFaceVertexCountsAttr([3,3,3,3]) + mesh.CreateFaceVertexIndicesAttr([0,2,1,0,1,3,0,3,2,1,2,3]) + return stage + + +def test_two_dof_profile_is_preserve_only_and_has_distinct_identity(): + from simscene.preparation.profiles import preparation_key + p=validate_parameters('articulated_prop_v2',parameters()) + assert p['source_physics_policy']=='preserve_valid' + target={'engine':'physx','version':'fixture'} + assert preparation_key('a'*64,'articulated_prop_v2',parameters(),target,{'backend':'usd'}) != \ + preparation_key('a'*64,'articulated_prop_v1',parameters(),target,{'backend':'usd'}) + with pytest.raises(PreparationError): + validate_parameters('articulated_prop_v2',dict(parameters(),source_physics_policy='repair_explicit')) + + +def test_two_dof_package_preserves_source_and_binds_both_joints(tmp_path,monkeypatch): + import pxr + from pxr import Usd,UsdGeom + from simscene.preparation.usd_layers import prepare_acquired + from simscene.physics_binding import resolve_body_bindings,validate_asset_binding + from simscene.scene import validate + stage=source_stage();source=tmp_path/'source.usda';stage.GetRootLayer().Export(str(source));before=source.read_bytes() + acquired={'root':str(source),'source_ref':{'source_id':'fixture','asset_id':'tree','revision':'v1'}, + 'files':[{'path':source.name,'sha256':hashlib.sha256(before).hexdigest(),'size_bytes':len(before)}]} + monkeypatch.setattr(pxr,'PhysxSchema',object(),raising=False) + report=prepare_acquired(acquired,'articulated_prop_v2',parameters(),{'engine':'physx','usd_version':'.'.join(map(str,Usd.GetVersion()))},tmp_path/'package') + assert source.read_bytes()==before + manifest=validate_asset_binding({'manifest_path':report['manifest_path'],'manifest_sha256':report['manifest_sha256']},require_dynamic=True,asset_path=report['asset_path']) + assert manifest['profile_id']=='articulated_prop_v2' and len(manifest['joint_map'])==2 + assert manifest['runtime_validation']['status']=='not_run' + composed=Usd.Stage.CreateInMemory();UsdGeom.SetStageMetersPerUnit(composed,1.);UsdGeom.SetStageUpAxis(composed,UsdGeom.Tokens.z) + UsdGeom.Xform.Define(composed,'/World/asset/Asset').GetPrim().GetReferences().AddReference(report['asset_path']) + obj={'kind':'asset','asset_path':report['asset_path'],'asset_binding':{'manifest_path':report['manifest_path'],'manifest_sha256':report['manifest_sha256']},'dynamic':True,'position':[0,0,0]} + config={'commands':[{'joint_id':'joint1','trigger':{'type':'at_step','physics_step':0},'target_position':.25,'position_unit':'m','stiffness':12.,'damping':4.,'max_effort':150.}]} + obj['mechanism']=config + scene={'scene_id':'test','revision':1,'objects':{'asset':obj},'observation':{'strict_start':True,'sample_interval_steps':1}} + assert validate(scene)==[] + binding=resolve_body_bindings(composed,scene)['asset'] + assert binding['profile_id']=='articulated_prop_v2' and len(binding['motion_bodies'])==3 + assert binding['root_body'].endswith('/Links/Base') + assert {j['joint_path'].split('/')[-1] for j in binding['joints'].values()}=={'Hinge','Slide'} + slide=next(j for j in binding['joints'].values() if j['type']=='prismatic') + assert slide['drive']['max_effort']==150. and slide['drive']['stiffness']==12. + + +def test_two_dof_runtime_rejects_unbounded_or_acceleration_source_drive(): + from pxr import UsdPhysics + from simscene.preparation.articulation_v2 import runtime_joint + from simscene.preparation.articulation_v2 import inspect_articulation_v2 + stage=source_stage();drive=UsdPhysics.DriveAPI(stage.GetPrimAtPath('/Asset/Joints/Slide'),'linear') + for value in ('acceleration','infinity'): + if value=='acceleration':drive.GetTypeAttr().Set('acceleration') + else:drive.GetTypeAttr().Set('force');drive.GetMaxForceAttr().Set(float('inf')) + graph=inspect_articulation_v2(stage) + with pytest.raises(PreparationError):runtime_joint(graph['joint_map']['joint1']) + + +def test_two_dof_preparation_rejects_unmapped_static_colliders(tmp_path,monkeypatch): + import pxr + from pxr import Usd,UsdGeom,UsdPhysics + from simscene.preparation.usd_layers import prepare_acquired + stage=source_stage();box=UsdGeom.Cube.Define(stage,'/Asset/UnownedCollider') + UsdPhysics.CollisionAPI.Apply(box.GetPrim()) + source=tmp_path/'source.usda';stage.GetRootLayer().Export(str(source));payload=source.read_bytes() + acquired={'root':str(source),'files':[{'path':source.name,'sha256':hashlib.sha256(payload).hexdigest(),'size_bytes':len(payload)}]} + monkeypatch.setattr(pxr,'PhysxSchema',object(),raising=False) + with pytest.raises(PreparationError,match='static collider'): + prepare_acquired(acquired,'articulated_prop_v2',parameters(),{'engine':'physx','usd_version':'.'.join(map(str,Usd.GetVersion()))},tmp_path/'package') + + +def test_two_dof_fixed_world_frame_cannot_be_silently_changed(tmp_path): + from pxr import Gf,Usd,UsdGeom,UsdPhysics + from simscene.preparation.articulation_v2 import inspect_articulation_v2,resolve_instance_v2 + source=source_stage();fixed=UsdPhysics.FixedJoint.Define(source,'/Asset/Joints/Anchor') + fixed.CreateBody1Rel().SetTargets(['/Asset/Links/Base']);p=tmp_path/'source.usda';source.GetRootLayer().Export(str(p)) + stage=Usd.Stage.CreateInMemory();UsdGeom.SetStageMetersPerUnit(stage,1.);UsdGeom.SetStageUpAxis(stage,UsdGeom.Tokens.z) + anchor=UsdGeom.Xform.Define(stage,'/World/object/Asset').GetPrim() + UsdGeom.Xform.Define(stage,'/World/object/Asset/Native').GetPrim().GetReferences().AddReference(str(p)) + manifest={'articulation_report':inspect_articulation_v2(stage,anchor)} + assert resolve_instance_v2(stage,anchor,manifest)['root_body'].endswith('/Links/Base') + joint=UsdPhysics.Joint(stage.GetPrimAtPath('/World/object/Asset/Native/Joints/Anchor')) + joint.CreateLocalPos0Attr(Gf.Vec3f(10,0,0)) + with pytest.raises(PreparationError,match='world.*anchor'): + resolve_instance_v2(stage,anchor,manifest) + + +def test_two_dof_world_anchor_follows_explicit_rigid_instance_placement(tmp_path): + from pxr import Gf,Usd,UsdGeom,UsdPhysics + from simscene.preparation.articulation import transform_world_anchors + from simscene.preparation.articulation_v2 import inspect_articulation_v2,resolve_instance_v2 + source=source_stage();fixed=UsdPhysics.FixedJoint.Define(source,'/Asset/Joints/Anchor') + fixed.CreateBody1Rel().SetTargets(['/Asset/Links/Base']);p=tmp_path/'source.usda';source.GetRootLayer().Export(str(p)) + stage=Usd.Stage.CreateInMemory();UsdGeom.SetStageMetersPerUnit(stage,1.);UsdGeom.SetStageUpAxis(stage,UsdGeom.Tokens.z) + parent=UsdGeom.Xform.Define(stage,'/World/object');anchor=UsdGeom.Xform.Define(stage,'/World/object/Asset').GetPrim() + UsdGeom.Xform.Define(stage,'/World/object/Asset/Native').GetPrim().GetReferences().AddReference(str(p)) + manifest={'articulation_report':inspect_articulation_v2(stage,anchor)} + parent.AddTranslateOp().Set(Gf.Vec3d(1,2,3));parent.AddRotateZOp().Set(35.) + transform_world_anchors(stage,anchor) + assert resolve_instance_v2(stage,anchor,manifest)['root_body'].endswith('/Links/Base') diff --git a/tests/test_recipe_io.py b/tests/test_recipe_io.py index 6cb4570..3e2e1b4 100644 --- a/tests/test_recipe_io.py +++ b/tests/test_recipe_io.py @@ -101,6 +101,82 @@ def test_generated_export_records_only_trusted_intent_and_rejects_arbitrary_code manifest['provenance']['identity']['recipe_id']='exec_program' with self.assertRaises(ValueError):io.prepared_selection(manifest,acquired,manifest_sha256='a'*64) + def test_usdcraft_sdk_generated_intent_is_portable_and_version_pinned(self): + from simscene.generation.usdcraft_sdk import COMMIT, RECIPE + manifest=copy.deepcopy(self.manifest);acquired=copy.deepcopy(self.acquired) + manifest['source_ref']=dict(manifest['source_ref'],source_id='local-usdcraft-sdk',asset_id=RECIPE) + acquired['source_ref']=manifest['source_ref'] + identity={'recipe_id':RECIPE,'parameters':{'length_m':.7},'seed':0,'template_sha256':'1'*64, + 'generation_contract_version':3,'toolchain':{'schema_version':1,'backend':'usdcraft_sdk', + 'python':'/private/sdk/python','reviewed_commit':COMMIT, + 'observed':{'usdcraft_commit':COMMIT,'usdcraft_version':'1.0.0','source_clean':True, + 'repository_path':'/private/sdk/repo','source_tree_sha256':'2'*64,'python_version':[3,12,0]}}} + manifest['provenance']={'generator':'usdcraft_sdk','reviewed_commit':COMMIT,'identity':identity} + selection=io.prepared_selection(manifest,acquired,manifest_sha256='a'*64) + self.assertEqual(selection['generation']['generator'],'usdcraft_sdk') + self.assertEqual(selection['generation']['parameters']['length_m'],.7) + self.assertEqual(selection['generation']['generation_contract_version'],3) + self.assertNotIn('/private/',json.dumps(selection)) + identity['generation_contract_version']=1 + with self.assertRaises(ValueError):io.prepared_selection(manifest,acquired,manifest_sha256='a'*64) + identity['generation_contract_version']=3 + identity['recipe_id']='execute_downloaded_code' + with self.assertRaises(ValueError):io.prepared_selection(manifest,acquired,manifest_sha256='a'*64) + + def test_sdk_recipe_rebuild_uses_a_durable_trusted_generation_job(self): + from importlib.resources import files + from simscene.generation.usdcraft_sdk import COMMIT, RECIPE + selection=copy.deepcopy(self.selection) + new_ref={'source_id':'local-usdcraft-sdk','asset_id':RECIPE,'revision':'a'*64,'variant_id':None} + selection['source_ref']=new_ref + runtime={'schema_version':1,'backend':'usdcraft_sdk','python':'/private/sdk/python','reviewed_commit':COMMIT, + 'observed':{'usdcraft_commit':COMMIT,'usdcraft_version':'1.0.0','source_clean':True}} + template=files('simscene.generation').joinpath('templates/'+RECIPE+'.py').read_bytes() + identity={'recipe_id':RECIPE,'parameters':{'length_m':.7},'seed':0,'generation_contract_version':3, + 'template_sha256':hashlib.sha256(template).hexdigest(),'toolchain':runtime} + selection['generation']=io._generation_intent(identity,{'generator':'usdcraft_sdk','reviewed_commit':COMMIT}) + result={'root':self.binding['asset_path'],**self.binding['asset_binding'],'actual_download_bytes':0} + runtime_path=self.root/'sdk-runtime.json';runtime_path.write_text(json.dumps(runtime)) + config={'home':str(self.root/'state'),'asset_cache_directory':str(self.root/'cache'), + 'usdcraft_generation_runtime':str(runtime_path)} + with (patch('simscene.generation.jobs.start',return_value={'job_id':'gen-fixture'}) as generate, + patch('simscene.generation.jobs.status',return_value={'state':'completed','result':{'asset_ref':new_ref}}), + patch('simscene.acquisition.plans.make_plan',return_value={'ready_to_fetch':True,'plan_id':'p'}) as plan, + patch('simscene.preparation.jobs.start',return_value={'job_id':'prep-fixture'}), + patch('simscene.preparation.jobs.status',return_value={'state':'completed','result':result,'actual_download_bytes':0}), + patch('simscene.recipes.io.validate_rebuilt',return_value={})): + catalog=acquirer.acquire({'schema':io.SCHEMA,'assets':{'plate':selection}},self.root/'cache',config=config) + self.assertEqual(catalog['plate'],self.binding) + self.assertEqual(generate.call_args.args[:2],(RECIPE,selection['generation']['parameters'])) + self.assertEqual(plan.call_args.args[0],new_ref) + selection['generation']['generator']='untrusted' + with self.assertRaises(acquirer.RecipeAcquireError): + acquirer.acquire({'schema':io.SCHEMA,'assets':{'plate':selection}},self.root/'cache',config=config) + + def test_generated_rebuild_rejects_wrong_backend_and_stale_template_before_launch(self): + from importlib.resources import files + from simscene.generation.sand3d import COMMIT + from simscene.generation.usdcraft_sdk import RECIPE + selection=copy.deepcopy(self.selection) + selection['source_ref']=dict(selection['source_ref'],source_id='local-sand3d',asset_id=RECIPE) + runtime={'schema_version':1,'python':'/private/python','reviewed_commit':COMMIT, + 'observed':{'sand3d_commit':COMMIT}} + runtime_path=self.root/'sand3d-runtime.json';runtime_path.write_text(json.dumps(runtime)) + config={'home':str(self.root/'state'),'generation_runtime':str(runtime_path)} + selection['generation']={'generator':'sand3d','seed':0,'recipe_id':RECIPE,'parameters':{}, + 'reviewed_commit':COMMIT,'template_sha256':'1'*64,'toolchain_intent':runtime['observed']} + with patch('simscene.generation.jobs.start') as generate: + with self.assertRaises(acquirer.RecipeAcquireError): + acquirer.acquire({'schema':io.SCHEMA,'assets':{'plate':selection}},self.root/'cache',config=config) + generate.assert_not_called() + selection['source_ref']['asset_id']='guide_plate_v1' + selection['generation']['recipe_id']='guide_plate_v1' + assert hashlib.sha256(files('simscene.generation').joinpath('templates/guide_plate_v1.py').read_bytes()).hexdigest()!='1'*64 + with patch('simscene.generation.jobs.start') as generate: + with self.assertRaises(acquirer.RecipeAcquireError): + acquirer.acquire({'schema':io.SCHEMA,'assets':{'plate':selection}},self.root/'cache',config=config) + generate.assert_not_called() + def test_legacy_snapshot_export_retains_v1_payload_and_asset_uri(self): run=self.root/'legacy-run';(run/'assets'/('a'*64)).mkdir(parents=True) source='https://example.invalid/selected.usd' diff --git a/tests/test_two_joint_dispatch.py b/tests/test_two_joint_dispatch.py new file mode 100644 index 0000000..6fcb58d --- /dev/null +++ b/tests/test_two_joint_dispatch.py @@ -0,0 +1,30 @@ +import json +from unittest.mock import Mock,patch + +import pytest + +from simscene.verification import case_runner + + +def test_two_joint_schema_dispatches_to_its_own_sealed_verifier(tmp_path): + case=tmp_path/'case.json';case.write_text(json.dumps({'schema':'simscene.articulated_asset_two_joint.v1'})) + fake=Mock();fake.verify_run.return_value={'passed':False} + with patch.object(case_runner.importlib,'import_module',return_value=fake) as load: + result=case_runner.evaluate(tmp_path,case) + assert load.call_args.args[0]=='.articulated_asset_two_joint' + assert result['case_type']=='articulated_asset_two_joint' + with pytest.raises(ValueError): + case_runner.evaluate(tmp_path,case,'parallel') + + +def test_two_joint_paired_mode_requires_and_dispatches_positive_reference(tmp_path): + case=tmp_path/'case.json';case.write_text(json.dumps({'schema':'simscene.articulated_asset_two_joint.v1'})) + reference=tmp_path/'positive';reference.mkdir() + fake=Mock();fake.verify_pair.return_value={'passed':True} + with patch.object(case_runner.importlib,'import_module',return_value=fake) as load: + result=case_runner.evaluate(tmp_path,case,mode='missing_second_joint_drive',reference_run=reference) + assert load.call_args.args[0]=='.articulated_asset_two_joint_pair' + fake.verify_pair.assert_called_once_with(reference,tmp_path,case) + assert result['passed'] and result['case_type']=='articulated_asset_two_joint' + with pytest.raises(ValueError): + case_runner.evaluate(tmp_path,case,mode='missing_second_joint_drive') diff --git a/tests/test_usdcraft_sdk_example.py b/tests/test_usdcraft_sdk_example.py new file mode 100644 index 0000000..472bcd6 --- /dev/null +++ b/tests/test_usdcraft_sdk_example.py @@ -0,0 +1,59 @@ +"""Keep the generated-plate example a controlled parameter comparison.""" +import copy +import importlib.util +import json +import os +from pathlib import Path +from unittest.mock import patch + +import pytest + + +ROOT=Path(__file__).resolve().parents[1]/'examples'/'usdcraft_sdk_guide' + + +def test_generated_plate_example_changes_only_its_prepared_role(): + short=json.loads((ROOT/'recipe-short.json').read_text()) + long=json.loads((ROOT/'recipe-long.json').read_text()) + case=json.loads((ROOT/'case.json').read_text()) + lock=json.loads((ROOT/'assets.lock.json').read_text())['assets'] + assert case['seed']==17 and case['physics_dt_s']==1/60 and case['physics_device']=='cpu' + left=copy.deepcopy(short['operations']);right=copy.deepcopy(long['operations']) + first=next(op for op in left if op.get('id')=='plate')['object'] + second=next(op for op in right if op.get('id')=='plate')['object'] + assert first.pop('asset_role')=='short' and second.pop('asset_role')=='long' + assert left==right + ball=next(op for op in left if op.get('id')=='ball')['object'] + assert ball['physics']['enable_ccd'] is True + for role,length in (('short',.5),('long',.7)): + item=lock[role];condition=case['assets'][role] + assert item['source_ref']['source_id']=='local-usdcraft-sdk' + assert item['generation']['parameters']['length_m']==length==condition['length_m'] + assert item['source_sha256']==condition['source_sha256'] + assert condition['manifest_sha256']=='${'+role+'.manifest_sha256}' + assert condition['source_ref']=='${'+role+'.source_ref}' + assert item['parameters']['source_physics_policy']=='replace_visual_only' + assert item['parameters']['static_proxy']['size_m']==[length,.18,.015] + + +@pytest.mark.skipif(not os.getenv('SIMSCENE_SDK_PAIR_FIXTURE'),reason='requires independently recorded Isaac pair') +def test_real_pair_checker_rejects_equal_but_wrong_seed_device_and_initial_scene(): + fixture=json.loads(Path(os.environ['SIMSCENE_SDK_PAIR_FIXTURE']).read_text()) + short=Path(fixture['short']);long=Path(fixture['long']);case=Path(fixture['case']) + spec=importlib.util.spec_from_file_location('sdk_guide_check',ROOT/'check_pair.py') + module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module) + assert module.check(short,long,case)['passed'] + read_text=Path.read_text + for targets,change in ( + ({short/'run-lock.json',long/'run-lock.json'},lambda data:data.update(seed=999,physics_device='gpu')), + ({short/'spec.json',long/'spec.json'},lambda data:data['objects']['ball'].update(position=[.3,0.,.7])), + ({short/'result.json'},lambda data:data['samples'][100]['positions']['/World/ball'].__setitem__(2,float('nan'))), + ({short/'result.json'},lambda data:data['samples'][100].update(absolute_physics_step=-1)), + ): + def spoof(path,*args,**kwargs): + text=read_text(path,*args,**kwargs) + if path in targets: + data=json.loads(text);change(data);return json.dumps(data) + return text + with patch.object(Path,'read_text',spoof): + assert not module.check(short,long,case)['passed'] diff --git a/tests/test_usdcraft_sdk_generation.py b/tests/test_usdcraft_sdk_generation.py new file mode 100644 index 0000000..51b7981 --- /dev/null +++ b/tests/test_usdcraft_sdk_generation.py @@ -0,0 +1,201 @@ +"""Trusted USDCraft template selection, durable dispatch and immutable sources.""" +import json +import hashlib +import io +import sys +from contextlib import redirect_stdout +from pathlib import Path +import tempfile +import unittest +from unittest.mock import patch + +from simscene.generation import jobs + +COMMIT = '46fec187bdce40845c30863a56143047edc4a263' +RECIPE = 'usdcraft_sdk_guide_plate_v1' + + +class USDCraftSDKGenerationTests(unittest.TestCase): + def test_explicit_sdk_recipe_uses_its_own_runtime_and_replays_durable_job(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + runtime = {'schema_version': 1, 'backend': 'usdcraft_sdk', 'python': '/isolated/sdk-python', + 'reviewed_commit': COMMIT, + 'observed': {'usdcraft_commit': COMMIT, 'usdcraft_version': '1.0.0', 'source_clean': True}} + manifest = root / 'sdk-runtime.json' + manifest.write_text(json.dumps(runtime)) + config = {'home': str(root / 'state'), 'index_directory': str(root / 'index'), + 'usdcraft_generation_runtime': str(manifest)} + with patch('simscene.generation.jobs.subprocess.Popen') as launch, \ + patch('simscene.jobs._process_identity', return_value={'start_ticks': 123}): + launch.return_value.pid = 999 + first = jobs.start(RECIPE, {'length_m': .6}, 'sdk-request', config=config) + second = jobs.start(RECIPE, {'length_m': .6}, 'sdk-request', config=config) + self.assertEqual(first['job_id'], second['job_id']) + self.assertTrue(second['replayed']) + self.assertEqual(launch.call_count, 1) + task = json.loads((jobs.directory(first['job_id'], config=config) / 'task.json').read_text()) + self.assertEqual(task['recipe_id'], RECIPE) + self.assertEqual(task['runtime']['backend'], 'usdcraft_sdk') + self.assertEqual(task['parameters'], {'length_m': .6, 'width_m': .18, 'thickness_m': .015}) + + def test_generated_sdk_source_is_pinned_and_uses_ordinary_plan_and_acquisition(self): + from simscene.generation import usdcraft_sdk + from simscene.catalog.models import AssetRef + from simscene.catalog.store import CatalogStore + from simscene.acquisition.plans import make_plan + from simscene.acquisition.dispatch import acquire_selected + from test_asset_plans import config_fixture, runtime_fixture + self.assertTrue(callable(getattr(usdcraft_sdk, 'generate_asset', None)), 'SDK generator missing') + with tempfile.TemporaryDirectory() as directory: + root = Path(directory); config = config_fixture(directory) + runtime = {'schema_version': 1, 'backend': 'usdcraft_sdk', 'python': '/isolated/sdk-python', + 'reviewed_commit': COMMIT, + 'observed': {'usdcraft_commit': COMMIT, 'usdcraft_version': '1.0.0', 'source_clean': True}} + def backend(task, python, folder): + self.assertEqual(task['recipe_id'], RECIPE) + self.assertEqual(task['parameters']['length_m'], .6) + Path(task['output']).write_text('#usda 1.0\n') + Path(task['runtime_output']).write_text(json.dumps(runtime['observed'])) + Path(task['report_output']).write_text(json.dumps({'check': 'passed', 'compile': 'passed', 'closure': 'resolved_locally'})) + with patch('simscene.generation.usdcraft_sdk._run', side_effect=backend): + result = usdcraft_sdk.generate_asset(RECIPE, {'length_m': .6}, runtime, + output_directory=root / 'job-output', config=config) + record = CatalogStore(config['index_directory']).get(AssetRef.from_dict(result['asset_ref'])) + self.assertEqual(record.ref.source_id, 'local-usdcraft-sdk') + self.assertEqual(record.license['license'], 'Apache-2.0') + self.assertEqual(record.provenance['generator'], 'usdcraft_sdk') + self.assertEqual(record.provenance['identity']['toolchain']['reviewed_commit'], COMMIT) + self.assertEqual(record.provenance['identity']['parameters']['length_m'], .6) + self.assertEqual(len(record.provenance['identity']['template_sha256']), 64) + self.assertEqual(result['physics_status'], 'not_prepared') + self.assertEqual(record.availability['acquisition']['kind'], 'generated_package') + plan = make_plan(record.ref, 'visual_prop_v1', {'source_physics_policy': 'replace_visual_only', 'proxy_tolerance_m': .002}, + record=record, runtime=runtime_fixture(), config=config) + self.assertTrue(plan['ready_to_fetch'], plan['blocking_reasons']) + acquired = acquire_selected(plan, config=config) + self.assertEqual(hashlib.sha256(Path(acquired['root']).read_bytes()).hexdigest(), + record.provenance['identity']['output_sha256']) + self.assertEqual(acquired['dependency_status'], 'resolved_locally') + self.assertEqual(acquired['actual_download_bytes'], 0) + + def test_sdk_backend_rejects_program_text_paths_and_unbounded_parameters(self): + from simscene.generation import usdcraft_sdk + for value in ({'program': 'print(1)'}, {'script_path': '/tmp/evil.py'}, {'length_m': float('nan')}, + {'thickness_m': .08, 'width_m': .02}): + with self.subTest(value=value), self.assertRaises(ValueError): + usdcraft_sdk.parameters(RECIPE, value) + self.assertFalse(callable(getattr(usdcraft_sdk, 'run_external_program', None))) + from simscene.generation import usdcraft_backend_worker as worker + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + task = {'operation': 'generate', 'recipe_id': RECIPE, + 'parameters': {'length_m': .5, 'width_m': .18, 'thickness_m': .015}, + 'expected_runtime': {}, 'template_sha256': 'a' * 64, + 'output': str(root / 'source.usda'), 'runtime_output': str(root / 'backend-runtime.json'), + 'report_output': str(root / 'sdk-report.json')} + for bad in (dict(task, program='print(1)'), dict(task, model_path='/tmp/evil.py'), + dict(task, output='/tmp/escaped.usda'), dict(task, recipe_id='other')): + with self.subTest(task=bad), self.assertRaises(ValueError): + worker.validate_task(bad, root) + + def test_identical_generated_source_reuses_identity_despite_job_specific_report_hash(self): + from simscene.generation import usdcraft_sdk + from simscene.catalog.models import stable_hash + import shutil + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + config = {'home': str(root / 'state'), 'index_directory': str(root / 'index')} + runtime = {'schema_version': 1, 'backend': 'usdcraft_sdk', 'python': '/isolated/sdk-python', + 'reviewed_commit': COMMIT, + 'observed': {'usdcraft_commit': COMMIT, 'usdcraft_version': '1.0.0', 'source_clean': True}} + def backend(task, python, folder): + Path(task['output']).write_text('#usda 1.0\n') + Path(task['runtime_output']).write_text(json.dumps(runtime['observed'])) + Path(task['report_output']).write_text(json.dumps({'check': 'passed', 'compile': 'passed', + 'closure': 'resolved_locally', 'compile_report_sha256': hashlib.sha256(str(folder).encode()).hexdigest()})) + with patch('simscene.generation.usdcraft_sdk._run', side_effect=backend): + first = usdcraft_sdk.generate_asset(RECIPE, {}, runtime, output_directory=root / 'one', config=config) + manifest = Path(first['generated_manifest_path']) + generated = json.loads(manifest.read_text()) + self.assertEqual(generated['identity']['generation_contract_version'], 3) + self.assertNotIn('compile_report_sha256', generated['generator_check']) + first_manifest = manifest.read_bytes() + # Recreate an older published contract at its original distinct + # identity and ensure a new generation neither alters nor aliases it. + legacy = json.loads(first_manifest) + legacy['identity']['generation_contract_version'] = 2 + legacy_revision = stable_hash(legacy['identity']) + legacy['asset_ref']['revision'] = legacy_revision + legacy['generator_check']['compile_report_sha256'] = 'a' * 64 + legacy['generator_check']['compiled_root_sha256'] = 'b' * 64 + legacy_dir = root / 'state' / 'generated_assets' / legacy_revision + legacy_dir.mkdir() + shutil.copyfile(manifest.parent / 'source.usda', legacy_dir / 'source.usda') + legacy_bytes = json.dumps(legacy).encode() + (legacy_dir / 'generated.json').write_bytes(legacy_bytes) + second = usdcraft_sdk.generate_asset(RECIPE, {}, runtime, output_directory=root / 'two', config=config) + self.assertEqual(manifest.read_bytes(), first_manifest) + self.assertEqual((legacy_dir / 'generated.json').read_bytes(), legacy_bytes) + self.assertNotEqual(first['asset_ref']['revision'], legacy_revision) + # Differences in frozen toolchain data remain an immutable collision. + altered = json.loads(first_manifest) + altered['identity']['toolchain']['reviewed_commit'] = '0' * 40 + manifest.write_text(json.dumps(altered)) + with self.assertRaisesRegex(ValueError, 'immutable generated source collision'): + usdcraft_sdk.generate_asset(RECIPE, {}, runtime, output_directory=root / 'three', config=config) + self.assertEqual(first['asset_ref'], second['asset_ref']) + self.assertNotEqual(first['sdk_report_sha256'], second['sdk_report_sha256']) + self.assertTrue(Path(second['sdk_report_path']).is_file()) + + def test_changed_runtime_or_template_is_rejected_before_template_execution(self): + from simscene.generation import usdcraft_backend_worker as worker + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + runtime = {'usdcraft_version': '1.0.0', 'source_tree_sha256': '1' * 64} + task = {'operation': 'generate', 'recipe_id': RECIPE, + 'parameters': {'length_m': .5, 'width_m': .18, 'thickness_m': .015}, + 'expected_runtime': dict(runtime), 'template_sha256': 'a' * 64, + 'output': str(root / 'source.usda'), 'runtime_output': str(root / 'backend-runtime.json'), + 'report_output': str(root / 'sdk-report.json')} + with patch.object(worker, '_observe', return_value=dict(runtime, source_tree_sha256='2' * 64)): + with self.assertRaisesRegex(ValueError, 'runtime changed'): + worker.run(task, root) + with patch.object(worker, '_observe', return_value=runtime): + with self.assertRaisesRegex(ValueError, 'template differs'): + worker.run(task, root) + self.assertFalse((root / 'model.py').exists()) + + def test_supervisor_dispatches_sdk_recipe_without_calling_sand3d(self): + from simscene.generation import worker + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / 'job.json').write_text(json.dumps({'job_id': 'gen-' + 'a' * 32, 'state': 'queued'})) + (root / 'config.json').write_text(json.dumps({'home': str(root)})) + (root / 'task.json').write_text(json.dumps({'recipe_id': RECIPE, 'parameters': {}, 'runtime': {'backend': 'usdcraft_sdk'}})) + with patch('simscene.__file__', str(root / 'runtime' / 'simscene' / '__init__.py')), \ + patch('simscene.generation.usdcraft_sdk.generate_asset', return_value={'asset_ref': {'source_id': 'local-usdcraft-sdk'}}), \ + patch('simscene.generation.sand3d.generate_asset', side_effect=AssertionError('wrong backend')): + worker.execute(root) + record = json.loads((root / 'job.json').read_text()) + self.assertEqual(record['state'], 'completed') + self.assertEqual(record['result']['asset_ref']['source_id'], 'local-usdcraft-sdk') + + def test_sdk_runtime_has_separate_configuration_and_explicit_probe_cli(self): + from simscene.catalog.config import read + from simscene.cli import main + with tempfile.TemporaryDirectory() as directory: + root = Path(directory); config = root / 'v2.json'; manifest = root / 'sdk-runtime.json' + config.write_text(json.dumps({'usdcraft_generation_runtime': str(manifest)})) + with patch.dict('os.environ', {'SIMSCENE_V2_CONFIG': str(config)}): + self.assertEqual(read()['usdcraft_generation_runtime'], str(manifest)) + argv = ['simscene', 'generate', 'probe', '--backend', 'usdcraft-sdk', '--python', '/sdk/python', + '--checkout', '/sdk/reviewed-checkout', '--output', str(manifest)] + with patch.object(sys, 'argv', argv), redirect_stdout(io.StringIO()), \ + patch('simscene.generation.usdcraft_sdk.probe_runtime', return_value={'backend': 'usdcraft_sdk'}) as probe: + self.assertEqual(main(), 0) + probe.assert_called_once_with('/sdk/python', str(manifest), checkout='/sdk/reviewed-checkout') + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_usdcraft_sdk_hardening.py b/tests/test_usdcraft_sdk_hardening.py new file mode 100644 index 0000000..a15c82a --- /dev/null +++ b/tests/test_usdcraft_sdk_hardening.py @@ -0,0 +1,146 @@ +"""Runtime integrity and process-tree behavior for the optional SDK backend.""" +import os +from pathlib import Path +import py_compile +import subprocess +import sys +import tempfile +import threading +import time +import unittest +from unittest.mock import patch + +from simscene.generation import usdcraft_backend_worker as worker +from simscene.generation import usdcraft_sdk + + +class USDCraftRuntimeIntegrityTests(unittest.TestCase): + def test_structural_validation_precedes_dependency_bootstrap(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + task = {'operation': 'generate', 'recipe_id': usdcraft_sdk.RECIPE, + 'parameters': {'length_m': .5, 'width_m': .18, 'thickness_m': .015}, + 'expected_runtime': {}, 'template_sha256': 'a' * 64, + 'output': str(root / 'source.usda'), 'runtime_output': str(root / 'backend-runtime.json'), + 'report_output': str(root / 'sdk-report.json')} + with patch.object(worker, 'parameters', side_effect=AssertionError('loaded before bootstrap')): + worker.validate_task(task, root, normalize=False) + + def test_git_blob_verification_rejects_hidden_tracked_change_and_ignored_module(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + def git(*args): + return subprocess.run(['git', '-C', str(root), *args], check=True, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True).stdout.strip() + git('init', '-q') + git('config', 'user.email', 'fixture@example.invalid') + git('config', 'user.name', 'Fixture') + for name in ['sdk/__init__.py', 'sdk/model.template', 'usdcraft/__init__.py', + 'storage/__init__.py', 'storage/artifact_contract.py']: + path = root / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text('# committed fixture\n') + (root / '.gitignore').write_text('sdk/ignored_shadow.py\n') + git('add', '.') + git('commit', '-qm', 'fixture') + commit = git('rev-parse', 'HEAD') + baseline = worker._verify_checkout(root, commit) + self.assertTrue(baseline) + git('update-index', '--assume-unchanged', 'storage/artifact_contract.py') + (root / 'storage/artifact_contract.py').write_text('# tampered, not executed\n') + self.assertEqual(git('status', '--porcelain=v1'), '') + with self.assertRaisesRegex(ValueError, 'blob|commit'): + worker._verify_checkout(root, commit) + (root / 'storage/artifact_contract.py').write_text('# committed fixture\n') + git('update-index', '--no-assume-unchanged', 'storage/artifact_contract.py') + (root / 'sdk/ignored_shadow.py').write_text('# ignored, not executed\n') + self.assertEqual(git('status', '--porcelain=v1'), '') + with self.assertRaisesRegex(ValueError, 'untracked|unexpected|shadow'): + worker._verify_checkout(root, commit) + + def test_top_level_sdk_origins_cannot_be_shadowed(self): + with tempfile.TemporaryDirectory() as directory: + base = Path(directory); root = base / 'checkout'; shadow = base / 'shadow' + for package in ['sdk', 'usdcraft', 'storage', 'viewer']: + (root / package).mkdir(parents=True) + (root / package / '__init__.py').write_text('') + (shadow / 'storage').mkdir(parents=True) + (shadow / 'storage' / '__init__.py').write_text('') + worker._verify_import_origins(root, [str(root)]) + with self.assertRaisesRegex(ValueError, 'origin|shadow'): + worker._verify_import_origins(root, [str(shadow), str(root)]) + + def test_probe_never_executes_pth_startup_hooks(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory); venv = root / 'venv'; marker = root / 'executed' + subprocess.run([sys.executable, '-m', 'venv', '--without-pip', str(venv)], check=True) + site = next((venv / 'lib').glob('python*/site-packages')) + (site / 'untrusted.pth').write_text('import pathlib; pathlib.Path(' + repr(str(marker)) + ').write_text("ran")\n') + output = root / 'probe'; output.mkdir() + # The empty venv must fail the SDK probe, without executing the .pth. + with self.assertRaises(subprocess.CalledProcessError): + usdcraft_sdk._run({'operation': 'probe', 'output': str(output / 'observed.json')}, venv / 'bin/python', output) + self.assertFalse(marker.exists()) + + def test_checkout_bytecode_cache_cannot_override_verified_python_source(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory); package = root / 'sdk'; package.mkdir() + marker = root / 'forged-cache-ran'; source = package / '__init__.py' + malicious = 'from pathlib import Path; Path(' + repr(str(marker)) + ').write_text("forged")\n' + safe = '# harmless verified source'.ljust(len(malicious) - 1) + '\n' + timestamp = int(time.time()) - 10 + source.write_text(malicious); os.utime(source, (timestamp, timestamp)) + py_compile.compile(str(source), doraise=True) + source.write_text(safe); os.utime(source, (timestamp, timestamp)) + # Establish that the forged, timestamp-valid cache would execute. + env = dict(os.environ, PYTHONPATH=str(root), PYTHONDONTWRITEBYTECODE='1') + env.pop('PYTHONPYCACHEPREFIX', None) + subprocess.run([sys.executable, '-S', '-c', 'import sdk'], env=env, cwd=root, check=True) + self.assertTrue(marker.exists()) + marker.unlink() + output = root / 'output'; output.mkdir(); launcher = root / 'launcher' + launcher.write_text('#!/usr/bin/python3\nimport sys\nsys.path.insert(0, ' + repr(str(root)) + ')\nimport sdk\n') + launcher.chmod(0o755) + usdcraft_sdk._run({'operation': 'probe', 'output': str(output / 'observed.json')}, launcher, output) + self.assertFalse(marker.exists()) + + def test_timeout_and_cancel_kill_sdk_descendants_before_they_write(self): + for mode in ('timeout', 'cancel'): + with self.subTest(mode=mode), tempfile.TemporaryDirectory() as directory: + root = Path(directory); output = root / 'output'; output.mkdir() + marker = root / 'late-marker'; ready = root / 'child-started'; child = root / 'child.py'; launcher = root / 'launcher' + child.write_text('import time\nfrom pathlib import Path\nPath(' + repr(str(ready)) + ').write_text("ready")\ntime.sleep(1.5)\nPath(' + repr(str(marker)) + ').write_text("late")\n') + launcher.write_text('#!/usr/bin/python3\nimport subprocess, time\nsubprocess.Popen(["/usr/bin/python3", ' + repr(str(child)) + '])\ntime.sleep(30)\n') + launcher.chmod(0o755) + timer = None + if mode == 'cancel': + timer = threading.Timer(.5, lambda: (root / 'cancel-request.json').write_text('{}')) + timer.start() + try: + with patch.object(usdcraft_sdk, 'SDK_TIMEOUT_SECONDS', 1.0): + expected = subprocess.TimeoutExpired if mode == 'timeout' else usdcraft_sdk.GenerationCancelled + with self.assertRaises(expected): + usdcraft_sdk._run({'operation': 'generate'}, launcher, output) + finally: + if timer: + timer.join() + self.assertTrue(ready.exists(), 'the descendant must have actually started') + time.sleep(1.7) + self.assertFalse(marker.exists(), 'a descendant survived cancellation or timeout') + + def test_supervisor_records_sdk_cancellation_as_cancelled(self): + import json + from simscene.generation import worker as supervisor + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / 'job.json').write_text(json.dumps({'job_id': 'gen-' + 'a' * 32, 'state': 'queued'})) + (root / 'config.json').write_text('{}') + (root / 'task.json').write_text(json.dumps({'recipe_id': usdcraft_sdk.RECIPE, 'parameters': {}, 'runtime': {}})) + with patch('simscene.__file__', str(root / 'runtime' / 'simscene' / '__init__.py')), \ + patch.object(usdcraft_sdk, 'generate_asset', side_effect=usdcraft_sdk.GenerationCancelled('cancelled')): + supervisor.execute(root) + self.assertEqual(json.loads((root / 'job.json').read_text())['state'], 'cancelled') + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_usdcraft_two_drawer_example.py b/tests/test_usdcraft_two_drawer_example.py new file mode 100644 index 0000000..291ce74 --- /dev/null +++ b/tests/test_usdcraft_two_drawer_example.py @@ -0,0 +1,32 @@ +"""The portable example must retain its intended one-command counterfactual.""" +import copy +import json +from pathlib import Path + +from simscene.verification.articulated_asset_two_joint import _commands, validate_case + + +EXAMPLE = Path(__file__).resolve().parents[1] / 'examples' / 'usdcraft_two_drawer' + + +def test_drawer_case_and_control_keep_a_single_declared_causal_difference(): + positive = json.loads((EXAMPLE / 'recipe.json').read_text()) + control = json.loads((EXAMPLE / 'recipe-control.json').read_text()) + case = json.loads((EXAMPLE / 'case.json').read_text()) + selection = json.loads((EXAMPLE / 'assets.lock.json').read_text())['assets']['cabinet'] + obj = case['objects']['cabinet'] + assert obj['prepared_manifest_sha256'] == '${cabinet.manifest_sha256}' + assert obj['source_ref'] == '${cabinet.source_ref}' + obj['prepared_manifest_sha256'] = 'a' * 64 + obj['source_ref'] = selection['source_ref'] + validate_case(case) + positive_ops = copy.deepcopy(positive['operations']) + cabinet = next(op for op in positive_ops if op.get('id') == 'cabinet') + commands = cabinet['object']['mechanism']['commands'] + assert commands == _commands(obj['joints'], obj['phases']) + removed = commands.pop() + assert removed['joint_id'] == obj['phases'][1]['joint_id'] + assert removed['trigger'] == {'type': 'at_step', 'physics_step': obj['phases'][1]['command_step']} + assert positive_ops == control['operations'] + assert selection['profile_id'] == 'articulated_prop_v2' + assert selection['source_ref']['asset_id'] == 'ds_R022_02' From 30852a39e9e0043ea4c798d31194a9480ce1088e Mon Sep 17 00:00:00 2001 From: shaoxiang <519517384@qq.com> Date: Mon, 16 Nov 2026 19:37:44 +0800 Subject: [PATCH 03/20] Keep packaged skills consistent with their sources --- plugins/build.py | 6 ------ skills/build-scene/SKILL.md | 2 +- skills/build-scene/references/passive-d6-joints.md | 4 ++++ .../references/passive-network-verification.md | 12 +++++++++--- tests/agent/test_package.py | 7 +++++++ 5 files changed, 21 insertions(+), 10 deletions(-) diff --git a/plugins/build.py b/plugins/build.py index 36d2277..4378796 100644 --- a/plugins/build.py +++ b/plugins/build.py @@ -165,12 +165,6 @@ def build(destination, use_installed_deps=False): for example,names in EXAMPLE_DATA.items(): target=portable/'examples'/example;target.mkdir(parents=True) for name in names:shutil.copyfile(ROOT/'examples'/example/name,target/name) - shutil.copyfile(ROOT/'docs'/'passive-network-verification.md', - portable/'skills'/'build-scene'/'references'/'passive-network-verification.md') - shutil.copyfile(ROOT/'docs'/'structural-loads-verification.md', - portable/'skills'/'build-scene'/'references'/'structural-loads-verification.md') - shutil.copyfile(ROOT/'docs'/'passive-d6-joints.md', - portable/'skills'/'build-scene'/'references'/'passive-d6-joints.md') write(portable/'plugin.json',{'$schema':'https://agent-plugins.org/schemas/1.0.0/plugin.schema.json','name':'simscene','version':PACKAGE_VERSION,'description':'Discover assets, compose and run experimental simulation scenes.'}) write(portable/'mcp.json',{'$schema':'https://agent-plugins.org/schemas/1.0.0/mcp.schema.json','mcpServers':{'simscene':{'type':'stdio','command':'python3','args':['${PLUGIN_ROOT}/server/launch.py'],'cwd':'${PLUGIN_ROOT}'}}}) claude.mkdir(parents=True) diff --git a/skills/build-scene/SKILL.md b/skills/build-scene/SKILL.md index 34e0817..b32b03f 100644 --- a/skills/build-scene/SKILL.md +++ b/skills/build-scene/SKILL.md @@ -45,7 +45,7 @@ backend experimental until actual paired mechanism trials pass. For a passive force-path acceptance case, read [network verification](references/passive-network-verification.md). A separate -gravity-loaded support pad requires the explicit v2 declaration and +gravity-loaded support pad requires the explicit v2 or v3 declaration and [typed support evidence](references/structural-loads-verification.md); never invent an activation or count structural motion as task progress. Freeze the software, geometry, case and controls before formal runs, and retain their diff --git a/skills/build-scene/references/passive-d6-joints.md b/skills/build-scene/references/passive-d6-joints.md index 30277ad..2c1ce80 100644 --- a/skills/build-scene/references/passive-d6-joints.md +++ b/skills/build-scene/references/passive-d6-joints.md @@ -40,3 +40,7 @@ contract. Before accepting a new load or layout, verify resting compatibility, actual transmission and a matched drawer-end cut. Keep both endpoints' original motion, complete observations, case and runtime pins. See [network verification](passive-network-verification.md) for composition. +For a complete network, use `simscene.passive_network.v3` with exactly one +explicitly versioned D6 rope assertion and its required typed support loads; +v1 and v2 do not admit D6 rope assertions. Preserve older frozen cases and their +original checker versions. diff --git a/skills/build-scene/references/passive-network-verification.md b/skills/build-scene/references/passive-network-verification.md index 4e00bcd..08e4dde 100644 --- a/skills/build-scene/references/passive-network-verification.md +++ b/skills/build-scene/references/passive-network-verification.md @@ -5,7 +5,12 @@ against complete recorded physics observations. It accepts measured motion, physical contact callbacks and passive constraints. It never starts physics, edits a scene, releases an object, applies a force or fills a missing sample. -The public case schema is `simscene.passive_network.v1`. A passed network +The public case schemas are `simscene.passive_network.v1`, +`simscene.passive_network.v2`, and `simscene.passive_network.v3`. +The examples below use v1. Version 2 adds required typed support loads; +version 3 also requires exactly one explicit D6 rope assertion. For direct +Python calls to a v3 case use `simscene.verification.passive_network_v3`, or +use the existing schema-dispatching `run_verify` interface. A passed network contract covers its declared physical chain, counts, timing and controls. Asset discovery, the semantic review of household identities, native video quality, project export/replay and separate P1 mechanism contracts remain @@ -146,7 +151,7 @@ and independently inspected geometry, before observing a formal success. | Field | Contract | | --- | --- | -| `schema` | Exactly `simscene.passive_network.v1`. | +| `schema` | `simscene.passive_network.v1`; `simscene.passive_network.v2` for typed support loads; or `simscene.passive_network.v3` for a D6 rope and typed support loads. | | `profile` | `pilot`, `P2` or `P3`. A pilot never accepts a formal stage. | | `require_strict_initial_state` | Must be `true`; source `observation.strict_start` must also be `true`. | | `trigger_id`, `release_step` | One colliding dynamic sphere, scheduled at the declared step. All other dynamic bodies exist initially. | @@ -160,7 +165,8 @@ and independently inspected geometry, before observing a formal success. | `maximum_joint_anchor_error_m` | Global error limit for every enabled observed joint. | | `contact_window_tolerance_steps` | Frozen tolerance for event-window contact witnesses. | | `rope_body_ids` | Exact capsule-link IDs. Rope motion cannot supply activity time. | -| `mechanism_cases` | Optional mapping from assertion name to a complete frozen `simscene.mechanism.v1` contract, evaluated on the full original telemetry. | +| `mechanism_cases` | Frozen mechanism assertions evaluated on the full original telemetry; v3 requires exactly one `simscene.mechanism.v2` D6 rope assertion. | +| `structural_loads` | Required nonempty typed support declarations in v2 and v3, rejected in v1; see [typed support evidence](structural-loads-verification.md). | | `terminal` | Actual sugar dimensions, measured receiver interior and stability limits. | | `activity` | Frozen task stages/ROIs/speed floors plus all four timing limits. | | `controls`, `required_controls` | Explicit isolated interventions and their expected upstream/downstream behavior. | diff --git a/tests/agent/test_package.py b/tests/agent/test_package.py index 52f2f26..1333d14 100644 --- a/tests/agent/test_package.py +++ b/tests/agent/test_package.py @@ -94,7 +94,14 @@ async def check_independent_metadata(root,plugin): 'examples/usdcraft_sdk_guide/assets.lock.json', 'examples/usdcraft_sdk_guide/check_pair.py'): self.assertEqual((plugin/sample).read_bytes(),(ROOT/sample).read_bytes(),sample) + for original in (ROOT/'skills').rglob('*.md'): + reference=plugin/'skills'/original.relative_to(ROOT/'skills') + self.assertTrue(reference.is_file(),str(reference)) + self.assertEqual(reference.read_bytes(),original.read_bytes(), + f'{reference}: packaged skill differs from its source') for reference in (plugin/'skills').rglob('*.md'): + original=ROOT/'skills'/reference.relative_to(plugin/'skills') + self.assertTrue(original.is_file(),str(reference)) for link in re.findall(r'\]\(([^\s)]+)\)',reference.read_text()): target=link.split('#')[0] if not target or ':' in target:continue From 8c4af7637111326dabc233c41ee068b09a912faf Mon Sep 17 00:00:00 2001 From: shaoxiang <519517384@qq.com> Date: Tue, 17 Nov 2026 16:02:53 +0800 Subject: [PATCH 04/20] Document integration qualification baseline --- docs/validation/integration-release-matrix.md | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 docs/validation/integration-release-matrix.md diff --git a/docs/validation/integration-release-matrix.md b/docs/validation/integration-release-matrix.md new file mode 100644 index 0000000..621e0bd --- /dev/null +++ b/docs/validation/integration-release-matrix.md @@ -0,0 +1,22 @@ +# Integration capability and evidence scope + +The integration development line builds on `30852a39e9e0043ea4c798d31194a9480ce1088e`. +It is not the same build as the separate DyCraft authoring line: the two lines +have both used version `0.2.0.dev2`, so a version string alone is insufficient +to identify a package. Record the commit, wheel hash, installed module path, +worker, checker, and independent backend runtimes for each qualification. + +| Capability | Existing evidence at the integration baseline | Scope and remaining work | +| --- | --- | --- | +| USDCraft metadata and layout | Metadata-only catalog query; one single-hinge cabinet and three imported props in a measured layout | Explicit horizontal support and keepouts; proposal alone is not a physical verdict. | +| ArtVIP | One pinned door, explicit mass and drive repairs, driven run and no-drive control | One object and one scheduled hinge; neither all ArtVIP assets nor passive triggering are qualified. | +| USDCraft two-joint cabinet | One pinned three-link/two-slider asset; separate missing-second-drive control | One native graph and bounded scheduled drives; no independent payload interaction has yet been qualified. | +| USDCraft SDK | One trusted guide template; two prepared lengths and a CCD ball comparison | Isolated optional runtime, explicit static collision proxies, and a recorded density assumption. | +| Installed package | Portable, Claude and DeepSeek layouts build; the installed portable MCP applied an actual layout | The baseline package lacks the fixed cabinet example and has not demonstrated the complete installed MCP-to-Isaac workflow. | +| MobilityGen | Standalone fixed-route Jetbot pair | Experimental and outside the general scene job/MCP workflow; native velocity consistency is not verified. | +| DyCraft authoring | Separate development branch and its own recorded outcomes | Its earlier client qualifications remain incomplete; this integration line does not inherit them. | + +The recorded physical examples use Isaac Sim 6.2.0-rc.14 on the documented +Linux host. Prepared assets, callbacks and frame records must be checked for +each new run. Hashes support integrity comparisons; they are not signatures. +See [catalog capabilities](catalog-capabilities.md) for per-source conditions. From 4699765fa0743f6c123b08aa6ec9ad2c07777fe3 Mon Sep 17 00:00:00 2001 From: shaoxiang <519517384@qq.com> Date: Tue, 17 Nov 2026 16:10:26 +0800 Subject: [PATCH 05/20] Ship discoverable fixed integration recipes --- plugins/build.py | 8 ++- skills/build-scene/SKILL.md | 4 +- .../references/integration-workspace.md | 50 ++++++++++++++ src/simscene/mcp_server.py | 7 ++ src/simscene/recipes/data/fixed-examples.json | 65 +++++++++++++++++++ src/simscene/recipes/registry.py | 10 ++- tests/agent/test_package.py | 16 ++++- tests/test_integration_example_registry.py | 38 +++++++++++ 8 files changed, 193 insertions(+), 5 deletions(-) create mode 100644 skills/build-scene/references/integration-workspace.md create mode 100644 src/simscene/recipes/data/fixed-examples.json create mode 100644 tests/test_integration_example_registry.py diff --git a/plugins/build.py b/plugins/build.py index 4378796..fcf2fd8 100644 --- a/plugins/build.py +++ b/plugins/build.py @@ -42,10 +42,12 @@ def versions(root=ROOT): small pinned example recipes are included without model payloads. ''' EXAMPLE_DATA={ - 'artvip_door':('assets.lock.json','case.json','recipe.json','supplement.json'), + 'automatic_cabinet_layout':('assets.lock.json','case.json','recipe.json','supplemental-checks.json','check.py'), + 'artvip_door':('assets.lock.json','case.json','recipe.json','supplement.json','check.py'), 'usdcraft_two_drawer':('assets.lock.json','case.json','recipe.json','recipe-control.json'), 'usdcraft_sdk_guide':('assets.lock.json','case.json','recipe-short.json','recipe-long.json','check_pair.py'), } +EXAMPLE_HELPERS=('acquire_recipe_assets.py','apply_scene_recipe.py','freeze_recipe_case.py') def write(path, value): path.parent.mkdir(parents=True,exist_ok=True) path.write_text(json.dumps(value,indent=2)+'\n') @@ -165,12 +167,15 @@ def build(destination, use_installed_deps=False): for example,names in EXAMPLE_DATA.items(): target=portable/'examples'/example;target.mkdir(parents=True) for name in names:shutil.copyfile(ROOT/'examples'/example/name,target/name) + helper_root=portable/'experiments';helper_root.mkdir() + for name in EXAMPLE_HELPERS:shutil.copyfile(ROOT/'experiments'/name,helper_root/name) write(portable/'plugin.json',{'$schema':'https://agent-plugins.org/schemas/1.0.0/plugin.schema.json','name':'simscene','version':PACKAGE_VERSION,'description':'Discover assets, compose and run experimental simulation scenes.'}) write(portable/'mcp.json',{'$schema':'https://agent-plugins.org/schemas/1.0.0/mcp.schema.json','mcpServers':{'simscene':{'type':'stdio','command':'python3','args':['${PLUGIN_ROOT}/server/launch.py'],'cwd':'${PLUGIN_ROOT}'}}}) claude.mkdir(parents=True) shutil.copytree(portable/'server',claude/'server') shutil.copytree(portable/'skills',claude/'skills') shutil.copytree(portable/'examples',claude/'examples') + shutil.copytree(portable/'experiments',claude/'experiments') shutil.copyfile(portable/'README.md',claude/'README.md') for notice in ('LICENSE','NOTICE','OPEN_SOURCE_NOTICES.md'): shutil.copyfile(portable/notice,claude/notice) @@ -180,6 +185,7 @@ def build(destination, use_installed_deps=False): shutil.copytree(portable/'server',deepseek/'server') shutil.copytree(portable/'skills',deepseek/'skills') shutil.copytree(portable/'examples',deepseek/'examples') + shutil.copytree(portable/'experiments',deepseek/'experiments') shutil.copyfile(portable/'README.md',deepseek/'README.md') for notice in ('LICENSE','NOTICE','OPEN_SOURCE_NOTICES.md'): shutil.copyfile(portable/notice,deepseek/notice) diff --git a/skills/build-scene/SKILL.md b/skills/build-scene/SKILL.md index b32b03f..d0ff9d0 100644 --- a/skills/build-scene/SKILL.md +++ b/skills/build-scene/SKILL.md @@ -5,7 +5,9 @@ description: Discover online simulation assets, compose editable scenes with mea Choose reproduction, modification or original construction first. Reproduce a locked recipe directly; test changed interfaces locally; build new mechanisms -on a small bench before assembling the full scene. For editable parameter +on a small bench before assembling the full scene. For the installed fixed +cabinet, ArtVIP, two-drawer and SDK examples, read +[fixed integration examples](references/integration-workspace.md). For editable parameter modules, compact first-handoff diagnosis and machine-side waiting, read [passive production](references/passive-production.md). Use its scripts when they remove repeated geometry or log-reading work; unsupported cases remain diff --git a/skills/build-scene/references/integration-workspace.md b/skills/build-scene/references/integration-workspace.md new file mode 100644 index 0000000..16a7cbb --- /dev/null +++ b/skills/build-scene/references/integration-workspace.md @@ -0,0 +1,50 @@ +# Fixed integration examples + +Read `simscene://recipes/examples` or `simscene recipe list` to discover four +model-free examples. These are fixed scene inputs, separate from the role +recipes accepted by `scene_compile_recipe`. The registry describes earlier +evidence for selected configurations; it is not a pass for a new run. + +Choose the closest path: + +* **Reproduce:** use `automatic_cabinet_layout` for the single-hinge USDCraft + cabinet, two ABO notebook instances and one GSO box. The lock pins source + revisions, preparation parameters and experimental 0.12 kg prop masses; + the case and supplemental checks fix the earlier 600-step/60 Hz predicates. +* **Modify:** keep the selected source and role bindings, measure the actual + support and motion keepout, then freeze a new case and run the changed scene. + A changed asset, placement, drive or preparation cannot inherit an old pass. +* **Explore:** make a small physical test first. A manifest's joint count, + generator output or geometrically feasible layout does not establish motion, + support, stability or a contact-triggered event. + +Other examples cover one explicitly repaired `artvip_door`, the scheduled +`usdcraft_two_drawer` with its missing-second-drive control, and the optional +`usdcraft_sdk_guide` two-size comparison. Their locks and case files record +the exact assumptions. They do not certify every object in those sources. + +The package root is the value in a copied project's +`build-scene/.simscene-plugin-root`; otherwise use the root that contains +`server/`, `skills/` and `examples/`. Each `examples//` contains the +listed lock, ordinary operations, case and checker. Source model payloads are +not bundled. Search metadata with `catalog_search`, then use `asset_plan` and +`asset_prepare` only for selected assets; retain the returned job IDs and +prepared bindings. Record transfer categories rather than assuming a warm +cache proves a cold download. Check per-asset license and missing dependencies. + +For shell-capable clients, the installed package also contains the same small +helpers as the source tree: `experiments/acquire_recipe_assets.py`, +`experiments/apply_scene_recipe.py` and `experiments/freeze_recipe_case.py`. +Run them with the matching `server/vendor` first on `PYTHONPATH` and a host +Python with the required USD bindings. The acquire helper invokes the ordinary +durable jobs directly; a workflow specifically requiring MCP coverage must +perform and record those corresponding MCP calls instead. The helpers do not +turn preparation or scene construction into a physical acceptance. + +After applying operations at the current scene revision, measure the resulting +world bounds, preserve collisions and reserve the mechanism's working region. +Freeze the case against the new bindings before `simulation_start`, wait for +the same durable job, inspect real frames and observations, then run the +appropriate checker with the same installed package and USD environment. +Archive the case, inputs, physical result, video mapping and an actual visual +review. Scheduled commands are not evidence of contact-triggered motion. diff --git a/src/simscene/mcp_server.py b/src/simscene/mcp_server.py index 99ee11d..c2d5d58 100644 --- a/src/simscene/mcp_server.py +++ b/src/simscene/mcp_server.py @@ -75,6 +75,13 @@ def catalog_sources_resource() -> str: from .catalog.service import sources return json.dumps(sources(),ensure_ascii=False) +@server.resource('simscene://recipes/examples') +def fixed_examples_resource() -> str: + """List pinned example inputs and prior-evidence scope without starting physics.""" + import json + from .recipes.registry import list_examples + return json.dumps(list_examples(),ensure_ascii=False) + @threaded_tool(annotations=_read_local) def environment_probe() -> dict: """Inspect configured runtime and GPU without starting Isaac Sim.""" diff --git a/src/simscene/recipes/data/fixed-examples.json b/src/simscene/recipes/data/fixed-examples.json new file mode 100644 index 0000000..706b146 --- /dev/null +++ b/src/simscene/recipes/data/fixed-examples.json @@ -0,0 +1,65 @@ +{ + "schema": "simscene.fixed_examples.v1", + "examples": [ + { + "id": "automatic_cabinet_layout", + "description": "Measured worktable layout with one scheduled USDCraft hinge, two ABO notebooks and one GSO box.", + "asset_sources": ["usdcraft", "abo-glb", "gso-glb"], + "profiles": ["articulated_prop_v1", "rigid_prop_v1"], + "asset_lock": "assets.lock.json", + "operations": ["recipe.json"], + "case": "case.json", + "checker": "check.py", + "steps": 600, + "seed": 42, + "runtime_evidence": "prior_example_only", + "requires_new_physical_verification": true, + "scope": "One fixed placement and scheduled drive; 0.12 kg prop masses and measured scaling are experimental." + }, + { + "id": "artvip_door", + "description": "One ArtVIP door with explicitly repaired mass and bounded scheduled hinge drive.", + "asset_sources": ["artvip"], + "profiles": ["articulated_prop_v1"], + "asset_lock": "assets.lock.json", + "operations": ["recipe.json"], + "case": "case.json", + "checker": "check.py", + "steps": 600, + "seed": 42, + "runtime_evidence": "prior_example_only", + "requires_new_physical_verification": true, + "scope": "One door; experimental mass overrides source density and the original drive is neutralized." + }, + { + "id": "usdcraft_two_drawer", + "description": "One USDCraft cabinet with two scheduled slider joints and a missing-second-drive control.", + "asset_sources": ["usdcraft"], + "profiles": ["articulated_prop_v2"], + "asset_lock": "assets.lock.json", + "operations": ["recipe.json", "recipe-control.json"], + "case": "case.json", + "checker": "builtin:simscene verify", + "steps": 600, + "seed": 42, + "runtime_evidence": "prior_example_only", + "requires_new_physical_verification": true, + "scope": "One three-link/two-slider graph; no payload or passive contact triggering is claimed." + }, + { + "id": "usdcraft_sdk_guide", + "description": "Two generated guide lengths prepared as static box proxies for a falling-ball comparison.", + "asset_sources": ["local-usdcraft-sdk"], + "profiles": ["static_fixture_v1"], + "asset_lock": "assets.lock.json", + "operations": ["recipe-short.json", "recipe-long.json"], + "case": "case.json", + "checker": "check_pair.py", + "steps": 360, + "seed": 17, + "runtime_evidence": "prior_example_only", + "requires_new_physical_verification": true, + "scope": "Reviewed optional SDK runtime, fixed generator template and experimental static collision proxies." + } + ] +} diff --git a/src/simscene/recipes/registry.py b/src/simscene/recipes/registry.py index ec328ea..72ea79b 100644 --- a/src/simscene/recipes/registry.py +++ b/src/simscene/recipes/registry.py @@ -4,7 +4,15 @@ def list_recipes(): - return json.loads(files('simscene.recipes').joinpath('data/recipes.json').read_text()) + result = json.loads(files('simscene.recipes').joinpath('data/recipes.json').read_text()) + # Fixed examples are separate from role recipes accepted by compile_recipe. + result['fixed_examples'] = list_examples()['examples'] + return result + + +def list_examples(): + """List model-free, pinned example inputs; this never asserts a new run passed.""" + return json.loads(files('simscene.recipes').joinpath('data/fixed-examples.json').read_text()) def get_recipe(recipe_id): diff --git a/tests/agent/test_package.py b/tests/agent/test_package.py index 1333d14..dd97aaf 100644 --- a/tests/agent/test_package.py +++ b/tests/agent/test_package.py @@ -62,6 +62,9 @@ async def check_independent_metadata(root,plugin): self.assertTrue({'catalog_search','asset_plan','asset_prepare','catalog_discover','asset_generate','scene_compile_recipe','scene_plan_layout'}<=names) response=await session.read_resource('simscene://catalog/sources') self.assertTrue(json.loads(response.contents[0].text)['sources']) + response=await session.read_resource('simscene://recipes/examples') + examples=json.loads(response.contents[0].text)['examples'] + self.assertIn('automatic_cabinet_layout',{entry['id'] for entry in examples}) response=await session.call_tool('catalog_search',{'query':'Original package fixture','filters':{'source_ids':['abo-glb']},'limit':1}) self.assertFalse(response.isError,str(response)) page=json.loads(response.content[0].text);self.assertEqual(len(page['items']),1) @@ -89,10 +92,19 @@ async def check_independent_metadata(root,plugin): stage=root/kind;stage.mkdir() plugin=output/kind/'simscene' self.assertTrue((plugin/'README.md').is_file()) - for sample in ('examples/artvip_door/assets.lock.json', + for sample in ('examples/automatic_cabinet_layout/assets.lock.json', + 'examples/automatic_cabinet_layout/recipe.json', + 'examples/automatic_cabinet_layout/case.json', + 'examples/automatic_cabinet_layout/supplemental-checks.json', + 'examples/automatic_cabinet_layout/check.py', + 'examples/artvip_door/assets.lock.json', + 'examples/artvip_door/check.py', 'examples/usdcraft_two_drawer/case.json', 'examples/usdcraft_sdk_guide/assets.lock.json', - 'examples/usdcraft_sdk_guide/check_pair.py'): + 'examples/usdcraft_sdk_guide/check_pair.py', + 'experiments/acquire_recipe_assets.py', + 'experiments/apply_scene_recipe.py', + 'experiments/freeze_recipe_case.py'): self.assertEqual((plugin/sample).read_bytes(),(ROOT/sample).read_bytes(),sample) for original in (ROOT/'skills').rglob('*.md'): reference=plugin/'skills'/original.relative_to(ROOT/'skills') diff --git a/tests/test_integration_example_registry.py b/tests/test_integration_example_registry.py new file mode 100644 index 0000000..4f436d7 --- /dev/null +++ b/tests/test_integration_example_registry.py @@ -0,0 +1,38 @@ +"""Fixed examples must be discoverable without claiming a new physics pass.""" +from pathlib import Path + +from simscene.recipes import registry + + +ROOT = Path(__file__).resolve().parents[1] + + +def test_fixed_examples_are_separate_from_compilable_role_recipes(): + assert hasattr(registry, 'list_examples'), 'fixed example registry is not available' + listing = registry.list_examples() + assert listing['schema'] == 'simscene.fixed_examples.v1' + examples = {entry['id']: entry for entry in listing['examples']} + assert set(examples) == {'automatic_cabinet_layout', 'artvip_door', + 'usdcraft_two_drawer', 'usdcraft_sdk_guide'} + assert examples['automatic_cabinet_layout']['asset_sources'] == ['usdcraft', 'abo-glb', 'gso-glb'] + assert examples['automatic_cabinet_layout']['runtime_evidence'] == 'prior_example_only' + assert examples['automatic_cabinet_layout']['operations'] == ['recipe.json'] + assert examples['usdcraft_two_drawer']['operations'] == ['recipe.json', 'recipe-control.json'] + assert all(entry['requires_new_physical_verification'] is True for entry in examples.values()) + assert all(entry['id'] not in {item['recipe_id'] for item in registry.list_recipes()['recipes']} + for entry in examples.values()) + assert registry.list_recipes()['fixed_examples'] == listing['examples'] + for entry in examples.values(): + directory = ROOT / 'examples' / entry['id'] + for name in [entry['asset_lock'], entry['case'], *entry['operations'], entry['checker']]: + if name.startswith('builtin:'): + continue + assert Path(name).name == name + assert (directory / name).is_file(), (entry['id'], name) + + +def test_fixed_example_resource_returns_registry_data(): + from simscene import mcp_server + import json + assert hasattr(mcp_server, 'fixed_examples_resource') + assert json.loads(mcp_server.fixed_examples_resource()) == registry.list_examples() From 179bd826987a62706c47b1938ebd406ce5e2ae6e Mon Sep 17 00:00:00 2001 From: shaoxiang <519517384@qq.com> Date: Tue, 17 Nov 2026 16:40:25 +0800 Subject: [PATCH 06/20] Preflight measured articulation motion clearances --- docs/scene-layout.md | 39 ++ experiments/check_motion_clearance.py | 33 ++ plugins/build.py | 2 +- .../references/integration-workspace.md | 18 +- src/simscene/layout_synthesis.py | 15 +- src/simscene/recipes/data/fixed-examples.json | 2 + .../recipes/data/known-motion-geometry.json | 367 ++++++++++++++++++ src/simscene/recipes/motion_keepouts.py | 215 ++++++++++ tests/agent/test_package.py | 3 +- tests/test_motion_keepouts.py | 144 +++++++ 10 files changed, 834 insertions(+), 4 deletions(-) create mode 100644 experiments/check_motion_clearance.py create mode 100644 src/simscene/recipes/data/known-motion-geometry.json create mode 100644 src/simscene/recipes/motion_keepouts.py create mode 100644 tests/test_motion_keepouts.py diff --git a/docs/scene-layout.md b/docs/scene-layout.md index c117fd5..bc201e5 100644 --- a/docs/scene-layout.md +++ b/docs/scene-layout.md @@ -83,3 +83,42 @@ placing partial results. Render bounds are not the collision geometry or a stability certificate. `physics_tested` remains false. Check actual USD bindings, collider clearance, joint travel, contacts, and settling in a fresh Isaac run using a frozen case. + +## Motion envelopes for two pinned examples + +The installed examples provide source-specific profiles +`usdcraft_lift_cabinet_v1` and `usdcraft_two_drawer_v1`. Their recorded +owner-local geometry comes from the selected source's zero-state child bounds, +including its collision geometry. The hinge uses a conservative full-turn +cylindrical enclosure, including intermediate positions; the drawers use the +entire native slider limits along the transformed native axes. These envelopes +can reject feasible placements and do not account for future parent drift or +constraint failure. They are not automatically inferred for arbitrary joints. + +After acquiring and preparing the matching asset, save the current `scene_get` +result to a new JSON file. For an installed portable package, use its matching +vendored SimScene code and the host's USD Python bindings: + +```bash +PYTHONPATH="$SIMSCENE_PLUGIN_ROOT/server/vendor" python3 \ + "$SIMSCENE_PLUGIN_ROOT/experiments/check_motion_clearance.py" \ + --scene /your/current-scene.json --owner cabinet \ + --profile usdcraft_lift_cabinet_v1 --output /your/new-keepout.json +``` + +With no `--object` arguments the result is `not_checked`: its `keepout_bounds` +are inputs to `scene_plan_layout`, not an acceptance verdict. Use +`clearance_m: 0.05` in the planner. After applying at the returned revision, +save a fresh `scene_get` result and repeat the command with `--object box` +and one `--object` for each other external prop, writing a new output file. +`clear` means only those render bounds cleared the qualified geometry; +`conflict` names the object and joint. The owner is excluded from its own +keepout. Unknown sources, changed native joint/collider metadata, unsafe owner +overrides and missing geometry fail instead of being reported as clear. The +result pins the scene content and revision, profile, and prepared manifest. + +The primitive-box support's declared region must be on and within its actual +top; invalid support height or extent is rejected before sampling. A declared +region on an imported support still requires inspection of its actual prepared +colliders. Neither a clear keepout nor a valid support replaces a fresh physical +run, observed contacts or stability checks. diff --git a/experiments/check_motion_clearance.py b/experiments/check_motion_clearance.py new file mode 100644 index 0000000..9f6a831 --- /dev/null +++ b/experiments/check_motion_clearance.py @@ -0,0 +1,33 @@ +"""Check known pinned motion envelopes against a saved current scene.""" +import argparse +import json +from pathlib import Path + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--scene', required=True, help='JSON saved from the current scene') + parser.add_argument('--owner', required=True, help='prepared articulated object ID') + parser.add_argument('--profile', required=True, help='known source-specific motion profile') + parser.add_argument('--object', action='append', default=[], help='external object ID; repeat as needed') + parser.add_argument('--clearance-m', type=float, default=.05) + parser.add_argument('--output', required=True, help='new JSON output path') + args = parser.parse_args(argv) + from simscene.recipes.motion_keepouts import check_motion_clearance + from simscene.scene import SceneError + try: + scene = json.loads(Path(args.scene).read_text()) + report = check_motion_clearance(scene, args.owner, args.profile, args.object, args.clearance_m) + except (SceneError, ValueError, TypeError, KeyError, OSError) as error: + report = {'schema': 'simscene.motion_clearance.v1', 'status': 'error', + 'error': str(error), 'physics_tested': False} + with Path(args.output).open('x', encoding='utf8') as stream: + json.dump(report, stream, indent=2, allow_nan=False) + stream.write('\n') + print(json.dumps({'status': report['status'], 'output': args.output, + 'physics_tested': False}, ensure_ascii=False)) + return 1 if report['status'] == 'error' else 2 if report['status'] == 'conflict' else 0 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/plugins/build.py b/plugins/build.py index fcf2fd8..0af6775 100644 --- a/plugins/build.py +++ b/plugins/build.py @@ -47,7 +47,7 @@ def versions(root=ROOT): 'usdcraft_two_drawer':('assets.lock.json','case.json','recipe.json','recipe-control.json'), 'usdcraft_sdk_guide':('assets.lock.json','case.json','recipe-short.json','recipe-long.json','check_pair.py'), } -EXAMPLE_HELPERS=('acquire_recipe_assets.py','apply_scene_recipe.py','freeze_recipe_case.py') +EXAMPLE_HELPERS=('acquire_recipe_assets.py','apply_scene_recipe.py','freeze_recipe_case.py','check_motion_clearance.py') def write(path, value): path.parent.mkdir(parents=True,exist_ok=True) path.write_text(json.dumps(value,indent=2)+'\n') diff --git a/skills/build-scene/references/integration-workspace.md b/skills/build-scene/references/integration-workspace.md index 16a7cbb..a6a008a 100644 --- a/skills/build-scene/references/integration-workspace.md +++ b/skills/build-scene/references/integration-workspace.md @@ -34,13 +34,29 @@ cache proves a cold download. Check per-asset license and missing dependencies. For shell-capable clients, the installed package also contains the same small helpers as the source tree: `experiments/acquire_recipe_assets.py`, -`experiments/apply_scene_recipe.py` and `experiments/freeze_recipe_case.py`. +`experiments/apply_scene_recipe.py`, `experiments/freeze_recipe_case.py` and +`experiments/check_motion_clearance.py`. Run them with the matching `server/vendor` first on `PYTHONPATH` and a host Python with the required USD bindings. The acquire helper invokes the ordinary durable jobs directly; a workflow specifically requiring MCP coverage must perform and record those corresponding MCP calls instead. The helpers do not turn preparation or scene construction into a physical acceptance. +For the USDCraft hinge or two-drawer examples, the registry names a specific +`motion_profile`. Save the current `scene_get` result and call the packaged +`check_motion_clearance.py` with that scene, owner ID, profile and a new output +path. The matching vendor directory must be first on `PYTHONPATH`. With no +`--object` arguments the result is `not_checked` and provides conservative +world `keepout_bounds`; pass those bounds to `scene_plan_layout` with 0.05 m +clearance. For the unchanged fixed cabinet pose, the example's larger +`supplemental-checks.json` `reserved_volume` also encloses that calculated +envelope; verify containment before reusing it to reproduce the original seed +and placement. After applying its operations, save the new scene and call the helper +again with each external object as a repeated `--object` argument. Stop if the +result is `conflict` or `error`; the owner is deliberately excluded. The result +pins the scene content and revision, the prepared source and the measured +profile. Changed joint or collider geometry is unsupported, not silently clear. + After applying operations at the current scene revision, measure the resulting world bounds, preserve collisions and reserve the mechanism's working region. Freeze the case against the new bindings before `simulation_start`, wait for diff --git a/src/simscene/layout_synthesis.py b/src/simscene/layout_synthesis.py index 5da2efd..a6e972a 100644 --- a/src/simscene/layout_synthesis.py +++ b/src/simscene/layout_synthesis.py @@ -16,7 +16,7 @@ import threading import time -from .placement import bounds, place_on, rotate, surface, vector +from .placement import bounds, place_on, rotate, surface, validate_surfaces, vector from .scene import SceneError, validate @@ -224,6 +224,19 @@ def primitive_has_collider(obj): if support in item_exclusions or name in support_exclusions: raise SceneError('layout support and dynamic object have collision exclusions: ' + name) region, orientation, position = surface(objects[support], support_surface) + try: + validate_surfaces({'selected': region}) + except (ValueError, TypeError, KeyError) as error: + raise SceneError('invalid support surface: ' + str(error)) from error + if support_obj.get('kind') == 'box': + size = support_obj.get('size', [1, 1, 1]) + if not vector(size) or any(value <= 0 for value in size): + raise SceneError('primitive support extent must be finite and positive') + if abs(region['z_m'] - size[2] / 2) > 1e-6: + raise SceneError('primitive support height must coincide with its box top') + if any(region['min_xy'][i] < -size[i] / 2 - 1e-6 or + region['max_xy'][i] > size[i] / 2 + 1e-6 for i in range(2)): + raise SceneError('primitive support extent exceeds its box top') if any(objects[name].get('rigid_attachment') for name in ids): raise SceneError('arrange physical parents rather than attached visuals') center = [(region['min_xy'][i] + region['max_xy'][i]) / 2 for i in range(2)] diff --git a/src/simscene/recipes/data/fixed-examples.json b/src/simscene/recipes/data/fixed-examples.json index 706b146..f2ce0cb 100644 --- a/src/simscene/recipes/data/fixed-examples.json +++ b/src/simscene/recipes/data/fixed-examples.json @@ -10,6 +10,7 @@ "operations": ["recipe.json"], "case": "case.json", "checker": "check.py", + "motion_profile": "usdcraft_lift_cabinet_v1", "steps": 600, "seed": 42, "runtime_evidence": "prior_example_only", @@ -40,6 +41,7 @@ "operations": ["recipe.json", "recipe-control.json"], "case": "case.json", "checker": "builtin:simscene verify", + "motion_profile": "usdcraft_two_drawer_v1", "steps": 600, "seed": 42, "runtime_evidence": "prior_example_only", diff --git a/src/simscene/recipes/data/known-motion-geometry.json b/src/simscene/recipes/data/known-motion-geometry.json new file mode 100644 index 0000000..cb1024c --- /dev/null +++ b/src/simscene/recipes/data/known-motion-geometry.json @@ -0,0 +1,367 @@ +{ + "schema": "simscene.known_motion_geometry.v1", + "profiles": { + "usdcraft_lift_cabinet_v1": { + "qualification_manifest": { + "source_ref": { + "asset_id": "ds_R021_02", + "revision": "92f4e908415d7532a02661d6502ab49dc3aa33f9", + "source_id": "usdcraft", + "variant_id": null + }, + "source_sha256": "72dbc3b8479048ff07b838a951c4dd58617eeddc8668a861415a5ca087f32be5", + "profile_id": "articulated_prop_v1", + "parameters": { + "collision_method": "preserve", + "scale_mode": "preserve", + "source_physics_policy": "preserve_valid" + }, + "joint_map": { + "main": { + "relative_prim_path": "Native/Joints/flap_hinge", + "type": "revolute", + "axis": "X", + "limits": [ + 0.0, + 1.3962634015954636 + ], + "parent_body_id": "link0", + "child_body_id": "link1", + "local_pos0_m": [ + 0.0, + -0.17499999701976776, + 0.39800000190734863 + ], + "local_rot0_wxyz": [ + 6.123234262925839e-17, + 0.0, + 0.0, + 1.0 + ] + } + }, + "body_map": { + "link1": { + "relative_prim_path": "Native/Links/flap_door", + "collider_relative_prim_paths": [ + "Native/Links/flap_door/Collisions/flap_panel/Geom/flap_door_with_handle_recess_obj", + "Native/Links/flap_door/Collisions/handle_bar/GeomHull" + ] + }, + "link0": { + "relative_prim_path": "Native/Links/cabinet_carcass", + "collider_relative_prim_paths": [ + "Native/Links/cabinet_carcass/Collisions/left_side/Geom", + "Native/Links/cabinet_carcass/Collisions/right_side/Geom", + "Native/Links/cabinet_carcass/Collisions/top_panel/Geom", + "Native/Links/cabinet_carcass/Collisions/bottom_panel/Geom", + "Native/Links/cabinet_carcass/Collisions/back_panel/Geom", + "Native/Links/cabinet_carcass/Collisions/interior_shelf/Geom" + ] + } + } + }, + "motions": [ + { + "joint_id": "main", + "kind": "revolute", + "axis_owner": [ + -1.0, + 1.2246468525851679e-16, + 0.0 + ], + "pivot_owner_m": [ + 0.0, + -0.17499999701976776, + 0.39800000190734874 + ], + "limits": [ + 0.0, + 1.3962634015954636 + ], + "parent_transform_owner": [ + [ + 1.0, + 0.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0, + 0.0 + ], + [ + 0.0, + 0.0, + 0.0, + 1.0 + ] + ], + "initial_child_bounds_owner_m": { + "min": [ + -0.4480100138282776, + -0.19300999922513962, + 0.0019900021457672323 + ], + "max": [ + 0.4480100138282776, + -0.17498999999999998, + 0.39801000000000003 + ] + } + } + ], + "basis": { + "source_scene_sha256": "b89511596ba182e2868ea21182502b5b62a580babd6d978e1a15b459e47f53fc", + "coordinate_frame": "unscaled owner-local metres, authored zero joint state", + "bounds": "USD initial child render and collider bounds including guide purpose, expanded by 10 micrometres", + "revolute_sweep": "full-turn cylindrical enclosure; covers all intermediate angles", + "prismatic_sweep": "entire native joint-limit interval along transformed native axis", + "not_proved": "future joint integrity, parent drift, collider penetration or dynamic stability" + } + }, + "usdcraft_two_drawer_v1": { + "qualification_manifest": { + "source_ref": { + "asset_id": "ds_R022_02", + "revision": "92f4e908415d7532a02661d6502ab49dc3aa33f9", + "source_id": "usdcraft", + "variant_id": null + }, + "source_sha256": "e5070e0690c183629f0d24d2465d5ff0b53b88cd71b3682200650e05e009c7d0", + "profile_id": "articulated_prop_v2", + "parameters": { + "collision_method": "preserve", + "scale_mode": "preserve", + "source_physics_policy": "preserve_valid" + }, + "joint_map": { + "joint0": { + "relative_prim_path": "Native/Joints/slide_lower", + "type": "prismatic", + "axis": "X", + "limits": [ + 0.0, + 0.5 + ], + "parent_body_id": "link0", + "child_body_id": "link1", + "local_pos0_m": [ + 0.0, + -0.23999999463558197, + 0.2800000011920929 + ], + "local_rot0_wxyz": [ + 0.7071067690849304, + 0.0, + 0.0, + -0.7071067690849304 + ] + }, + "joint1": { + "relative_prim_path": "Native/Joints/slide_upper", + "type": "prismatic", + "axis": "X", + "limits": [ + 0.0, + 0.5 + ], + "parent_body_id": "link0", + "child_body_id": "link2", + "local_pos0_m": [ + 0.0, + -0.23999999463558197, + 0.6299999952316284 + ], + "local_rot0_wxyz": [ + 0.7071067690849304, + 0.0, + 0.0, + -0.7071067690849304 + ] + } + }, + "body_map": { + "link1": { + "relative_prim_path": "Native/Links/lower_drawer", + "collider_relative_prim_paths": [ + "Native/Links/lower_drawer/Collisions/box_back/Geom", + "Native/Links/lower_drawer/Collisions/box_bottom/Geom", + "Native/Links/lower_drawer/Collisions/box_left/Geom", + "Native/Links/lower_drawer/Collisions/box_right/Geom", + "Native/Links/lower_drawer/Collisions/drawer_front/Geom", + "Native/Links/lower_drawer/Collisions/handle_bar/GeomHull", + "Native/Links/lower_drawer/Collisions/handle_post_left/GeomHull", + "Native/Links/lower_drawer/Collisions/handle_post_right/GeomHull", + "Native/Links/lower_drawer/Collisions/inner_front_rail/Geom", + "Native/Links/lower_drawer/Collisions/runner_left/Geom", + "Native/Links/lower_drawer/Collisions/runner_right/Geom" + ] + }, + "link0": { + "relative_prim_path": "Native/Links/carcass", + "collider_relative_prim_paths": [ + "Native/Links/carcass/Collisions/back_panel/Geom", + "Native/Links/carcass/Collisions/bottom_panel/Geom", + "Native/Links/carcass/Collisions/divider_board/Geom", + "Native/Links/carcass/Collisions/left_side/Geom", + "Native/Links/carcass/Collisions/plinth_back/Geom", + "Native/Links/carcass/Collisions/plinth_front/Geom", + "Native/Links/carcass/Collisions/plinth_left/Geom", + "Native/Links/carcass/Collisions/plinth_right/Geom", + "Native/Links/carcass/Collisions/right_side/Geom", + "Native/Links/carcass/Collisions/stone_top/Geom", + "Native/Links/carcass/Collisions/top_panel/Geom" + ] + }, + "link2": { + "relative_prim_path": "Native/Links/upper_drawer", + "collider_relative_prim_paths": [ + "Native/Links/upper_drawer/Collisions/box_back/Geom", + "Native/Links/upper_drawer/Collisions/box_bottom/Geom", + "Native/Links/upper_drawer/Collisions/box_left/Geom", + "Native/Links/upper_drawer/Collisions/box_right/Geom", + "Native/Links/upper_drawer/Collisions/drawer_front/Geom", + "Native/Links/upper_drawer/Collisions/handle_bar/GeomHull", + "Native/Links/upper_drawer/Collisions/handle_post_left/GeomHull", + "Native/Links/upper_drawer/Collisions/handle_post_right/GeomHull", + "Native/Links/upper_drawer/Collisions/inner_front_rail/Geom", + "Native/Links/upper_drawer/Collisions/runner_left/Geom", + "Native/Links/upper_drawer/Collisions/runner_right/Geom" + ] + } + } + }, + "motions": [ + { + "joint_id": "joint0", + "kind": "prismatic", + "axis_owner": [ + 0.0, + -1.0, + 0.0 + ], + "pivot_owner_m": [ + 0.0, + -0.23999999463558197, + 0.2800000011920929 + ], + "limits": [ + 0.0, + 0.5 + ], + "parent_transform_owner": [ + [ + 1.0, + 0.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0, + 0.0 + ], + [ + 0.0, + 0.0, + 0.0, + 1.0 + ] + ], + "initial_child_bounds_owner_m": { + "min": [ + -0.4470099969005585, + -0.30001000037997966, + 0.1049899928474426 + ], + "max": [ + 0.4470099969005585, + 0.27201001215934756, + 0.46501000715255736 + ] + } + }, + { + "joint_id": "joint1", + "kind": "prismatic", + "axis_owner": [ + 0.0, + -1.0, + 0.0 + ], + "pivot_owner_m": [ + 0.0, + -0.23999999463558197, + 0.6299999952316284 + ], + "limits": [ + 0.0, + 0.5 + ], + "parent_transform_owner": [ + [ + 1.0, + 0.0, + 0.0, + 0.0 + ], + [ + 0.0, + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0, + 0.0 + ], + [ + 0.0, + 0.0, + 0.0, + 1.0 + ] + ], + "initial_child_bounds_owner_m": { + "min": [ + -0.4470099969005585, + -0.30001000037997966, + 0.46998999925494195 + ], + "max": [ + 0.4470099969005585, + 0.27201001215934756, + 0.8350100071525574 + ] + } + } + ], + "basis": { + "source_scene_sha256": "ce479751b8358e39fd37c5b24c6000e788189924d4db5b2efd09567027008eaa", + "coordinate_frame": "unscaled owner-local metres, authored zero joint state", + "bounds": "USD initial child render and collider bounds including guide purpose, expanded by 10 micrometres", + "revolute_sweep": "full-turn cylindrical enclosure; covers all intermediate angles", + "prismatic_sweep": "entire native joint-limit interval along transformed native axis", + "not_proved": "future joint integrity, parent drift, collider penetration or dynamic stability" + } + } + } +} diff --git a/src/simscene/recipes/motion_keepouts.py b/src/simscene/recipes/motion_keepouts.py new file mode 100644 index 0000000..cb8a7f1 --- /dev/null +++ b/src/simscene/recipes/motion_keepouts.py @@ -0,0 +1,215 @@ +"""Conservative, source-pinned motion envelopes for two measured examples. + +These are geometric preflights, not general joint inference or a physics pass. +""" +import hashlib +from importlib.resources import files +import itertools +import json +import math + +from ..placement import bounds, intersects, rotate, vector +from ..scene import SceneError + + +def _number(value): + return type(value) in (int, float) and math.isfinite(value) + + +def _box(value): + return (isinstance(value, dict) and set(value) == {'min', 'max'} + and vector(value['min']) and vector(value['max']) + and all(a < b for a, b in zip(value['min'], value['max']))) + + +def swept_local_bounds(kind, initial_bounds, axis, limits, pivot=None): + """Enclose every pose of a known rigid child, in unscaled owner-local metres. + + A revolute joint uses a full-turn cylinder, so intermediate positions are + enclosed even when endpoints alone would miss them. A prismatic joint uses + the union along the full supplied translation interval. The input bounds + must enclose the child's actual initial geometry at joint coordinate zero. + """ + if not _box(initial_bounds): + raise SceneError('motion geometry requires finite nonempty initial bounds') + if not vector(axis) or abs(sum(v * v for v in axis) - 1.) > 1e-5: + raise SceneError('motion axis must be a finite unit vector') + if (not isinstance(limits, list) or len(limits) != 2 or + not all(_number(v) for v in limits) or limits[0] > limits[1] or + not limits[0] <= 0 <= limits[1]): + raise SceneError('motion limits must be finite, ordered, and contain the measured zero state') + length = math.sqrt(sum(v * v for v in axis)) + unit = [v / length for v in axis] + if kind == 'prismatic': + return {'min': [initial_bounds['min'][i] + min(unit[i] * q for q in limits) for i in range(3)], + 'max': [initial_bounds['max'][i] + max(unit[i] * q for q in limits) for i in range(3)]} + if kind != 'revolute' or not vector(pivot): + raise SceneError('unsupported motion geometry or missing revolute pivot') + projections, radii = [], [] + for point in itertools.product(*[(initial_bounds['min'][i], initial_bounds['max'][i]) for i in range(3)]): + delta = [point[i] - pivot[i] for i in range(3)] + along = sum(delta[i] * unit[i] for i in range(3)) + projections.append(along) + radii.append(math.sqrt(sum((delta[i] - along * unit[i]) ** 2 for i in range(3)))) + lo, hi, radius = min(projections), max(projections), max(radii) + radial = [radius * math.sqrt(max(0., 1. - unit[i] ** 2)) for i in range(3)] + return {'min': [pivot[i] + min(lo * unit[i], hi * unit[i]) - radial[i] for i in range(3)], + 'max': [pivot[i] + max(lo * unit[i], hi * unit[i]) + radial[i] for i in range(3)]} + + +def load_profile(profile_id): + raw = files('simscene.recipes').joinpath('data/known-motion-geometry.json').read_bytes() + data = json.loads(raw) + if (not isinstance(profile_id, str) or data.get('schema') != 'simscene.known_motion_geometry.v1' + or profile_id not in data.get('profiles', {})): + raise SceneError('unknown or unsupported motion geometry profile') + return data['profiles'][profile_id] + + +def _contains(actual, required): + if isinstance(required, dict): + return isinstance(actual, dict) and all(key in actual and _contains(actual[key], value) + for key, value in required.items()) + if isinstance(required, list): + return isinstance(actual, list) and len(actual) == len(required) and all( + _contains(a, b) for a, b in zip(actual, required)) + if _number(required): + return _number(actual) and abs(actual - required) <= 1e-7 + return type(actual) is type(required) and actual == required + + +def _world_bounds(local, position, orientation): + points = [] + for point in itertools.product(*[(local['min'][i], local['max'][i]) for i in range(3)]): + turned = rotate(orientation, point) + points.append([turned[i] + position[i] for i in range(3)]) + return {'min': [min(p[i] for p in points) for i in range(3)], + 'max': [max(p[i] for p in points) for i in range(3)]} + + +def require_contained_bounds(actual, frozen): + if not _box(actual) or not _box(frozen): + raise SceneError('motion geometry requires finite child bounds') + if any(actual['min'][i] < frozen['min'][i] - 1e-8 or + actual['max'][i] > frozen['max'][i] + 1e-8 for i in range(3)): + raise SceneError('actual child geometry exceeds the qualified initial bounds') + + +def _inspect_prepared_geometry(asset_path, profile): + """Recheck the actual composed stage, not only the manifest's claims.""" + try: + from pxr import Usd, UsdGeom + except ImportError as error: + raise SceneError('USD Python bindings are required to inspect motion geometry') from error + from ..preparation.articulation import inspect_articulation + from ..preparation.articulation_v2 import inspect_articulation_v2 + + try: + stage = Usd.Stage.Open(str(asset_path)) + if not stage or not stage.GetDefaultPrim() or str(stage.GetDefaultPrim().GetPath()) != '/Asset': + raise SceneError('prepared motion geometry stage cannot be opened') + expected = profile['qualification_manifest'] + inspect = inspect_articulation_v2 if expected['profile_id'] == 'articulated_prop_v2' else inspect_articulation + observed = inspect(stage) + if (not _contains(observed.get('joint_map'), expected['joint_map']) or + not _contains(observed.get('body_map'), expected['body_map'])): + raise SceneError('actual native joint or collider geometry differs from the known profile') + cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), [UsdGeom.Tokens.default_, UsdGeom.Tokens.render, + UsdGeom.Tokens.proxy, UsdGeom.Tokens.guide]) + xforms = UsdGeom.XformCache() + for motion in profile['motions']: + joint = expected['joint_map'][motion['joint_id']] + parent = expected['body_map'][joint['parent_body_id']]['relative_prim_path'] + child = expected['body_map'][joint['child_body_id']]['relative_prim_path'] + parent_prim = stage.GetPrimAtPath('/Asset/' + parent) + child_prim = stage.GetPrimAtPath('/Asset/' + child) + if not parent_prim or not child_prim: + raise SceneError('known motion parent or child geometry is missing') + transform = xforms.GetLocalToWorldTransform(parent_prim) + matrix = [[float(transform[i][j]) for j in range(4)] for i in range(4)] + if not _contains(matrix, motion['parent_transform_owner']): + raise SceneError('native parent transform differs from qualified motion geometry') + box = cache.ComputeWorldBound(child_prim).ComputeAlignedRange() + if box.IsEmpty(): + raise SceneError('native child geometry has empty bounds') + require_contained_bounds({'min': list(box.GetMin()), 'max': list(box.GetMax())}, + motion['initial_child_bounds_owner_m']) + except SceneError: + raise + except Exception as error: + raise SceneError('could not inspect actual prepared motion geometry: ' + str(error)) from error + + +def check_motion_clearance(scene, owner_id, profile_id, object_ids=None, clearance_m=.05): + """Return named known-joint keepouts and check selected external objects. + + The prepared closure, source hash, collision paths and joint metadata must + match a shipped measurement profile. Only render bounds of explicitly + listed objects are compared; unlisted objects remain unassessed. + """ + profile = load_profile(profile_id) + objects = scene.get('objects') if isinstance(scene, dict) else None + if not isinstance(objects, dict) or owner_id not in objects: + raise SceneError('motion preflight requires an existing owner') + owner = objects[owner_id] + if (not isinstance(owner, dict) or owner.get('kind') != 'asset' or owner.get('dynamic') is not True + or not owner.get('asset_binding') or not owner.get('asset_path')): + raise SceneError('motion preflight requires a dynamic prepared articulated owner') + forbidden = {'size', 'scale', 'variants', 'pose_follower', 'rigid_attachment', 'asset_metrics', + 'physics', 'mass_kg', 'collision_exclusions'} & set(owner) + if forbidden or owner.get('collision', True) is not True: + raise SceneError('motion geometry cannot be reused with owner geometry or physics overrides') + position = owner.get('position', [0, 0, 0]) + orientation = owner.get('orientation_wxyz', [1, 0, 0, 0]) + if not vector(position) or not vector(orientation, 4) or abs(sum(v*v for v in orientation) - 1.) > 1e-6: + raise SceneError('motion owner requires finite position and a normalized orientation') + if not _number(clearance_m) or not 0 <= clearance_m <= .5: + raise SceneError('motion clearance must be finite and between zero and 0.5 m') + selected = [] if object_ids is None else object_ids + if (not isinstance(selected, list) or len(selected) > 8 + or any(not isinstance(name, str) or name not in objects for name in selected) + or len(set(selected)) != len(selected)): + raise SceneError('motion preflight accepts at most eight distinct existing object IDs') + from ..physics_binding import validate_asset_binding + try: + manifest = validate_asset_binding(owner['asset_binding'], require_dynamic=True, asset_path=owner['asset_path']) + except (ValueError, OSError, TypeError, KeyError, AttributeError) as error: + raise SceneError('motion geometry requires a verified prepared owner: ' + str(error)) from error + if not _contains(manifest, profile['qualification_manifest']): + raise SceneError('prepared source, joint or collider geometry differs from the known motion profile') + _inspect_prepared_geometry(owner['asset_path'], profile) + named = [] + for motion in profile['motions']: + local = swept_local_bounds(motion['kind'], motion['initial_child_bounds_owner_m'], + motion['axis_owner'], motion['limits'], motion['pivot_owner_m']) + named.append({'joint_id': motion['joint_id'], 'bounds': _world_bounds(local, position, orientation), + 'kind': motion['kind'], 'limits': motion['limits']}) + checked, conflicts = [], [] + for name in selected: + if name == owner_id: + continue + box = bounds(objects[name], scene, name) + if not _box(box): + raise SceneError('object has unknown or invalid measured geometry: ' + name) + checked.append({'object_id': name, 'world_bounds_m': box}) + for region in named: + if intersects(box, region['bounds'], clearance_m): + conflicts.append({'object_id': name, 'owner_id': owner_id, 'joint_id': region['joint_id'], + 'clearance_m': clearance_m}) + identity = hashlib.sha256(json.dumps(profile, sort_keys=True, separators=(',', ':'), allow_nan=False).encode()).hexdigest() + try: + scene_identity = hashlib.sha256(json.dumps(scene, sort_keys=True, separators=(',', ':'), + allow_nan=False).encode()).hexdigest() + except (TypeError, ValueError) as error: + raise SceneError('motion preflight requires a finite JSON scene') from error + return {'schema': 'simscene.motion_clearance.v1', 'scene_revision': scene.get('revision'), + 'scene_sha256': scene_identity, 'owner_id': owner_id, 'profile_id': profile_id, 'profile_sha256': identity, + 'owner_manifest_sha256': owner['asset_binding'].get('manifest_sha256'), + 'keepout_bounds': [entry['bounds'] for entry in named], 'motions': named, + 'clearance_m': clearance_m, 'checked_objects': checked, 'conflicts': conflicts, + 'skipped_owner': owner_id in selected, + 'status': 'conflict' if conflicts else 'clear' if checked else 'not_checked', + 'physics_tested': False, + 'scope': ('Known source and prepared geometry only; full-turn revolute or native-limit slider ' + 'envelopes and selected rendered bounds. Unlisted objects, future joint integrity, ' + 'actual contacts, parent drift and dynamic stability require separate checks.')} diff --git a/tests/agent/test_package.py b/tests/agent/test_package.py index dd97aaf..199df92 100644 --- a/tests/agent/test_package.py +++ b/tests/agent/test_package.py @@ -104,7 +104,8 @@ async def check_independent_metadata(root,plugin): 'examples/usdcraft_sdk_guide/check_pair.py', 'experiments/acquire_recipe_assets.py', 'experiments/apply_scene_recipe.py', - 'experiments/freeze_recipe_case.py'): + 'experiments/freeze_recipe_case.py', + 'experiments/check_motion_clearance.py'): self.assertEqual((plugin/sample).read_bytes(),(ROOT/sample).read_bytes(),sample) for original in (ROOT/'skills').rglob('*.md'): reference=plugin/'skills'/original.relative_to(ROOT/'skills') diff --git a/tests/test_motion_keepouts.py b/tests/test_motion_keepouts.py new file mode 100644 index 0000000..f6f85bb --- /dev/null +++ b/tests/test_motion_keepouts.py @@ -0,0 +1,144 @@ +"""Known joint motion must reserve intermediate space before physics starts.""" +import copy +import importlib +import importlib.util +import json +import math +import os +from pathlib import Path +import subprocess +import sys + +import pytest + +from simscene.scene import SceneError + + +def implementation(): + assert importlib.util.find_spec('simscene.recipes.motion_keepouts') is not None, 'motion preflight is unavailable' + return importlib.import_module('simscene.recipes.motion_keepouts') + + +def test_revolute_bound_includes_the_intermediate_sweep_not_just_endpoints(): + mod = implementation() + initial = {'min': [0., .99, -.01], 'max': [.2, 1.01, .01]} + result = mod.swept_local_bounds('revolute', initial, [1., 0., 0.], [0., math.pi], [0., 0., 0.]) + # A 180-degree rotation has almost zero Z at either endpoint, but reaches + # approximately one metre at its intermediate 90-degree pose. + assert result['min'][1] <= -1.01 and result['max'][1] >= 1.01 + assert result['min'][2] <= -1.01 and result['max'][2] >= 1.01 + + +def test_prismatic_bound_uses_the_real_axis_and_full_declared_travel(): + mod = implementation() + result = mod.swept_local_bounds('prismatic', {'min': [-.4, -.3, .1], 'max': [.4, .27, .47]}, + [0., -1., 0.], [0., .5]) + assert result['min'] == pytest.approx([-.4, -.8, .1]) + assert result['max'] == pytest.approx([.4, .27, .47]) + with pytest.raises(SceneError, match='axis'): + mod.swept_local_bounds('prismatic', {'min': [-.4, -.3, .1], 'max': [.4, .27, .47]}, + [0., 0., 0.], [0., .5]) + + +def test_actual_child_geometry_must_fit_the_frozen_source_envelope(): + mod = implementation() + assert hasattr(mod, 'require_contained_bounds') + frozen = {'min': [-.5, -.2, 0.], 'max': [.5, .2, .4]} + mod.require_contained_bounds({'min': [-.49, -.19, .01], 'max': [.49, .19, .39]}, frozen) + with pytest.raises(SceneError, match='geometry|bounds'): + mod.require_contained_bounds({'min': [-.6, -.19, .01], 'max': [.49, .19, .39]}, frozen) + + +def test_missing_usd_bindings_are_reported_as_a_preflight_error(monkeypatch): + import builtins + mod = implementation() + original_import = builtins.__import__ + def no_usd(name, *args, **kwargs): + if name == 'pxr': + raise ImportError('USD bindings unavailable') + return original_import(name, *args, **kwargs) + monkeypatch.setattr(builtins, '__import__', no_usd) + with pytest.raises(SceneError, match='USD|inspect'): + mod._inspect_prepared_geometry('/missing.usda', {}) + + +def test_known_hinge_checks_external_props_and_never_flags_its_owner(monkeypatch): + mod = implementation() + profile = mod.load_profile('usdcraft_lift_cabinet_v1') + manifest = copy.deepcopy(profile['qualification_manifest']) + monkeypatch.setattr('simscene.physics_binding.validate_asset_binding', lambda *a, **k: manifest) + monkeypatch.setattr(mod, '_inspect_prepared_geometry', lambda *a: None) + scene = {'revision': 3, 'objects': { + 'cabinet': {'kind': 'asset', 'dynamic': True, 'position': [-.7, .259, .832], + 'asset_path': '/prepared/main.usda', 'asset_binding': {'placeholder': True}}, + 'box': {'kind': 'box', 'size': [.1, .1, .1], 'position': [.6, .2, 1.]}, + }} + original = copy.deepcopy(scene) + clear = mod.check_motion_clearance(scene, 'cabinet', 'usdcraft_lift_cabinet_v1', ['cabinet', 'box']) + assert clear['status'] == 'clear' and clear['physics_tested'] is False + assert clear['skipped_owner'] is True and len(clear['keepout_bounds']) == 1 + assert scene == original + scene['objects']['box']['position'] = [-.7, -.1, 1.1] + blocked = mod.check_motion_clearance(scene, 'cabinet', 'usdcraft_lift_cabinet_v1', ['box']) + assert blocked['status'] == 'conflict' + assert blocked['scene_sha256'] != clear['scene_sha256'] + assert blocked['conflicts'][0]['object_id'] == 'box' + assert blocked['conflicts'][0]['joint_id'] == 'main' + unchecked = mod.check_motion_clearance(scene, 'cabinet', 'usdcraft_lift_cabinet_v1', []) + assert unchecked['status'] == 'not_checked' + + +def test_missing_or_changed_native_joint_geometry_is_not_marked_clear(monkeypatch): + mod = implementation() + profile = mod.load_profile('usdcraft_lift_cabinet_v1') + manifest = copy.deepcopy(profile['qualification_manifest']) + manifest['joint_map']['main']['axis'] = 'Z' + monkeypatch.setattr('simscene.physics_binding.validate_asset_binding', lambda *a, **k: manifest) + scene = {'revision': 1, 'objects': {'cabinet': {'kind': 'asset', 'dynamic': True, + 'asset_path': '/prepared/main.usda', 'asset_binding': {'placeholder': True}}}} + with pytest.raises(SceneError, match='joint|geometry'): + mod.check_motion_clearance(scene, 'cabinet', 'usdcraft_lift_cabinet_v1', []) + with pytest.raises(SceneError, match='unknown|unsupported'): + mod.load_profile('uninspected_joint') + + +def test_nine_objects_are_rejected_before_layout_backend_is_called(): + from simscene.layout_synthesis import plan_layout + objects = {'table': {'kind': 'box', 'size': [4, 4, .1], 'position': [0, 0, 0], 'collision': True}} + objects.update({f'part{i}': {'kind': 'box', 'size': [.1, .1, .1]} for i in range(9)}) + with pytest.raises(SceneError, match='1..8'): + plan_layout({'revision': 0, 'objects': objects}, [f'part{i}' for i in range(9)], 'table') + + +def test_file_preflight_reports_unknown_profile_without_a_false_pass(tmp_path): + script = Path(__file__).resolve().parents[1] / 'experiments/check_motion_clearance.py' + assert script.is_file(), 'installed motion preflight entrypoint is unavailable' + scene = tmp_path / 'scene.json' + output = tmp_path / 'result.json' + scene.write_text(json.dumps({'revision': 0, 'objects': {}})) + result = subprocess.run([sys.executable, str(script), '--scene', str(scene), '--owner', 'cabinet', + '--profile', 'unknown', '--output', str(output)], + env=dict(os.environ, PYTHONPATH=str(Path(__file__).resolve().parents[1] / 'src')), + text=True, capture_output=True) + assert result.returncode == 1 + report = json.loads(output.read_text()) + assert report['status'] == 'error' and report['physics_tested'] is False + assert 'unknown' in report['error'] + + +@pytest.mark.parametrize('surface', [ + {'min_xy': [-.4, -.4], 'max_xy': [.4, .4], 'z_m': .3}, + {'min_xy': [-1.1, -.4], 'max_xy': [.4, .4], 'z_m': .05}, +]) +def test_wrong_primitive_support_height_or_extent_fails_before_sampling(surface, monkeypatch): + from simscene import layout_synthesis + scene = {'revision': 0, 'objects': { + 'table': {'kind': 'box', 'size': [2., 1., .1], 'collision': True, + 'support_surfaces': {'top': surface}}, + 'part': {'kind': 'box', 'size': [.1, .1, .1], 'dynamic': True}, + }} + def no_backend(_): + pytest.fail('an invalid support reached the optional layout backend') + monkeypatch.setattr(layout_synthesis, '_run_backend', no_backend) + with pytest.raises(SceneError, match='support.*(height|extent)'): + layout_synthesis.plan_layout(scene, ['part'], 'table', support_surface='top') From 7439e1093fcfff910822d3d5882106bb2af2007b Mon Sep 17 00:00:00 2001 From: shaoxiang <519517384@qq.com> Date: Tue, 17 Nov 2026 17:05:24 +0800 Subject: [PATCH 07/20] Bind installed cabinet handoff to runtime and media evidence --- docs/packaging.md | 8 + examples/automatic_cabinet_layout/check.py | 99 +------- experiments/apply_scene_recipe.py | 19 +- experiments/assemble_integration_receipt.py | 32 +++ plugins/build.py | 56 ++++- .../references/integration-workspace.md | 22 +- src/simscene/mcp_server.py | 20 ++ src/simscene/recipes/integration_delivery.py | 224 ++++++++++++++++++ .../verification/automatic_cabinet_layout.py | 104 ++++++++ tests/agent/test_package.py | 8 +- tests/test_build_identity.py | 48 ++++ tests/test_integration_delivery.py | 139 +++++++++++ tests/test_recipe_io.py | 14 ++ 13 files changed, 689 insertions(+), 104 deletions(-) create mode 100644 experiments/assemble_integration_receipt.py create mode 100644 src/simscene/recipes/integration_delivery.py create mode 100644 src/simscene/verification/automatic_cabinet_layout.py create mode 100644 tests/test_build_identity.py create mode 100644 tests/test_integration_delivery.py diff --git a/docs/packaging.md b/docs/packaging.md index d2b8c98..5cd8134 100644 --- a/docs/packaging.md +++ b/docs/packaging.md @@ -51,6 +51,14 @@ check resources and Pillow in a fresh interpreter, and retain the own-project wheel under `wheels/`. Each client tree has `server/dependency-lock.json` and `server/build-info.json` with versions, build mode, and wheel SHA256. These are platform/Python-specific bundles, not universal offline runtime distributions. +The build record also identifies the full Git commit and whether the checkout +was clean. A clean build verifies its wheel source snapshot against the Git +tree; dirty or non-Git builds explicitly record that state. Query the running +MCP resource `simscene://runtime/identity` for the loaded module, worker and +build record, and compare the wheel digest with the actual wheel. Two builds +with the same version string can contain different code. Isaac, layout and +optional generator environments are distinct runtimes and need their own +identity checks. A wheel can also be installed using ordinary pip: diff --git a/examples/automatic_cabinet_layout/check.py b/examples/automatic_cabinet_layout/check.py index f193bbc..54a62ed 100644 --- a/examples/automatic_cabinet_layout/check.py +++ b/examples/automatic_cabinet_layout/check.py @@ -1,108 +1,13 @@ """Check the frozen cabinet layout case and its additional physical evidence.""" import argparse -import hashlib import json -import math from pathlib import Path -from pxr import Usd -from simscene.evidence_integrity import verify as verify_evidence -from simscene.physics_binding import validate_asset_binding -from simscene.preparation.articulation import inspect_articulation -from simscene.recipes.cases import freeze_case -from simscene.run_integrity import verify as verify_inputs -from simscene.verification.asset_gallery import verify_run -from simscene.verification.settling import stable - - -def sha(path): - digest = hashlib.sha256() - with path.open('rb') as stream: - for chunk in iter(lambda: stream.read(1024 * 1024), b''): - digest.update(chunk) - return digest.hexdigest() +from simscene.verification.automatic_cabinet_layout import verify as verify_example def verify(run): - root = Path(__file__).resolve().parent - run = Path(run).resolve() - checks_path = root / 'supplemental-checks.json' - checks = json.loads(checks_path.read_text()) - selections = json.loads((root / 'assets.lock.json').read_text())['assets'] - selection = selections['cabinet'] - result = json.loads((run / 'result.json').read_text()) - spec = json.loads((run / 'spec.json').read_text()) - case = json.loads((run / 'acceptance-case.json').read_text()) - bindings = {role: {'asset_path': spec['objects'][role]['asset_path'], - 'asset_binding': spec['objects'][role]['asset_binding']} for role in selections} - template = json.loads((root / 'case.json').read_text()) - expected_case = freeze_case(template, bindings, selections)['case'] - inputs, evidence, core = verify_inputs(run), verify_evidence(run), verify_run(run) - frames = [result['initial_observation'], *result['samples']] - parent, door = checks['cabinet_parent'], checks['cabinet_child'] - records = [frame.get('mechanisms', {}).get('cabinet', {}).get('joints', {}).get('main', {}) for frame in frames] - - def finite(value): - return type(value) in (int, float) and math.isfinite(value) - - native = all(finite(record.get('native_position')) and finite(record.get('native_velocity')) and - record.get('native_measurement_source') == 'PhysX_articulation_tensor_DOF_readback_SI' and - finite(record.get('position')) and abs(record['native_position'] - record['position']) <= .015 - for record in records) - initial = frames[0]['positions'][parent] - displacements = [math.dist(initial, frame['positions'][parent]) for frame in frames] - contacts = set() - for frame in frames: - for pair in frame.get('contact_pairs', []): - actors = pair.get('actor_paths', []) - if len(actors) == 2 and pair.get('count', 0) > 0: - contacts.add(frozenset(actors)) - prop_bodies = [result['body_bindings'][name]['motion_body'] for name in checks['rigid_objects']] - forbidden = [sorted(pair) for pair in contacts if door in pair and any(body in pair for body in prop_bodies)] - keep = checks['reserved_volume'] - - def intersects(a, b): - return all(a['max'][i] > b['min'][i] and b['max'][i] > a['min'][i] for i in range(3)) - - prop_clear = all(not intersects(frame['bounds'][name], keep) for frame in frames for name in checks['rigid_objects']) - cabinet_contained = all(all(keep['min'][i] - .01 <= frame['bounds']['cabinet']['min'][i] and - frame['bounds']['cabinet']['max'][i] <= keep['max'][i] + .01 - for i in range(3)) for frame in frames) - obj = spec['objects']['cabinet'] - manifest = validate_asset_binding(obj['asset_binding'], require_dynamic=True, asset_path=obj['asset_path']) - package = Path(obj['asset_binding']['manifest_path']).parent - source_file = package / 'source' / selection['source_files'][0]['path'] - source = inspect_articulation(Usd.Stage.Open(str(source_file))) - source_joint, prepared_joint = source['joint_map']['main'], result['body_bindings']['cabinet']['joints']['main'] - joint_keys = ('type', 'axis', 'limits', 'position_unit', 'native_authored_attributes', - 'local_pos0_m', 'local_pos1_m', 'local_rot0_wxyz', 'local_rot1_wxyz') - source_masses = sorted(item['mass_kg'] for item in source['body_map'].values() if item.get('role') == 'rigid') - prepared_masses = sorted(item['mass_kg'] for item in manifest['body_map'].values() if item.get('role') == 'rigid') - note = case['components'][-1]['case']['physical_model_note'] - supplemental = { - 'case_matches_frozen_example': case == expected_case, - 'requirements_pinned_in_case': ('Supplemental acceptance SHA-256: ' + sha(checks_path)) in note, - 'native_dof_readback_each_step': native, - 'cabinet_supported_by_table': frozenset((parent, checks['support_actor'])) in contacts, - 'cabinet_settled_two_seconds': stable(frames, parent, result['simulation_time_s'], 2., - checks['max_linear_speed_m_s'], checks['max_angular_speed_rad_s']), - 'cabinet_translation_within_limit': max(displacements) <= checks['max_parent_translation_m'], - 'props_outside_reserved_sweep': prop_clear, - 'cabinet_inside_reserved_volume': cabinet_contained, - 'no_door_prop_contacts': not forbidden, - 'source_file_hash_matches_lock': sha(source_file) == selection['source_sha256'], - 'native_joint_attributes_preserved': all(source_joint.get(key) == prepared_joint.get(key) for key in joint_keys), - 'native_rigid_masses_preserved': len(source_masses) == 2 and source_masses == prepared_masses, - 'one_joint_binding': len(result['body_bindings']['cabinet']['joints']) == 1, - } - return {'schema': 'simscene.cabinet_layout_example_check.v1', 'run': str(run), - 'passed': (inputs['passed'] and evidence['passed'] and evidence['partial'] is False and - core['passed'] and all(supplemental.values())), - 'input_integrity': inputs, 'evidence_integrity': evidence, 'core_verification': core, - 'supplemental': supplemental, 'max_parent_translation_m': max(displacements), - 'native_dof_range_rad': [min(record['native_position'] for record in records if finite(record.get('native_position'))), - max(record['native_position'] for record in records if finite(record.get('native_position')))], - 'scope': 'One frozen layout and recorded run; not a general asset or structural certification.'} + return verify_example(run, Path(__file__).resolve().parent) def main(): diff --git a/experiments/apply_scene_recipe.py b/experiments/apply_scene_recipe.py index 7167da5..cc8c03c 100644 --- a/experiments/apply_scene_recipe.py +++ b/experiments/apply_scene_recipe.py @@ -22,12 +22,23 @@ def apply(recipe,scene_id,catalog,save_directory,*,lock=None,store=None): def main(argv=None): - p=argparse.ArgumentParser(description=__doc__);p.add_argument('recipe');p.add_argument('--scene-id',required=True) + p=argparse.ArgumentParser(description=__doc__);p.add_argument('recipe');p.add_argument('--scene-id') p.add_argument('--asset-catalog');p.add_argument('--asset-lock');p.add_argument('--save-directory',required=True) + p.add_argument('--operations-only',action='store_true',help='resolve ordinary operations without applying them') a=p.parse_args(argv) - result=apply(json.loads(Path(a.recipe).read_text()),a.scene_id, - json.loads(Path(a.asset_catalog).read_text()) if a.asset_catalog else {},a.save_directory, - lock=json.loads(Path(a.asset_lock).read_text()) if a.asset_lock else None) + recipe=json.loads(Path(a.recipe).read_text()) + catalog=json.loads(Path(a.asset_catalog).read_text()) if a.asset_catalog else {} + lock=json.loads(Path(a.asset_lock).read_text()) if a.asset_lock else None + if a.operations_only: + from simscene.recipes.io import resolve_operations + operations=resolve_operations(recipe,catalog,selections=lock['assets'] if lock else None) + root=Path(a.save_directory);root.mkdir(parents=True,exist_ok=True) + output=root/'resolved-operations.json' + with output.open('x',encoding='utf8') as stream:json.dump(operations,stream,indent=2);stream.write('\n') + result={'operations_path':str(output),'operation_count':len(operations),'physical_verification':'not_run'} + else: + if not a.scene_id:p.error('--scene-id is required unless --operations-only is used') + result=apply(recipe,a.scene_id,catalog,a.save_directory,lock=lock) print(json.dumps(result));return 0 diff --git a/experiments/assemble_integration_receipt.py b/experiments/assemble_integration_receipt.py new file mode 100644 index 0000000..a18400a --- /dev/null +++ b/experiments/assemble_integration_receipt.py @@ -0,0 +1,32 @@ +"""Recheck and assemble a fixed cabinet-example delivery receipt.""" +import argparse +import hashlib +import json +from pathlib import Path + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + for name in ('scene', 'run', 'case', 'recipe', 'identity', 'video', 'edit-map', 'review', 'example-directory'): + parser.add_argument('--' + name) + parser.add_argument('--output', required=True, help='new receipt JSON path') + args = parser.parse_args(argv) + from simscene.recipes.integration_delivery import collect_delivery + paths = {name: getattr(args, name) for name in ('scene', 'run', 'case', 'recipe', 'identity', 'video', + 'edit_map', 'review', 'example_directory') + if getattr(args, name) is not None} + report = collect_delivery(paths) + output = Path(args.output) + with output.open('x', encoding='utf8') as stream: + json.dump(report, stream, ensure_ascii=False, indent=2, allow_nan=False) + stream.write('\n') + print(json.dumps({'status': report['status'], 'physical_status': report['physical_status'], + 'media_status': report['media_status'], 'visual_review': report['visual_review'], + 'missing': report['missing'], 'errors': [value[:300] for value in report['errors'][:5]], + 'receipt': str(output), 'sha256': hashlib.sha256(output.read_bytes()).hexdigest()}, + ensure_ascii=False)) + return 0 if report['status'] == 'ready_for_submission' else 2 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/plugins/build.py b/plugins/build.py index 0af6775..10243ca 100644 --- a/plugins/build.py +++ b/plugins/build.py @@ -22,6 +22,53 @@ def versions(root=ROOT): return python,python.replace('.dev','-dev.') PYTHON_VERSION,PACKAGE_VERSION=versions() + +def source_identity(root=ROOT): + """Identify a checkout only when *root* is its actual Git top level.""" + root=Path(root).resolve() + try: + top=subprocess.check_output(['git','rev-parse','--show-toplevel'],cwd=root,stderr=subprocess.DEVNULL,text=True).strip() + if Path(top).resolve()!=root: + return {'source_commit':None,'source_clean':None} + commit=subprocess.check_output(['git','rev-parse','--verify','HEAD'],cwd=root,stderr=subprocess.DEVNULL,text=True).strip() + if not re.fullmatch(r'[0-9a-f]{40,64}',commit):raise ValueError('invalid Git commit') + status=subprocess.check_output(['git','status','--porcelain=v1','--untracked-files=normal'],cwd=root,stderr=subprocess.DEVNULL,text=True) + return {'source_commit':commit,'source_clean':not bool(status.strip())} + except (OSError,subprocess.SubprocessError,ValueError): + return {'source_commit':None,'source_clean':None} + + +def verify_source_snapshot(root, snapshot, commit): + """Reject ignored or changed files in a supposedly clean wheel snapshot.""" + root, snapshot = Path(root), Path(snapshot) + paths = ('src', 'pyproject.toml', 'README.md', 'LICENSE') + try: + result = subprocess.check_output( + ['git', 'ls-tree', '-r', '-z', '--full-tree', commit, '--', *paths], cwd=root) + algorithm = subprocess.check_output( + ['git', 'rev-parse', '--show-object-format'], cwd=root, text=True).strip() + expected = {} + for entry in result.split(b'\0'): + if not entry: + continue + header, raw_name = entry.split(b'\t', 1) + mode, kind, digest = header.decode('ascii').split(' ') + if mode not in ('100644', '100755') or kind != 'blob': + raise RuntimeError('source snapshot contains an unsupported Git entry') + expected[raw_name.decode('utf-8')] = digest + actual = {str(path.relative_to(snapshot)) for name in paths + for path in ([snapshot / name] if (snapshot / name).is_file() + else (snapshot / name).rglob('*')) if path.is_file()} + if actual != set(expected): + raise RuntimeError('source snapshot inventory differs from the committed tree') + for name, digest in expected.items(): + data = (snapshot / name).read_bytes() + content = b'blob ' + str(len(data)).encode('ascii') + b'\0' + data + if hashlib.new(algorithm, content).hexdigest() != digest: + raise RuntimeError(f'source snapshot content differs from the committed tree: {name}') + except (OSError, subprocess.SubprocessError, ValueError, UnicodeError) as error: + raise RuntimeError('unable to verify source snapshot against Git') from error + LAUNCHER='''"""Start the packaged MCP server without importing the development checkout.""" from pathlib import Path import sys @@ -47,7 +94,8 @@ def versions(root=ROOT): 'usdcraft_two_drawer':('assets.lock.json','case.json','recipe.json','recipe-control.json'), 'usdcraft_sdk_guide':('assets.lock.json','case.json','recipe-short.json','recipe-long.json','check_pair.py'), } -EXAMPLE_HELPERS=('acquire_recipe_assets.py','apply_scene_recipe.py','freeze_recipe_case.py','check_motion_clearance.py') +EXAMPLE_HELPERS=('acquire_recipe_assets.py','apply_scene_recipe.py','freeze_recipe_case.py', + 'check_motion_clearance.py','assemble_integration_receipt.py') def write(path, value): path.parent.mkdir(parents=True,exist_ok=True) path.write_text(json.dumps(value,indent=2)+'\n') @@ -120,6 +168,7 @@ def validate_vendor(vendor, python=sys.executable): def build(destination, use_installed_deps=False): + build_source=source_identity() requested=Path(destination).expanduser() if requested.is_symlink():raise FileExistsError(f'destination is a symlink: {requested}') destination=requested.resolve() @@ -135,6 +184,10 @@ def build(destination, use_installed_deps=False): for filename in ('pyproject.toml','README.md','LICENSE'): shutil.copyfile(ROOT/filename,snapshot/filename) shutil.copytree(ROOT/'src',snapshot/'src',ignore=shutil.ignore_patterns('__pycache__','*.pyc','*.egg-info')) + if build_source['source_clean'] is True: + verify_source_snapshot(ROOT,snapshot,build_source['source_commit']) + if source_identity()!=build_source: + raise RuntimeError('source revision or clean state changed while creating the build snapshot') wheels=Path(temporary)/'wheels';wheels.mkdir() subprocess.run([sys.executable,'-m','pip','wheel','--disable-pip-version-check', '--no-deps','--no-build-isolation','--wheel-dir',str(wheels),str(snapshot)],check=True) @@ -152,6 +205,7 @@ def build(destination, use_installed_deps=False): write(portable/'server'/'dependency-lock.json',versions_lock) write(portable/'server'/'build-info.json',{'python_version':PYTHON_VERSION,'plugin_version':PACKAGE_VERSION, 'builder_python':sys.version.split()[0],'wheel_sha256':wheel_sha256, + **build_source, 'dependency_mode':'installed' if use_installed_deps else 'pip', 'optional_backends':'Isaac/USD, isolated GLB decoder, layout, Sand3D and USDCraft SDK runtimes are configured separately'}) validate_vendor(vendor) diff --git a/skills/build-scene/references/integration-workspace.md b/skills/build-scene/references/integration-workspace.md index a6a008a..9ffa9cb 100644 --- a/skills/build-scene/references/integration-workspace.md +++ b/skills/build-scene/references/integration-workspace.md @@ -35,7 +35,11 @@ cache proves a cold download. Check per-asset license and missing dependencies. For shell-capable clients, the installed package also contains the same small helpers as the source tree: `experiments/acquire_recipe_assets.py`, `experiments/apply_scene_recipe.py`, `experiments/freeze_recipe_case.py` and -`experiments/check_motion_clearance.py`. +`experiments/check_motion_clearance.py`. For an MCP workflow use +`apply_scene_recipe.py --operations-only --asset-catalog CATALOG.json +--asset-lock LOCK.json --save-directory NEW_DIRECTORY RECIPE.json` to resolve +the verified bindings without editing the scene. Submit the resulting +`resolved-operations.json` with `scene_apply` and its current revision. Run them with the matching `server/vendor` first on `PYTHONPATH` and a host Python with the required USD bindings. The acquire helper invokes the ordinary durable jobs directly; a workflow specifically requiring MCP coverage must @@ -64,3 +68,19 @@ the same durable job, inspect real frames and observations, then run the appropriate checker with the same installed package and USD environment. Archive the case, inputs, physical result, video mapping and an actual visual review. Scheduled commands are not evidence of contact-triggered motion. + +For the fixed cabinet example, read `simscene://runtime/identity` from the +actual MCP session and save `{"runtime_identity": RESPONSE, "wheel_path": +"/path/to/the/builds/wheel.whl"}`. Keep the complete response, not just the +version. The portable installation's `server/build-info.json` records the +source commit, clean state and wheel digest. Isaac, layout and generator +runtimes have separate identities; the MCP interpreter is not the Isaac worker. + +After a real inspection, an attributed visual review may be saved separately +with the video SHA256, `reviewer`, `decision` (`accept` or `change_needed`) and +`reviewed_windows` (start/end seconds and actual observation). Run installed +`experiments/assemble_integration_receipt.py --help` to combine the scene, +frozen case, run, recipe, identity, video, edit mapping and this review. The +helper reports missing, physical, media and visual states separately. It never +authors the visual review, signs evidence or proves a deadline. The presence +of a receipt is not itself a pass. diff --git a/src/simscene/mcp_server.py b/src/simscene/mcp_server.py index c2d5d58..f5da14d 100644 --- a/src/simscene/mcp_server.py +++ b/src/simscene/mcp_server.py @@ -82,6 +82,26 @@ def fixed_examples_resource() -> str: from .recipes.registry import list_examples return json.dumps(list_examples(),ensure_ascii=False) +@server.resource('simscene://runtime/identity') +def runtime_identity_resource() -> str: + """Report this process's loaded package paths and local build identity.""" + import hashlib + import json + import sys + from pathlib import Path + import simscene + module=Path(simscene.__file__).resolve() + server_file=Path(__file__).resolve() + worker=module.parent/'worker'/'isaac_run.py' + build_file=module.parent.parent.parent/'build-info.json' + info=json.loads(build_file.read_text()) if build_file.is_file() and build_file.stat().st_size<=65536 else None + digest=lambda path: hashlib.sha256(path.read_bytes()).hexdigest() + return json.dumps({'schema':'simscene.runtime_identity.v1','python_executable':sys.executable, + 'python_version':sys.version.split()[0],'module_path':str(module),'module_sha256':digest(module), + 'mcp_server_path':str(server_file),'mcp_server_sha256':digest(server_file), + 'worker_path':str(worker),'worker_sha256':digest(worker),'build_info':info, + 'scope':'Current MCP process and local files; separate worker and optional backends need their own identity. Hashes are not signatures.'},ensure_ascii=False) + @threaded_tool(annotations=_read_local) def environment_probe() -> dict: """Inspect configured runtime and GPU without starting Isaac Sim.""" diff --git a/src/simscene/recipes/integration_delivery.py b/src/simscene/recipes/integration_delivery.py new file mode 100644 index 0000000..66b2421 --- /dev/null +++ b/src/simscene/recipes/integration_delivery.py @@ -0,0 +1,224 @@ +"""Assemble a narrow, inspectable handoff for the fixed cabinet example. + +This does not sign evidence, attest deadlines or perform a visual review. +""" +import hashlib +import json +import math +from pathlib import Path +import re +import zipfile + + +def _sha(path): + digest = hashlib.sha256() + with Path(path).open('rb') as stream: + for block in iter(lambda: stream.read(1024 * 1024), b''): + digest.update(block) + return digest.hexdigest() + + +def _canonical(value): + return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(',', ':'), + allow_nan=False).encode()).hexdigest() + + +def check_edit_binding(edit, video, run): + """Check that each declared camera source belongs to this exact run.""" + errors = [] + try: + video, run = Path(video).resolve(), Path(run).resolve() + lock = json.loads((run / 'run-lock.json').read_text()) + result = json.loads((run / 'result.json').read_text()) + if (not isinstance(edit, dict) or edit.get('schema') != 'simscene.video_edit.v1' + or Path(edit.get('path', '')).resolve() != video or edit.get('sha256') != _sha(video)): + errors.append('edited video identity differs from its mapping') + segments = edit.get('segments') if isinstance(edit, dict) else None + if not isinstance(segments, list) or not segments: + return errors + ['edited video has no source segments'] + for index, segment in enumerate(segments): + if not isinstance(segment, dict): + errors.append(f'segment {index} is invalid'); continue + record = result.get('videos', {}).get(segment.get('camera')) + valid = (isinstance(record, dict) and segment.get('run_id') == lock.get('run_id') + and Path(segment.get('run_directory', '')).resolve() == run + and Path(segment.get('source', '')).resolve() == Path(record.get('path', '')).resolve() + and segment.get('source_sha256') == _sha(record['path']) + and segment.get('source_frame_manifest_sha256') == _sha(record['frame_manifest']) + and segment.get('run_lock_sha256') == _sha(run / 'run-lock.json') + and segment.get('evidence_lock_sha256') == _sha(run / 'evidence-lock.json')) + if not valid: + errors.append(f'segment {index} does not match the run, camera or frame table') + except (OSError, ValueError, TypeError, KeyError, AttributeError) as error: + errors.append('cannot verify edited source binding: ' + str(error)) + return errors + + +def check_visual_review(review, video, duration_s): + """Validate an attributed review record; its content remains a declaration.""" + errors = [] + try: + if not isinstance(review, dict) or review.get('decision') not in ('accept', 'change_needed'): + return ['an explicit accept or change_needed visual decision is required'] + if not isinstance(review.get('reviewer'), str) or not review['reviewer'].strip(): + errors.append('visual reviewer is required') + if review.get('video_sha256') != _sha(video): + errors.append('visual review belongs to a different video') + windows = review.get('reviewed_windows') + if (not isinstance(windows, list) or not windows or type(duration_s) not in (int, float) + or not math.isfinite(duration_s) or duration_s <= 0): + return errors + ['reviewed action windows and finite video duration are required'] + for window in windows: + if not isinstance(window, dict): + errors.append('visual window is invalid'); continue + start, end = window.get('start_s'), window.get('end_s') + if (type(start) not in (int, float) or type(end) not in (int, float) + or not math.isfinite(start) or not math.isfinite(end) + or not 0 <= start < end <= duration_s + 1e-6 + or not isinstance(window.get('observation'), str) or not window['observation'].strip()): + errors.append('visual window is outside the video or lacks an observation') + except (OSError, ValueError, TypeError) as error: + errors.append('cannot read visual-review evidence: ' + str(error)) + return errors + + +def _identity_errors(identity, run_lock): + """Compare reported MCP files and wheel with the actual frozen worker copy.""" + errors = [] + try: + runtime = identity['runtime_identity'] + info = runtime['build_info'] + wheel = Path(identity['wheel_path']).resolve() + module = Path(runtime['module_path']).resolve() + server = Path(runtime['mcp_server_path']).resolve() + worker = Path(runtime['worker_path']).resolve() + package = module.parent + if (runtime.get('schema') != 'simscene.runtime_identity.v1' or module.name != '__init__.py' + or server != package / 'mcp_server.py' or worker != package / 'worker' / 'isaac_run.py'): + errors.append('reported MCP and worker paths do not belong to one package') + for field, path in [('module_sha256', module), ('mcp_server_sha256', server), ('worker_sha256', worker)]: + if runtime.get(field) != _sha(path):errors.append('loaded file changed: ' + field) + installed_info = json.loads((package.parent.parent / 'build-info.json').read_text()) + if info != installed_info: + errors.append('reported build record differs from the installed build-info.json') + if (not isinstance(info, dict) or info.get('wheel_sha256') != _sha(wheel) + or info.get('source_clean') is not True + or not isinstance(info.get('source_commit'), str) + or not re.fullmatch(r'[0-9a-f]{40,64}', info['source_commit'])): + errors.append('wheel or clean source commit identity is missing or mismatched') + if Path(runtime.get('python_executable', '')).resolve() != Path(run_lock.get('queue_launcher_python', '')).resolve(): + errors.append('MCP interpreter differs from the run queue launcher') + recorded = run_lock.get('worker_code_sha256') + if not isinstance(recorded, dict) or not recorded: + errors.append('run lacks a worker source snapshot') + else: + actual = {str(path.relative_to(package)) for path in package.rglob('*') + if path.is_file() and '__pycache__' not in path.parts and path.suffix != '.pyc'} + if actual != set(recorded): + errors.append('installed package and frozen worker file inventories differ') + elif any(_sha(package / name) != digest for name, digest in recorded.items()): + errors.append('installed package and frozen worker bytes differ') + else: + with zipfile.ZipFile(wheel) as archive: + wheel_files = {name[len('simscene/'):] for name in archive.namelist() + if name.startswith('simscene/') and not name.endswith('/')} + if wheel_files != set(recorded) or any( + hashlib.sha256(archive.read('simscene/' + name)).hexdigest() != digest + for name, digest in recorded.items()): + errors.append('wheel contents differ from the installed worker snapshot') + except (OSError, ValueError, TypeError, KeyError, AttributeError, zipfile.BadZipFile) as error: + errors.append('cannot verify installed identity: ' + str(error)) + return errors + + +def collect_delivery(paths): + """Recheck available inputs and report incomplete work without inventing review.""" + required = ('scene', 'run', 'case', 'recipe', 'identity', 'video', 'edit_map', 'review', 'example_directory') + if not isinstance(paths, dict) or set(paths) - set(required): + raise ValueError('delivery inputs must use the supported artifact names') + artifacts, missing = {}, [] + for name in required: + value = paths.get(name) + path = Path(value).expanduser().resolve() if isinstance(value, str) and value else None + exists = path is not None and (path.is_dir() if name in ('run', 'example_directory') else path.is_file()) + if not exists: + missing.append(name) + else: + artifacts[name] = {'path': str(path)} + if path.is_file():artifacts[name]['sha256'] = _sha(path) + report = {'schema': 'simscene.integration_delivery.v1', 'status': 'incomplete', + 'physical_status': 'not_checked', 'media_status': 'not_checked', + 'visual_review': 'not_supplied' if 'review' in missing else 'not_checked', + 'missing': missing, 'errors': [], 'artifacts': artifacts, + 'scope': ('Fixed cabinet example and its one-run edit. A visual decision is an attributed ' + 'review declaration; hashes are not signatures or deadline evidence.')} + present = lambda *names: all(name not in missing for name in names) + run = Path(paths['run']).resolve() if present('run') else None + example = Path(paths['example_directory']).resolve() if present('example_directory') else None + lock = None + if run: + try: + lock = json.loads((run / 'run-lock.json').read_text()) + except (OSError, ValueError, TypeError) as error: + report['errors'].append('run lock unavailable: ' + str(error)) + if run and example: + try: + from ..verification.automatic_cabinet_layout import verify + physical = verify(run, example) + report['physical_status'] = 'passed' if physical.get('passed') is True else 'failed' + if report['physical_status'] != 'passed':report['errors'].append('fixed physical checker did not pass') + except Exception as error: + report['physical_status'] = 'error' + report['errors'].append('fixed physical checker could not complete: ' + str(error)) + if lock and present('scene'): + try: + if _canonical(json.loads(Path(paths['scene']).read_text())) != lock.get('source_scene_sha256'): + report['errors'].append('scene content does not match the recorded run') + except (OSError, ValueError, TypeError) as error: + report['errors'].append('cannot compare source scene: ' + str(error)) + if lock and present('case') and _sha(paths['case']) != lock.get('acceptance_case_sha256'): + report['errors'].append('acceptance case does not match the recorded run') + if example and present('recipe'): + try: + if _sha(paths['recipe']) != _sha(example / 'recipe.json'): + report['errors'].append('recipe differs from the fixed example') + except OSError as error: + report['errors'].append('cannot compare fixed recipe: ' + str(error)) + if lock and present('identity'): + try: + identity = json.loads(Path(paths['identity']).read_text()) + report['errors'].extend(_identity_errors(identity, lock)) + package = Path(identity['runtime_identity']['module_path']).resolve().parent + if example and example != package.parent.parent.parent / 'examples' / 'automatic_cabinet_layout': + report['errors'].append('fixed example is not from the identified installed package') + except (OSError, ValueError, TypeError, KeyError) as error: + report['errors'].append('cannot read installed identity: ' + str(error)) + inspected = None + if run and present('video', 'edit_map'): + try: + video, edit_file = Path(paths['video']).resolve(), Path(paths['edit_map']).resolve() + media_errors = [] + if edit_file != video.with_suffix('.edit.json'): + media_errors.append('edit mapping is not the video\'s accompanying mapping') + media_errors.extend(check_edit_binding(json.loads(edit_file.read_text()), video, run)) + from ..video_tools import inspect + inspected = inspect(video, representative_count=1) + if not (inspected.get('simulation_timeline') or {}).get('passed'): + media_errors.append('edited video provenance or timeline did not pass') + report['media_status'] = 'failed' if media_errors else 'passed' + report['errors'].extend(media_errors) + except Exception as error: + report['media_status'] = 'error' + report['errors'].append('media check could not complete: ' + str(error)) + if inspected and present('review', 'video'): + try: + review = json.loads(Path(paths['review']).read_text()) + report['errors'].extend(check_visual_review(review, paths['video'], inspected.get('duration_s'))) + report['visual_review'] = review.get('decision', 'not_checked') if isinstance(review, dict) else 'not_checked' + if report['visual_review'] != 'accept':report['errors'].append('visual review is not accepted') + except (OSError, ValueError, TypeError) as error: + report['errors'].append('visual review could not be read: ' + str(error)) + if (not missing and not report['errors'] and report['physical_status'] == 'passed' + and report['media_status'] == 'passed' and report['visual_review'] == 'accept'): + report['status'] = 'ready_for_submission' + return report diff --git a/src/simscene/verification/automatic_cabinet_layout.py b/src/simscene/verification/automatic_cabinet_layout.py new file mode 100644 index 0000000..e843feb --- /dev/null +++ b/src/simscene/verification/automatic_cabinet_layout.py @@ -0,0 +1,104 @@ +"""Check the frozen cabinet layout case and its additional physical evidence.""" +import hashlib +import json +import math +from pathlib import Path + +from pxr import Usd +from simscene.evidence_integrity import verify as verify_evidence +from simscene.physics_binding import validate_asset_binding +from simscene.preparation.articulation import inspect_articulation +from simscene.recipes.cases import freeze_case +from simscene.run_integrity import verify as verify_inputs +from simscene.verification.asset_gallery import verify_run +from simscene.verification.settling import stable + + +def sha(path): + digest = hashlib.sha256() + with path.open('rb') as stream: + for chunk in iter(lambda: stream.read(1024 * 1024), b''): + digest.update(chunk) + return digest.hexdigest() + + +def verify(run, example_directory): + root = Path(example_directory).resolve() + run = Path(run).resolve() + checks_path = root / 'supplemental-checks.json' + checks = json.loads(checks_path.read_text()) + selections = json.loads((root / 'assets.lock.json').read_text())['assets'] + selection = selections['cabinet'] + result = json.loads((run / 'result.json').read_text()) + spec = json.loads((run / 'spec.json').read_text()) + case = json.loads((run / 'acceptance-case.json').read_text()) + bindings = {role: {'asset_path': spec['objects'][role]['asset_path'], + 'asset_binding': spec['objects'][role]['asset_binding']} for role in selections} + template = json.loads((root / 'case.json').read_text()) + expected_case = freeze_case(template, bindings, selections)['case'] + inputs, evidence, core = verify_inputs(run), verify_evidence(run), verify_run(run) + frames = [result['initial_observation'], *result['samples']] + parent, door = checks['cabinet_parent'], checks['cabinet_child'] + records = [frame.get('mechanisms', {}).get('cabinet', {}).get('joints', {}).get('main', {}) for frame in frames] + + def finite(value): + return type(value) in (int, float) and math.isfinite(value) + + native = all(finite(record.get('native_position')) and finite(record.get('native_velocity')) and + record.get('native_measurement_source') == 'PhysX_articulation_tensor_DOF_readback_SI' and + finite(record.get('position')) and abs(record['native_position'] - record['position']) <= .015 + for record in records) + initial = frames[0]['positions'][parent] + displacements = [math.dist(initial, frame['positions'][parent]) for frame in frames] + contacts = set() + for frame in frames: + for pair in frame.get('contact_pairs', []): + actors = pair.get('actor_paths', []) + if len(actors) == 2 and pair.get('count', 0) > 0: + contacts.add(frozenset(actors)) + prop_bodies = [result['body_bindings'][name]['motion_body'] for name in checks['rigid_objects']] + forbidden = [sorted(pair) for pair in contacts if door in pair and any(body in pair for body in prop_bodies)] + keep = checks['reserved_volume'] + + def intersects(a, b): + return all(a['max'][i] > b['min'][i] and b['max'][i] > a['min'][i] for i in range(3)) + + prop_clear = all(not intersects(frame['bounds'][name], keep) for frame in frames for name in checks['rigid_objects']) + cabinet_contained = all(all(keep['min'][i] - .01 <= frame['bounds']['cabinet']['min'][i] and + frame['bounds']['cabinet']['max'][i] <= keep['max'][i] + .01 + for i in range(3)) for frame in frames) + obj = spec['objects']['cabinet'] + manifest = validate_asset_binding(obj['asset_binding'], require_dynamic=True, asset_path=obj['asset_path']) + package = Path(obj['asset_binding']['manifest_path']).parent + source_file = package / 'source' / selection['source_files'][0]['path'] + source = inspect_articulation(Usd.Stage.Open(str(source_file))) + source_joint, prepared_joint = source['joint_map']['main'], result['body_bindings']['cabinet']['joints']['main'] + joint_keys = ('type', 'axis', 'limits', 'position_unit', 'native_authored_attributes', + 'local_pos0_m', 'local_pos1_m', 'local_rot0_wxyz', 'local_rot1_wxyz') + source_masses = sorted(item['mass_kg'] for item in source['body_map'].values() if item.get('role') == 'rigid') + prepared_masses = sorted(item['mass_kg'] for item in manifest['body_map'].values() if item.get('role') == 'rigid') + note = case['components'][-1]['case']['physical_model_note'] + supplemental = { + 'case_matches_frozen_example': case == expected_case, + 'requirements_pinned_in_case': ('Supplemental acceptance SHA-256: ' + sha(checks_path)) in note, + 'native_dof_readback_each_step': native, + 'cabinet_supported_by_table': frozenset((parent, checks['support_actor'])) in contacts, + 'cabinet_settled_two_seconds': stable(frames, parent, result['simulation_time_s'], 2., + checks['max_linear_speed_m_s'], checks['max_angular_speed_rad_s']), + 'cabinet_translation_within_limit': max(displacements) <= checks['max_parent_translation_m'], + 'props_outside_reserved_sweep': prop_clear, + 'cabinet_inside_reserved_volume': cabinet_contained, + 'no_door_prop_contacts': not forbidden, + 'source_file_hash_matches_lock': sha(source_file) == selection['source_sha256'], + 'native_joint_attributes_preserved': all(source_joint.get(key) == prepared_joint.get(key) for key in joint_keys), + 'native_rigid_masses_preserved': len(source_masses) == 2 and source_masses == prepared_masses, + 'one_joint_binding': len(result['body_bindings']['cabinet']['joints']) == 1, + } + return {'schema': 'simscene.cabinet_layout_example_check.v1', 'run': str(run), + 'passed': (inputs['passed'] and evidence['passed'] and evidence['partial'] is False and + core['passed'] and all(supplemental.values())), + 'input_integrity': inputs, 'evidence_integrity': evidence, 'core_verification': core, + 'supplemental': supplemental, 'max_parent_translation_m': max(displacements), + 'native_dof_range_rad': [min(record['native_position'] for record in records if finite(record.get('native_position'))), + max(record['native_position'] for record in records if finite(record.get('native_position')))], + 'scope': 'One frozen layout and recorded run; not a general asset or structural certification.'} diff --git a/tests/agent/test_package.py b/tests/agent/test_package.py index 199df92..150dcf1 100644 --- a/tests/agent/test_package.py +++ b/tests/agent/test_package.py @@ -65,6 +65,11 @@ async def check_independent_metadata(root,plugin): response=await session.read_resource('simscene://recipes/examples') examples=json.loads(response.contents[0].text)['examples'] self.assertIn('automatic_cabinet_layout',{entry['id'] for entry in examples}) + response=await session.read_resource('simscene://runtime/identity') + identity=json.loads(response.contents[0].text) + self.assertEqual(Path(identity['module_path']).resolve(),(vendor/'simscene/__init__.py').resolve()) + self.assertEqual(Path(identity['worker_path']).resolve(),(vendor/'simscene/worker/isaac_run.py').resolve()) + self.assertEqual(identity['build_info']['python_version'],'0.2.0.dev2') response=await session.call_tool('catalog_search',{'query':'Original package fixture','filters':{'source_ids':['abo-glb']},'limit':1}) self.assertFalse(response.isError,str(response)) page=json.loads(response.content[0].text);self.assertEqual(len(page['items']),1) @@ -105,7 +110,8 @@ async def check_independent_metadata(root,plugin): 'experiments/acquire_recipe_assets.py', 'experiments/apply_scene_recipe.py', 'experiments/freeze_recipe_case.py', - 'experiments/check_motion_clearance.py'): + 'experiments/check_motion_clearance.py', + 'experiments/assemble_integration_receipt.py'): self.assertEqual((plugin/sample).read_bytes(),(ROOT/sample).read_bytes(),sample) for original in (ROOT/'skills').rglob('*.md'): reference=plugin/'skills'/original.relative_to(ROOT/'skills') diff --git a/tests/test_build_identity.py b/tests/test_build_identity.py new file mode 100644 index 0000000..34966f3 --- /dev/null +++ b/tests/test_build_identity.py @@ -0,0 +1,48 @@ +"""Package version must not substitute for its source revision and dirty state.""" +import subprocess +import shutil + +import pytest + +from plugins import build + + +def test_build_identity_reports_commit_and_uncommitted_changes(tmp_path): + subprocess.run(['git', 'init', '-q', str(tmp_path)], check=True) + (tmp_path / 'tracked.txt').write_text('one\n') + subprocess.run(['git', '-C', str(tmp_path), 'add', 'tracked.txt'], check=True) + subprocess.run(['git', '-C', str(tmp_path), '-c', 'user.name=Test', + '-c', 'user.email=test@example.invalid', 'commit', '-qm', 'baseline'], check=True) + assert hasattr(build, 'source_identity'), 'build source identity is missing' + clean = build.source_identity(tmp_path) + commit = subprocess.check_output(['git', '-C', str(tmp_path), 'rev-parse', 'HEAD'], text=True).strip() + assert clean == {'source_commit': commit, 'source_clean': True} + (tmp_path / 'tracked.txt').write_text('two\n') + assert build.source_identity(tmp_path) == {'source_commit': commit, 'source_clean': False} + + +def test_build_identity_does_not_inherit_an_enclosing_repository(tmp_path): + assert hasattr(build, 'source_identity'), 'build source identity is missing' + assert build.source_identity(tmp_path) == {'source_commit': None, 'source_clean': None} + + +def test_clean_build_snapshot_must_equal_the_committed_source_tree(tmp_path): + repo, snapshot = tmp_path / 'repo', tmp_path / 'snapshot' + repo.mkdir(); snapshot.mkdir() + subprocess.run(['git', 'init', '-q', str(repo)], check=True) + (repo / 'src/simscene').mkdir(parents=True) + (repo / 'src/simscene/__init__.py').write_text('value = 1\n') + for name in ('pyproject.toml', 'README.md', 'LICENSE'): + (repo / name).write_text(name + '\n') + subprocess.run(['git', '-C', str(repo), 'add', 'src', 'pyproject.toml', 'README.md', 'LICENSE'], check=True) + subprocess.run(['git', '-C', str(repo), '-c', 'user.name=Test', + '-c', 'user.email=test@example.invalid', 'commit', '-qm', 'baseline'], check=True) + commit = subprocess.check_output(['git', '-C', str(repo), 'rev-parse', 'HEAD'], text=True).strip() + shutil.copytree(repo / 'src', snapshot / 'src') + for name in ('pyproject.toml', 'README.md', 'LICENSE'): + shutil.copyfile(repo / name, snapshot / name) + assert hasattr(build, 'verify_source_snapshot'), 'clean-source snapshot verification is missing' + build.verify_source_snapshot(repo, snapshot, commit) + (snapshot / 'src/simscene/ignored.py').write_text('extra\n') + with pytest.raises(RuntimeError, match='snapshot'): + build.verify_source_snapshot(repo, snapshot, commit) diff --git a/tests/test_integration_delivery.py b/tests/test_integration_delivery.py new file mode 100644 index 0000000..1157cf8 --- /dev/null +++ b/tests/test_integration_delivery.py @@ -0,0 +1,139 @@ +"""A handoff must not turn missing or mismatched evidence into completion.""" +import hashlib +import importlib +import importlib.util +import json +from pathlib import Path +import sys +import zipfile +import os +import subprocess + +import pytest + + +def implementation(): + assert importlib.util.find_spec('simscene.recipes.integration_delivery') is not None, 'delivery handoff is unavailable' + return importlib.import_module('simscene.recipes.integration_delivery') + + +def digest(path): + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def media_fixture(tmp_path): + run = tmp_path / 'run-a' + run.mkdir() + lock = run / 'run-lock.json' + lock.write_text(json.dumps({'run_id': 'run-a'})) + evidence = run / 'evidence-lock.json' + evidence.write_text('{}') + source = run / 'camera_overview.mp4' + source.write_bytes(b'source') + frames = run / 'camera_overview.frames.jsonl' + frames.write_text('{}\n') + (run / 'result.json').write_text(json.dumps({'videos': {'overview': { + 'path': str(source), 'frame_manifest': str(frames)}}})) + video = tmp_path / 'edit.mp4' + video.write_bytes(b'edited') + manifest = {'schema': 'simscene.video_edit.v1', 'path': str(video), 'sha256': digest(video), + 'segments': [{'run_id': 'run-a', 'run_directory': str(run), 'camera': 'overview', + 'source': str(source), 'source_sha256': digest(source), + 'source_frame_manifest_sha256': digest(frames), + 'run_lock_sha256': digest(lock), 'evidence_lock_sha256': digest(evidence)}]} + return run, video, manifest + + +def test_missing_artifacts_produce_incomplete_receipt_without_automatic_review(tmp_path): + mod = implementation() + result = mod.collect_delivery({'scene': str(tmp_path / 'missing.json')}) + assert result['status'] == 'incomplete' + assert result['visual_review'] == 'not_supplied' + assert 'scene' in result['missing'] and 'run' in result['missing'] + assert result['physical_status'] == 'not_checked' + + +def test_receipt_helper_preserves_an_incomplete_result_and_existing_output(tmp_path): + script = Path(__file__).resolve().parents[1] / 'experiments/assemble_integration_receipt.py' + assert script.is_file(), 'installed receipt helper is unavailable' + output = tmp_path / 'receipt.json' + env = dict(os.environ, PYTHONPATH=str(Path(__file__).resolve().parents[1] / 'src')) + command = [sys.executable, str(script), '--output', str(output)] + first = subprocess.run(command, env=env, capture_output=True, text=True) + assert first.returncode == 2 + assert json.loads(output.read_text())['status'] == 'incomplete' + original = output.read_bytes() + second = subprocess.run(command, env=env, capture_output=True, text=True) + assert second.returncode != 0 and output.read_bytes() == original + + +def test_media_mapping_requires_the_actual_run_camera_and_frame_manifest(tmp_path): + mod = implementation() + run, video, edit = media_fixture(tmp_path) + assert mod.check_edit_binding(edit, video, run) == [] + wrong = json.loads(json.dumps(edit)) + wrong['segments'][0]['run_id'] = 'another-run' + assert mod.check_edit_binding(wrong, video, run) + wrong = json.loads(json.dumps(edit)) + wrong['segments'][0]['camera'] = 'another-camera' + assert mod.check_edit_binding(wrong, video, run) + (run / 'camera_overview.frames.jsonl').write_text('tampered\n') + assert mod.check_edit_binding(edit, video, run) + + +def test_visual_review_is_bound_to_the_actual_video_and_remains_a_declaration(tmp_path): + mod = implementation() + video = tmp_path / 'film.mp4' + video.write_bytes(b'candidate') + review = {'decision': 'accept', 'reviewer': 'human-or-agent', 'video_sha256': digest(video), + 'reviewed_windows': [{'start_s': 0., 'end_s': 1., 'observation': 'action visible'}]} + assert mod.check_visual_review(review, video, duration_s=1.) == [] + review['video_sha256'] = '0' * 64 + assert mod.check_visual_review(review, video, duration_s=1.) + review['video_sha256'] = digest(video) + review['reviewed_windows'] = [] + assert mod.check_visual_review(review, video, duration_s=1.) + + +def test_missing_review_does_not_hide_an_available_physical_result(tmp_path, monkeypatch): + mod = implementation() + from simscene.verification import automatic_cabinet_layout + run, example = tmp_path / 'run', tmp_path / 'example' + run.mkdir(); example.mkdir() + monkeypatch.setattr(automatic_cabinet_layout, 'verify', lambda *_: {'passed': True}) + result = mod.collect_delivery({'run': str(run), 'example_directory': str(example)}) + assert result['status'] == 'incomplete' + assert result['physical_status'] == 'passed' + assert result['visual_review'] == 'not_supplied' + + +def test_runtime_identity_must_match_the_actual_installed_build_record(tmp_path): + mod = implementation() + server = tmp_path / 'plugin/server' + package = server / 'vendor/simscene' + worker = package / 'worker/isaac_run.py' + worker.parent.mkdir(parents=True) + module = package / '__init__.py'; module.write_text('module') + mcp = package / 'mcp_server.py'; mcp.write_text('server') + worker.write_text('worker') + wheel = tmp_path / 'package.whl' + files = [module, mcp, worker] + with zipfile.ZipFile(wheel, 'w') as archive: + for item in files: + archive.write(item, 'simscene/' + str(item.relative_to(package))) + claimed = {'source_commit': 'a' * 40, 'source_clean': True, 'wheel_sha256': digest(wheel)} + (server / 'build-info.json').write_text(json.dumps(claimed)) + runtime = {'schema': 'simscene.runtime_identity.v1', 'module_path': str(module), + 'mcp_server_path': str(mcp), 'worker_path': str(worker), + 'module_sha256': digest(module), 'mcp_server_sha256': digest(mcp), + 'worker_sha256': digest(worker), 'build_info': claimed, + 'python_executable': sys.executable} + recorded = {str(item.relative_to(package)): digest(item) for item in files} + assert mod._identity_errors({'runtime_identity': runtime, 'wheel_path': str(wheel)}, + {'worker_code_sha256': recorded, 'queue_launcher_python': sys.executable}) == [] + # The same wheel and files exist, but the actual installed build-info + # names another commit. A supplied JSON claim cannot override it. + (server / 'build-info.json').write_text(json.dumps({**claimed, 'source_commit': 'b' * 40})) + errors = mod._identity_errors({'runtime_identity': runtime, 'wheel_path': str(wheel)}, + {'worker_code_sha256': recorded, 'queue_launcher_python': sys.executable}) + assert any('build' in error for error in errors) diff --git a/tests/test_recipe_io.py b/tests/test_recipe_io.py index 3e2e1b4..1a1a537 100644 --- a/tests/test_recipe_io.py +++ b/tests/test_recipe_io.py @@ -67,6 +67,20 @@ def test_portable_apply_injects_exact_current_binding_and_retains_legacy_strings forged=copy.deepcopy(recipe);forged['operations'][0]['object']['asset_path']='old.usda' with self.assertRaises(ValueError):io.resolve_operations(forged,{'payload':self.binding},selections={'payload':self.selection}) + def test_can_emit_resolved_operations_without_changing_a_scene(self): + recipe={'operations':[{'op':'add','id':'item','object':{'kind':'asset','dynamic':True,'asset_role':'payload'}}]} + for name,value in [('recipe',recipe),('catalog',{'payload':self.binding}), + ('lock',{'assets':{'payload':self.selection}})]: + (self.root/(name+'.json')).write_text(json.dumps(value)) + with patch('simscene.scene.SceneStore') as store: + self.assertEqual(applier.main([str(self.root/'recipe.json'),'--asset-catalog',str(self.root/'catalog.json'), + '--asset-lock',str(self.root/'lock.json'),'--save-directory',str(self.root/'out'), + '--operations-only']),0) + store.assert_not_called() + operations=json.loads((self.root/'out/resolved-operations.json').read_text()) + self.assertEqual(operations[0]['object'],dict(kind='asset',dynamic=True,**self.binding)) + self.assertFalse((self.root/'out/scene.json').exists()) + def test_source_profile_target_toolchain_and_complete_closure_are_mandatory(self): for key,value in [('source_sha256','f'*64),('profile_version',99),('target',{}),('toolchain',{}),('source_ref',dict(self.selection['source_ref'],asset_id='imposter'))]: bad=copy.deepcopy(self.selection);bad[key]=value From 3314aee5c6e873e74584399fc2d9e9148217093c Mon Sep 17 00:00:00 2001 From: shaoxiang <519517384@qq.com> Date: Tue, 17 Nov 2026 17:14:07 +0800 Subject: [PATCH 08/20] Preserve and repair unverified HF USD cache scans --- src/simscene/huggingface_cache.py | 24 +++++++++++++++++++++++- tests/test_dependency_repair_retry.py | 27 +++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/src/simscene/huggingface_cache.py b/src/simscene/huggingface_cache.py index 00ea19c..5d37fd8 100644 --- a/src/simscene/huggingface_cache.py +++ b/src/simscene/huggingface_cache.py @@ -208,8 +208,25 @@ def collect(value): status='missing' if unresolved else 'resolved_locally' except ImportError: unresolved=[];status='unverified_usd_tools_unavailable' - fingerprint=json.dumps({'source':source,'files':files,'dependency_scan_version':4},sort_keys=True,separators=(',',':')).encode() + identity={'source':source,'files':files,'dependency_scan_version':4} + fingerprint=json.dumps(identity,sort_keys=True,separators=(',',':')).encode() digest=hashlib.sha256(fingerprint).hexdigest();target=cache.directory/digest + if target.is_dir(): + # The old content fingerprint did not include scan outcome. + # A retry can resolve the same bytes after USD tools become + # available, or change the missing-dependency assessment + # without downloading another file. Preserve the old lock and + # publish a distinct immutable scan identity in that case. + cache._verified_cached(target,digest,source) + old=json.loads((target/'simscene-lock.json').read_text()) + old_missing=sorted(str(x).replace(str(target),'${PACKAGE_ROOT}') + for x in old.get('unresolved_dependencies',[])) + if (old.get('dependency_status')!=status or old_missing!=unresolved + or old.get('udim_patterns',{})!=udim_patterns): + identity.update(dependency_status=status,unresolved_dependencies=unresolved, + udim_patterns=udim_patterns) + fingerprint=json.dumps(identity,sort_keys=True,separators=(',',':')).encode() + digest=hashlib.sha256(fingerprint).hexdigest();target=cache.directory/digest unresolved=[x.replace('${PACKAGE_ROOT}',str(target)) for x in unresolved] metadata={'source':source,'repository':repo,'revision':revision,'package_sha256':digest,'root':str(target.joinpath(*root_path.parts)), 'files':files,'dependency_status':status,'unresolved_dependencies':unresolved,'repair_errors':errors,'license':'unknown', @@ -219,6 +236,11 @@ def collect(value): if size>package_limit:raise SearchError('Hugging Face package exceeds cache capacity or frozen package budget') if target.is_dir(): result=cache._verified_cached(target,digest,source) + persisted=json.loads((target/'simscene-lock.json').read_text()) + if (persisted.get('dependency_status')!=status + or sorted(persisted.get('unresolved_dependencies',[]))!=sorted(unresolved) + or persisted.get('udim_patterns',{})!=udim_patterns): + raise SearchError('cached USD scan identity differs from current result') else: cache._evict(size);output.rename(target);result=_runtime_status(metadata) cache._write_index(index,digest) diff --git a/tests/test_dependency_repair_retry.py b/tests/test_dependency_repair_retry.py index 5656968..ba09b14 100644 --- a/tests/test_dependency_repair_retry.py +++ b/tests/test_dependency_repair_retry.py @@ -45,6 +45,33 @@ def geturl(self): class DependencyRepairRetryTest(unittest.TestCase): + def test_hf_unverified_cache_can_be_rescanned_without_redownloading_or_mutating_it(self): + import builtins + real_import = builtins.__import__ + root_data = b'#usda 1.0\ndef Xform "Asset" {}\n' + calls = [] + def download(url, destination, budget): + calls.append(url); destination.write_bytes(root_data) + return len(root_data), hashlib.sha256(root_data).hexdigest() + def without_usd(name, *args, **kwargs): + if name == 'pxr': raise ImportError('USD intentionally unavailable') + return real_import(name, *args, **kwargs) + with tempfile.TemporaryDirectory() as directory: + with patch('simscene.huggingface_cache._download', side_effect=download), \ + patch('builtins.__import__', side_effect=without_usd): + first = huggingface_cache.acquire('org/models', 'a'*40, 'root.usda', directory, 100000) + self.assertEqual(first['dependency_status'], 'unverified_usd_tools_unavailable') + old_lock = Path(directory) / first['package_sha256'] / 'simscene-lock.json' + original = old_lock.read_bytes() + with patch('simscene.huggingface_cache._download', side_effect=AssertionError('unexpected download')): + repaired = huggingface_cache.acquire('org/models', 'a'*40, 'root.usda', directory, 100000) + warm = huggingface_cache.acquire('org/models', 'a'*40, 'root.usda', directory, 100000) + self.assertEqual(repaired['dependency_status'], 'resolved_locally') + self.assertNotEqual(repaired['package_sha256'], first['package_sha256']) + self.assertEqual(warm['package_sha256'], repaired['package_sha256']) + self.assertEqual(old_lock.read_bytes(), original) + self.assertEqual(len(calls), 1) + def test_usd_texture_404_then_restored_creates_new_lock_reusing_existing_root(self): available = False calls = [] From 4383d2d11c01292460396274f12f3b26be16b69a Mon Sep 17 00:00:00 2001 From: shaoxiang <519517384@qq.com> Date: Tue, 17 Nov 2026 17:56:14 +0800 Subject: [PATCH 09/20] Add bounded drawer payload experiment and paired verifier --- examples/integration_workspace/README.md | 29 ++ .../integration_workspace/assets.lock.json | 424 +++++++++++++++++ examples/integration_workspace/case.json | 157 ++++++ examples/integration_workspace/check.py | 23 + .../integration_workspace/recipe-control.json | 414 ++++++++++++++++ examples/integration_workspace/recipe.json | 450 ++++++++++++++++++ plugins/build.py | 1 + .../references/integration-workspace.md | 12 +- src/simscene/recipes/data/fixed-examples.json | 16 + .../verification/drawer_payload_pair.py | 417 ++++++++++++++++ tests/agent/test_package.py | 5 + tests/test_drawer_payload_pair.py | 93 ++++ tests/test_integration_example_registry.py | 2 +- 13 files changed, 2041 insertions(+), 2 deletions(-) create mode 100644 examples/integration_workspace/README.md create mode 100644 examples/integration_workspace/assets.lock.json create mode 100644 examples/integration_workspace/case.json create mode 100644 examples/integration_workspace/check.py create mode 100644 examples/integration_workspace/recipe-control.json create mode 100644 examples/integration_workspace/recipe.json create mode 100644 src/simscene/verification/drawer_payload_pair.py create mode 100644 tests/test_drawer_payload_pair.py diff --git a/examples/integration_workspace/README.md b/examples/integration_workspace/README.md new file mode 100644 index 0000000..138733e --- /dev/null +++ b/examples/integration_workspace/README.md @@ -0,0 +1,29 @@ +# Drawer and payload workspace + +This model-free recipe combines one pinned USDCraft two-drawer cabinet, one +independent GSO box and two ABO notebook props. The payload's 0.12 kg mass and +the prop scale are explicit experimental assumptions. Both drawers use +scheduled, bounded position drives; no passive triggering is claimed. + +1. Read `assets.lock.json`, search the indicated sources, and prepare the + selected revisions and parameters. Supply bindings for `cabinet`, `box` + and `book_a`; the second notebook reuses `book_a`'s prepared model. +2. Resolve `recipe.json` and `recipe-control.json` separately with the packaged + `apply_scene_recipe.py --operations-only` helper, then apply each batch with + MCP `scene_apply` to a separate new scene. The control removes every lower + drawer drive command and leaves the upper schedule and other objects alone. +3. Use `freeze_recipe_case.py case.json --bindings ... --asset-lock ... + --output ...` **once** and pass those exact case bytes to both 600-step, + seed-42 Isaac CPU runs. The upper hold is steps 130–149, the lower hold is + 270–359, and the final observation covers steps 540–600. +4. Run `check.py --positive RUN_DIR --control RUN_DIR --case FROZEN_CASE + --output NEW_REPORT`. It verifies input/output locks, the unique control + difference, independent rigid body and native collider geometry, actual + joint/pose measurements, contacts, support and final stability. Check the + two native camera recordings and supply a separate visual review. + +This example is limited to its pinned assets, sizes, measured collision cavity, +drive schedule and engine configuration. A geometric precheck or successful +asset preparation is not physical evidence; a new run needs new results. Contact +callbacks demonstrate recorded contact and do not certify that every possible +penetration was detected. Assets and large recordings are acquired separately. diff --git a/examples/integration_workspace/assets.lock.json b/examples/integration_workspace/assets.lock.json new file mode 100644 index 0000000..5aaab4a --- /dev/null +++ b/examples/integration_workspace/assets.lock.json @@ -0,0 +1,424 @@ +{ + "schema": "simscene.selected_assets.v2", + "assets": { + "cabinet": { + "provider": "prepared", + "source_ref": { + "source_id": "usdcraft", + "asset_id": "ds_R022_02", + "revision": "92f4e908415d7532a02661d6502ab49dc3aa33f9", + "variant_id": null + }, + "profile_id": "articulated_prop_v2", + "profile_version": 1, + "parameters": { + "ccd": false, + "collision_method": "preserve", + "dynamic_friction": 0.5, + "proxy_tolerance_m": 0.002, + "restitution": 0.05, + "scale_mode": "preserve", + "source_physics_policy": "preserve_valid", + "static_friction": 0.6 + }, + "target": { + "engine": "physx", + "isaac_version": "6.2.0-rc.14+release.52805.02189a84.gl", + "platform": "linux-x86_64", + "usd_version": "0.25.11" + }, + "toolchain": { + "backend": "openusd", + "version": "0.25.11" + }, + "source_sha256": "e5070e0690c183629f0d24d2465d5ff0b53b88cd71b3682200650e05e009c7d0", + "source_closure_sha256": "3934e7dd6491d60e8db89ef41622cc9755bedca50099b68d9bb425ac6043519c", + "source_files": [ + { + "path": "rigid/kitchen_dining/R022_kitchen_drawer_unit/02_two_drawer_wide_unit/physx/model.usdc", + "size_bytes": 40680, + "sha256": "e5070e0690c183629f0d24d2465d5ff0b53b88cd71b3682200650e05e009c7d0" + } + ], + "previous_preparation": { + "prepared_id": "604117a7eca56e8899599e8498affea3276c86568489f7130a5e3e09e3cae9f0", + "manifest_sha256": "3091ae026b94baca2c73fedc0accf96971024d2e4c058d5f93e35f1e913afd6a", + "source_manifest_sha256": "08ad6fd8f3bb13a3ed2e7160e7dcdda91cad1ee1a42cd4f2540c298e14b77170", + "scope": "informational; rebuild may change absolute provenance; no physics verdict reused" + }, + "source_record": { + "ref": { + "asset_id": "ds_R022_02", + "revision": "92f4e908415d7532a02661d6502ab49dc3aa33f9", + "source_id": "usdcraft", + "variant_id": null + }, + "title": "Two-Drawer Wide Unit", + "format": "usd", + "entry_path": "rigid/kitchen_dining/R022_kitchen_drawer_unit/02_two_drawer_wide_unit/physx/model.usdc", + "license": { + "basis": "pinned_USDCraft_asset_distribution_card", + "evidence": "declared", + "license": "Apache-2.0", + "notices_required": true, + "status": "known" + }, + "availability": { + "acquisition": { + "dependency_mode": "inspect_selected_usd_closure", + "files": [ + { + "path": "rigid/kitchen_dining/R022_kitchen_drawer_unit/02_two_drawer_wide_unit/physx/model.usdc", + "sha256": "e5070e0690c183629f0d24d2465d5ff0b53b88cd71b3682200650e05e009c7d0", + "size": null + } + ], + "files_complete": false, + "kind": "hf_usd_package", + "package_path": "rigid/kitchen_dining/R022_kitchen_drawer_unit/02_two_drawer_wide_unit", + "path": "rigid/kitchen_dining/R022_kitchen_drawer_unit/02_two_drawer_wide_unit/physx/model.usdc", + "repository": "nvidia/USDCraft-10K", + "revision": "92f4e908415d7532a02661d6502ab49dc3aa33f9" + }, + "estimated_download_bytes": null, + "files_complete": false, + "granularity": "dependency_closure", + "status": "declared" + }, + "provenance": { + "has_textures": { + "evidence": "declared", + "value": false + }, + "license_scope": "USDCraft-generated native distribution; not a license rule for arbitrary owner packages", + "metadata_revision": "92f4e908415d7532a02661d6502ab49dc3aa33f9", + "original_metadata": { + "category": "Kitchen Drawer Unit", + "category_id": "R022", + "group": "kitchen_dining", + "has_textures": "false", + "joint_count": "2", + "joint_types": "prismatic", + "object_id": "ds_R022_02", + "part_count": "3", + "path": "rigid/kitchen_dining/R022_kitchen_drawer_unit/02_two_drawer_wide_unit", + "physics_type": "articulated", + "physx_sha256": "e5070e0690c183629f0d24d2465d5ff0b53b88cd71b3682200650e05e009c7d0", + "prompt": "Wide kitchen drawer unit, 90 x 60 x 87 cm, in matte graphite-painted wood with two large drawers and a marble-look stone top. Long brass bar handles sit on each drawer, with a flat plinth base and smooth drawer fronts. To store pots and utensils, the user grips a long brass bar handle and pulls a drawer out; each drawer slides out up to 50 cm on prismatic metal rails; every part is a rigid body, with no deformable, cloth, soft-volume or dynamic rod parts.", + "title": "Two-Drawer Wide Unit" + }, + "repository": "nvidia/USDCraft-10K", + "unit_axis_evidence": "dataset_card_declared_meters_Z_up" + } + } + }, + "box": { + "provider": "prepared", + "source_ref": { + "source_id": "gso-glb", + "asset_id": "ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box", + "revision": "75e8895e4f4e854cddd7009a7e60f86812041012", + "variant_id": null + }, + "profile_id": "rigid_prop_v1", + "profile_version": 1, + "parameters": { + "ccd": true, + "collision_method": "convex_hull", + "dynamic_friction": 0.5, + "mass_kg": 0.12, + "mass_note": "Experimental120mm scaled scanned box/.12kg assumption; not manufacturer values.", + "proxy_tolerance_m": 0.002, + "restitution": 0.05, + "scale_mode": "fit_longest", + "source_physics_policy": "reject_if_physics", + "static_friction": 0.6, + "target_longest_extent_m": 0.12 + }, + "target": { + "engine": "physx", + "isaac_version": "6.2.0-rc.14+release.52805.02189a84.gl", + "platform": "linux-x86_64", + "usd_version": "0.25.11" + }, + "toolchain": { + "backend": "omni.kit.asset_converter", + "canonicalization": "explicit_Rx90_once", + "codec_policy_version": 2, + "predecoder": { + "backend": "gltf-transform-meshopt", + "core_version": "4.5.1", + "extensions_version": "4.5.1", + "max_decoded_bytes": 268435456, + "meshoptimizer_version": "1.3.0", + "node_modules_sha256": "3bfdef144f9a32d73ab5147f5be0dcd2e9e731a28b56f9ae7e521a46e590c302", + "node_version": "v22.23.2", + "package_lock_sha256": "bac0ab1332c821de5680b887f828014d86a71eb930b14d91fd938e36c45bdff0", + "script_sha256": "06af0eaf70d3cfda095cadef3de0afde388d1c9b4ba1e930d408e95c002602e4" + }, + "usd_version": "0.25.11", + "version": "6.1.0" + }, + "source_sha256": "5454424606ed780b806c99a5a3ffc0f4b0b9ade2fc9afa9c63fbf932ea187949", + "source_closure_sha256": "c2800268fbde5b01d93558746942ffc8446780f390573605f2979056c6223975", + "source_files": [ + { + "path": "README.md", + "size_bytes": 11624, + "sha256": "a283318ac5c8990a1fb49ddd5b2f2f91aaaddece678e3a97941e90b29deb8ad9" + }, + { + "path": "objects/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box.glb", + "size_bytes": 263232, + "sha256": "5454424606ed780b806c99a5a3ffc0f4b0b9ade2fc9afa9c63fbf932ea187949" + } + ], + "previous_preparation": { + "prepared_id": "dd50547b39fed14df8ddecbe15ee71952928b21b43fb302cc105aece9e66947b", + "manifest_sha256": "52de9211b27fc73eaaadedd4725f1122224c0f31d5ab07a95baa340902244990", + "source_manifest_sha256": "bd310cb197a405b1671b990a1daeb72be6062d4419fadf252dd88ed8f23e6c67", + "scope": "informational; rebuild may change absolute provenance; no physics verdict reused" + }, + "source_record": { + "ref": { + "asset_id": "ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box", + "revision": "75e8895e4f4e854cddd7009a7e60f86812041012", + "source_id": "gso-glb", + "variant_id": null + }, + "title": "Ready-to-Use Rolled Fondant, Pure White - 24 oz box", + "format": "glb", + "entry_path": "objects/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box.glb", + "license": { + "basis": "object_metadata_row", + "evidence": "declared", + "license": "CC-BY-4.0", + "notices_required": true, + "status": "known" + }, + "availability": { + "acquisition": { + "additional_paths": [ + "README.md" + ], + "kind": "hf_single_glb", + "path": "objects/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box.glb", + "repository": "codepawl/scanned-objects-glb", + "revision": "75e8895e4f4e854cddd7009a7e60f86812041012" + }, + "estimated_download_bytes": 263232, + "files_complete": null, + "granularity": "single_file", + "status": "declared" + }, + "provenance": { + "mass_estimate_note": "metadata estimates are not measured/manufacturer dynamics", + "metadata_revision": "75e8895e4f4e854cddd7009a7e60f86812041012", + "original_metadata": { + "brand": "Ready-to-Use", + "category": "food and drink", + "category_source": "name rule", + "file": "objects/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box.glb", + "file_name": "engine/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box.glb", + "id": "ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box", + "license": "CC-BY-4.0", + "mass_estimate_kg": 0.2866, + "mpn": null, + "name": "Ready-to-Use Rolled Fondant, Pure White - 24 oz box", + "pack_bytes": 263232, + "pack_texture_px": 2048, + "size_metres": [ + 0.1217, + 0.1687, + 0.0491 + ], + "sku": "00070896423016", + "source": "https://fuel.gazebosim.org/1.0/GoogleResearch/models/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box", + "source_bytes": 13264125, + "source_categories": [ + "Consumer Goods" + ], + "source_texture_px": 4096, + "thumb": "thumbs/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box.webp", + "triangles": 1744, + "vertices": 949 + }, + "relationship": "community_conversion", + "repository": "codepawl/scanned-objects-glb", + "selected_variant": "standard_objects_glb", + "upstream_source": "https://fuel.gazebosim.org/1.0/GoogleResearch/models/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box", + "viewer_variant_not_selected": "engine/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box.glb" + } + } + }, + "book_a": { + "provider": "prepared", + "source_ref": { + "source_id": "abo-glb", + "asset_id": "B01DN8TB5U", + "revision": "c7c8293fed3b7ab122ef5d7896521a187e0962d7", + "variant_id": null + }, + "profile_id": "rigid_prop_v1", + "profile_version": 1, + "parameters": { + "ccd": true, + "collision_method": "convex_hull", + "dynamic_friction": 0.5, + "mass_kg": 0.12, + "mass_note": "Experimental 150mm scaled notebook surrogate for 200mm routing channels; mass assumption, not full-size manufacturer specification.", + "proxy_tolerance_m": 0.002, + "restitution": 0.05, + "scale_mode": "fit_longest", + "source_physics_policy": "reject_if_physics", + "static_friction": 0.6, + "target_longest_extent_m": 0.15 + }, + "target": { + "engine": "physx", + "isaac_version": "6.2.0-rc.14+release.52805.02189a84.gl", + "platform": "linux-x86_64", + "usd_version": "0.25.11" + }, + "toolchain": { + "backend": "omni.kit.asset_converter", + "canonicalization": "explicit_Rx90_once", + "codec_policy_version": 2, + "predecoder": { + "backend": "gltf-transform-meshopt", + "core_version": "4.5.1", + "extensions_version": "4.5.1", + "max_decoded_bytes": 268435456, + "meshoptimizer_version": "1.3.0", + "node_modules_sha256": "3bfdef144f9a32d73ab5147f5be0dcd2e9e731a28b56f9ae7e521a46e590c302", + "node_version": "v22.23.2", + "package_lock_sha256": "bac0ab1332c821de5680b887f828014d86a71eb930b14d91fd938e36c45bdff0", + "script_sha256": "06af0eaf70d3cfda095cadef3de0afde388d1c9b4ba1e930d408e95c002602e4" + }, + "usd_version": "0.25.11", + "version": "6.1.0" + }, + "source_sha256": "67d61db31084d820ca9b1b0d2d3761662f6a5532944573afceee8f57c8151845", + "source_closure_sha256": "6dbe5eddcba3d8c26d5b3f27a0272a59420e565492957a3cbfef22753a87de9a", + "source_files": [ + { + "path": "LICENSE-CC-BY-4.0.txt", + "size_bytes": 14527, + "sha256": "419896aea50c15d6e40c5b4baf4bd346f78223b9a354c7357ad00262afdc08ec" + }, + { + "path": "objects/B01DN8TB5U/B01DN8TB5U.glb", + "size_bytes": 524720, + "sha256": "67d61db31084d820ca9b1b0d2d3761662f6a5532944573afceee8f57c8151845" + } + ], + "previous_preparation": { + "prepared_id": "4f6ada04a8274c8ce1dadbd4a13242ab1f688b407e09d106cab2f613795684ec", + "manifest_sha256": "c00b0427d407b564b116c7b79426f9db3d5ccc1ed239e68186484918e85a759b", + "source_manifest_sha256": "7d3ae44fb94faa434650be896d80eb6b2fdff835a276afdafff3bc077bd0fc6a", + "scope": "informational; rebuild may change absolute provenance; no physics verdict reused" + }, + "source_record": { + "ref": { + "asset_id": "B01DN8TB5U", + "revision": "c7c8293fed3b7ab122ef5d7896521a187e0962d7", + "source_id": "abo-glb", + "variant_id": null + }, + "title": "AmazonBasics Classic Blank Notebook, 240 Pages, Hardcover - Plain", + "format": "glb", + "entry_path": "objects/B01DN8TB5U/B01DN8TB5U.glb", + "license": { + "basis": "dataset_card", + "evidence": "declared", + "license": "CC-BY-4.0", + "notices_required": true, + "status": "known" + }, + "availability": { + "acquisition": { + "kind": "hf_single_glb", + "path": "objects/B01DN8TB5U/B01DN8TB5U.glb", + "repository": "codepawl/abo-glb", + "revision": "c7c8293fed3b7ab122ef5d7896521a187e0962d7" + }, + "estimated_download_bytes": 524720, + "files_complete": null, + "granularity": "single_file", + "status": "declared" + }, + "provenance": { + "coordinate_system": "Y-up", + "dimensions_evidence": "declared", + "license": "CC-BY-4.0", + "metadata_revision": "c7c8293fed3b7ab122ef5d7896521a187e0962d7", + "original_metadata": { + "amazon_item_ids": [ + "B01DN8TB5U" + ], + "bounds_min": [ + -0.0635, + 0, + -0.0079 + ], + "brand": "AmazonBasics", + "catalog_dimensions_cm": { + "height": 12.7, + "length": 21, + "width": 1.5 + }, + "catalog_weight_kg": null, + "color": "Black", + "domain": "amazon.com", + "file": "objects/B01DN8TB5U/B01DN8TB5U.glb", + "hull_volume_m3": 0.00041, + "id": "B01DN8TB5U", + "ktx2_bytes": 634804, + "ktx2_file": "objects_ktx2/B01DN8TB5U/B01DN8TB5U.glb", + "lods": [ + { + "bytes": 182952, + "file": "lods/B01DN8TB5U/B01DN8TB5U_lod1.glb", + "texture_px": 1024, + "triangles": 786 + }, + { + "bytes": 50384, + "file": "lods/B01DN8TB5U/B01DN8TB5U_lod2.glb", + "texture_px": 512, + "triangles": 314 + }, + { + "bytes": 20140, + "file": "lods/B01DN8TB5U/B01DN8TB5U_lod3.glb", + "texture_px": 256, + "triangles": 220 + } + ], + "material": null, + "materials": 1, + "name": "AmazonBasics Classic Blank Notebook, 240 Pages, Hardcover - Plain", + "pack_bytes": 524720, + "product_type": "paper product", + "size_metres": [ + 0.127, + 0.2128, + 0.0157 + ], + "source_bytes": 14891808, + "source_texture_px": 4096, + "style": "Plain", + "texture_vram_mib_ktx2": 12, + "texture_vram_mib_webp": 64, + "triangles": 1574, + "vertices": 1164 + }, + "relationship": "community_conversion", + "repository": "codepawl/abo-glb", + "upstream_asset_id": "B01DN8TB5U", + "upstream_source": "amazon-berkeley-objects" + } + } + } + } +} diff --git a/examples/integration_workspace/case.json b/examples/integration_workspace/case.json new file mode 100644 index 0000000..006e6fe --- /dev/null +++ b/examples/integration_workspace/case.json @@ -0,0 +1,157 @@ +{ + "schema": "simscene.drawer_payload_pair.v1", + "steps": 600, + "seed": 42, + "physics_device": "cpu", + "physics_dt_s": 0.016666666666666666, + "windows": { + "reference_step": 209, + "upper_hold": [ + 130, + 149 + ], + "lower_hold": [ + 270, + 359 + ], + "lower_motion": [ + 210, + 359 + ], + "final": [ + 540, + 600 + ] + }, + "positive_commands": [ + { + "joint_id": "joint0", + "trigger": { + "type": "at_step", + "physics_step": 0 + }, + "target_position": 0.0, + "position_unit": "m", + "stiffness": 2000.0, + "damping": 100.0, + "max_effort": 400.0 + }, + { + "joint_id": "joint1", + "trigger": { + "type": "at_step", + "physics_step": 0 + }, + "target_position": 0.0, + "position_unit": "m", + "stiffness": 2000.0, + "damping": 100.0, + "max_effort": 400.0 + }, + { + "joint_id": "joint1", + "trigger": { + "type": "at_step", + "physics_step": 60 + }, + "target_position": 0.35, + "position_unit": "m", + "stiffness": 2000.0, + "damping": 100.0, + "max_effort": 400.0 + }, + { + "joint_id": "joint1", + "trigger": { + "type": "at_step", + "physics_step": 150 + }, + "target_position": 0.0, + "position_unit": "m", + "stiffness": 2000.0, + "damping": 100.0, + "max_effort": 400.0 + }, + { + "joint_id": "joint0", + "trigger": { + "type": "at_step", + "physics_step": 210 + }, + "target_position": 0.25, + "position_unit": "m", + "stiffness": 2000.0, + "damping": 100.0, + "max_effort": 400.0 + }, + { + "joint_id": "joint0", + "trigger": { + "type": "at_step", + "physics_step": 360 + }, + "target_position": 0.0, + "position_unit": "m", + "stiffness": 2000.0, + "damping": 100.0, + "max_effort": 400.0 + } + ], + "bindings": { + "cabinet": { + "manifest_sha256": "${cabinet.manifest_sha256}", + "source_ref": "${cabinet.source_ref}" + }, + "box": { + "manifest_sha256": "${box.manifest_sha256}", + "source_ref": "${box.source_ref}" + }, + "book_a": { + "manifest_sha256": "${book_a.manifest_sha256}", + "source_ref": "${book_a.source_ref}" + }, + "book_b": { + "manifest_sha256": "${book_a.manifest_sha256}", + "source_ref": "${book_a.source_ref}" + } + }, + "payload_collider_bounds_local": { + "min": [ + -0.043444233058121486, + -0.01748791165556678, + 2.8436708363571756e-06 + ], + "max": [ + 0.04312334993721854, + 0.017467988986744804, + 0.1200028468527472 + ] + }, + "support_bounds_local": { + "min": [ + -0.4069, + 0.0161, + -0.155 + ], + "max": [ + 0.4069, + 0.4959, + 0.15 + ] + }, + "allowed_bottom_z_local": [ + -0.155, + -0.14 + ], + "thresholds": { + "target_error_m": 0.01, + "control_displacement_m": 0.005, + "relative_drift_m": 0.02, + "final_joint_error_m": 0.01, + "table_drift_m": 0.002, + "tilt_deg": 10.0, + "joint_reconstruction_error_m": 0.001, + "min_drawer_travel_m": 0.2, + "min_payload_fraction": 0.8 + } +} diff --git a/examples/integration_workspace/check.py b/examples/integration_workspace/check.py new file mode 100644 index 0000000..0335d0f --- /dev/null +++ b/examples/integration_workspace/check.py @@ -0,0 +1,23 @@ +"""Check one frozen positive/control pair for the fixed drawer workspace.""" +import argparse +import json +from pathlib import Path + +from simscene.verification.drawer_payload_pair import verify_pair + + +def main(): + parser=argparse.ArgumentParser(description=__doc__) + parser.add_argument('--positive',required=True) + parser.add_argument('--control',required=True) + parser.add_argument('--case',required=True) + parser.add_argument('--output',required=True,help='new report path; existing evidence is preserved') + args=parser.parse_args() + report=verify_pair(args.positive,args.control,args.case) + with Path(args.output).open('x',encoding='utf8') as stream: + json.dump(report,stream,ensure_ascii=False,indent=2,allow_nan=False);stream.write('\n') + print(json.dumps({'passed':report['passed'],'output':args.output,'errors':report['errors']},ensure_ascii=False)) + return 0 if report['passed'] else 1 + + +if __name__=='__main__':raise SystemExit(main()) diff --git a/examples/integration_workspace/recipe-control.json b/examples/integration_workspace/recipe-control.json new file mode 100644 index 0000000..488bd1d --- /dev/null +++ b/examples/integration_workspace/recipe-control.json @@ -0,0 +1,414 @@ +{ + "description": "Matched control; remove only all lower drawer drive commands.", + "operations": [ + { + "op": "add", + "id": "floor", + "object": { + "kind": "box", + "size": [ + 7.0, + 7.0, + 0.1 + ], + "position": [ + 0.0, + 0.0, + -0.05 + ], + "color": [ + 0.16, + 0.19, + 0.22 + ], + "collision": true + } + }, + { + "op": "add", + "id": "table", + "object": { + "kind": "box", + "size": [ + 2.6, + 1.5, + 0.08 + ], + "position": [ + 0.0, + 0.0, + 0.79 + ], + "color": [ + 0.48, + 0.32, + 0.2 + ], + "support_surfaces": { + "worktop": { + "min_xy": [ + -1.28, + -0.73 + ], + "max_xy": [ + 1.28, + 0.73 + ], + "z_m": 0.04 + } + }, + "collision": true + } + }, + { + "op": "add", + "id": "cabinet", + "object": { + "kind": "asset", + "dynamic": true, + "position": [ + -1.8, + 0.0, + 0.005 + ], + "mechanism": { + "commands": [ + { + "joint_id": "joint1", + "trigger": { + "type": "at_step", + "physics_step": 0 + }, + "target_position": 0.0, + "position_unit": "m", + "stiffness": 2000.0, + "damping": 100.0, + "max_effort": 400.0 + }, + { + "joint_id": "joint1", + "trigger": { + "type": "at_step", + "physics_step": 60 + }, + "target_position": 0.35, + "position_unit": "m", + "stiffness": 2000.0, + "damping": 100.0, + "max_effort": 400.0 + }, + { + "joint_id": "joint1", + "trigger": { + "type": "at_step", + "physics_step": 150 + }, + "target_position": 0.0, + "position_unit": "m", + "stiffness": 2000.0, + "damping": 100.0, + "max_effort": 400.0 + } + ] + }, + "asset_role": "cabinet" + } + }, + { + "op": "add", + "id": "box", + "object": { + "kind": "asset", + "dynamic": true, + "position": [ + -1.8, + -0.08, + 0.1594879117077209 + ], + "orientation_wxyz": [ + 0.7071067811865476, + 0.7071067811865476, + 0, + 0 + ], + "asset_role": "box" + } + }, + { + "op": "add", + "id": "book_a", + "object": { + "kind": "asset", + "dynamic": true, + "position": [ + 0.26289903053234287, + 0.3871088653379733, + 0.8755482700515308 + ], + "orientation_wxyz": [ + 0.7071067811865476, + 0.7071067811865476, + 0.0, + 0.0 + ], + "asset_role": "book_a" + } + }, + { + "op": "add", + "id": "book_b", + "object": { + "kind": "asset", + "dynamic": true, + "position": [ + 0.8113178607321683, + -0.37845832407133945, + 0.8755482659645383 + ], + "orientation_wxyz": [ + 0.6532814824381883, + 0.6532814824381883, + 0.2705980500730985, + 0.2705980500730985 + ], + "asset_role": "book_a" + } + }, + { + "op": "add", + "id": "sky", + "object": { + "kind": "light", + "light": { + "type": "dome" + }, + "intensity": 500.0 + } + }, + { + "op": "add", + "id": "key", + "object": { + "kind": "light", + "light": { + "type": "sphere", + "radius_m": 0.4 + }, + "intensity": 2000.0, + "position": [ + 0.0, + -2.5, + 4.5 + ] + } + }, + { + "op": "add", + "id": "drawer_fill", + "object": { + "kind": "light", + "light": { + "type": "sphere", + "radius_m": 0.15 + }, + "position": [ + -1.8, + -0.52, + 0.85 + ], + "intensity": 1600.0 + } + }, + { + "op": "add", + "id": "overview", + "object": { + "kind": "camera", + "position": [ + 1.4, + -4.6, + 2.65 + ], + "record_fps": 30, + "preview_fps": 1, + "camera": { + "resolution": [ + 1920, + 1080 + ], + "focal_length_mm": 45.0, + "horizontal_aperture_mm": 36.0, + "focus_distance_m": 4.8, + "clipping_range_m": [ + 0.01, + 100.0 + ] + }, + "orientation_wxyz": [ + 0.8185196451622787, + 0.5388608160686871, + 0.10949889232068281, + 0.1663267987119022 + ] + } + }, + { + "op": "add", + "id": "leg_lf", + "object": { + "kind": "box", + "size": [ + 0.09, + 0.09, + 0.75 + ], + "position": [ + -1.12, + -0.57, + 0.375 + ], + "color": [ + 0.16, + 0.15, + 0.14 + ] + } + }, + { + "op": "add", + "id": "leg_lb", + "object": { + "kind": "box", + "size": [ + 0.09, + 0.09, + 0.75 + ], + "position": [ + -1.12, + 0.57, + 0.375 + ], + "color": [ + 0.16, + 0.15, + 0.14 + ] + } + }, + { + "op": "add", + "id": "leg_rf", + "object": { + "kind": "box", + "size": [ + 0.09, + 0.09, + 0.75 + ], + "position": [ + 1.12, + -0.57, + 0.375 + ], + "color": [ + 0.16, + 0.15, + 0.14 + ] + } + }, + { + "op": "add", + "id": "leg_rb", + "object": { + "kind": "box", + "size": [ + 0.09, + 0.09, + 0.75 + ], + "position": [ + 1.12, + 0.57, + 0.375 + ], + "color": [ + 0.16, + 0.15, + 0.14 + ] + } + }, + { + "op": "add", + "id": "detail", + "object": { + "kind": "camera", + "position": [ + -1.7, + -0.9, + 1.8 + ], + "orientation_wxyz": [ + 0.9830976922196835, + 0.15659550134871766, + 0.014920563115266527, + 0.09367045054871734 + ], + "record_fps": 30, + "preview_fps": 1, + "camera": { + "resolution": [ + 1920, + 1080 + ], + "focal_length_mm": 35.0, + "horizontal_aperture_mm": 36.0, + "focus_distance_m": 1.8, + "clipping_range_m": [ + 0.01, + 100.0 + ] + } + } + }, + { + "op": "set_presentation", + "presentation": { + "profile": "technical_showcase_1080p", + "capture": { + "resolution": [ + 1920, + 1080 + ], + "fps": 30, + "anti_aliasing": "dlaa", + "renderer": "RealTimePathTracing", + "depth_of_field": false, + "motion_blur": false, + "exposure_mode": "manual", + "exposure_ev": 0 + }, + "budget": { + "max_cameras": 2, + "max_recording_bytes": 4294967296, + "min_free_bytes": 4294967296 + }, + "diagnostics": { + "png_seconds": 0.1, + "keyframe_interval_s": 2 + } + } + }, + { + "op": "set_observation", + "observation": { + "sample_interval_steps": 1, + "strict_start": true, + "record_contact_pairs": true + } + } + ], + "schema": "simscene.scene_recipe.v2" +} diff --git a/examples/integration_workspace/recipe.json b/examples/integration_workspace/recipe.json new file mode 100644 index 0000000..18e17da --- /dev/null +++ b/examples/integration_workspace/recipe.json @@ -0,0 +1,450 @@ +{ + "description": "Two scheduled USDCraft drawers, independent GSO payload and two ABO notebook props; a matching control removes all lower drawer commands.", + "operations": [ + { + "op": "add", + "id": "floor", + "object": { + "kind": "box", + "size": [ + 7.0, + 7.0, + 0.1 + ], + "position": [ + 0.0, + 0.0, + -0.05 + ], + "color": [ + 0.16, + 0.19, + 0.22 + ], + "collision": true + } + }, + { + "op": "add", + "id": "table", + "object": { + "kind": "box", + "size": [ + 2.6, + 1.5, + 0.08 + ], + "position": [ + 0.0, + 0.0, + 0.79 + ], + "color": [ + 0.48, + 0.32, + 0.2 + ], + "support_surfaces": { + "worktop": { + "min_xy": [ + -1.28, + -0.73 + ], + "max_xy": [ + 1.28, + 0.73 + ], + "z_m": 0.04 + } + }, + "collision": true + } + }, + { + "op": "add", + "id": "cabinet", + "object": { + "kind": "asset", + "dynamic": true, + "position": [ + -1.8, + 0.0, + 0.005 + ], + "mechanism": { + "commands": [ + { + "joint_id": "joint0", + "trigger": { + "type": "at_step", + "physics_step": 0 + }, + "target_position": 0.0, + "position_unit": "m", + "stiffness": 2000.0, + "damping": 100.0, + "max_effort": 400.0 + }, + { + "joint_id": "joint1", + "trigger": { + "type": "at_step", + "physics_step": 0 + }, + "target_position": 0.0, + "position_unit": "m", + "stiffness": 2000.0, + "damping": 100.0, + "max_effort": 400.0 + }, + { + "joint_id": "joint1", + "trigger": { + "type": "at_step", + "physics_step": 60 + }, + "target_position": 0.35, + "position_unit": "m", + "stiffness": 2000.0, + "damping": 100.0, + "max_effort": 400.0 + }, + { + "joint_id": "joint1", + "trigger": { + "type": "at_step", + "physics_step": 150 + }, + "target_position": 0.0, + "position_unit": "m", + "stiffness": 2000.0, + "damping": 100.0, + "max_effort": 400.0 + }, + { + "joint_id": "joint0", + "trigger": { + "type": "at_step", + "physics_step": 210 + }, + "target_position": 0.25, + "position_unit": "m", + "stiffness": 2000.0, + "damping": 100.0, + "max_effort": 400.0 + }, + { + "joint_id": "joint0", + "trigger": { + "type": "at_step", + "physics_step": 360 + }, + "target_position": 0.0, + "position_unit": "m", + "stiffness": 2000.0, + "damping": 100.0, + "max_effort": 400.0 + } + ] + }, + "asset_role": "cabinet" + } + }, + { + "op": "add", + "id": "box", + "object": { + "kind": "asset", + "dynamic": true, + "position": [ + -1.8, + -0.08, + 0.1594879117077209 + ], + "orientation_wxyz": [ + 0.7071067811865476, + 0.7071067811865476, + 0, + 0 + ], + "asset_role": "box" + } + }, + { + "op": "add", + "id": "book_a", + "object": { + "kind": "asset", + "dynamic": true, + "position": [ + 0.26289903053234287, + 0.3871088653379733, + 0.8755482700515308 + ], + "orientation_wxyz": [ + 0.7071067811865476, + 0.7071067811865476, + 0.0, + 0.0 + ], + "asset_role": "book_a" + } + }, + { + "op": "add", + "id": "book_b", + "object": { + "kind": "asset", + "dynamic": true, + "position": [ + 0.8113178607321683, + -0.37845832407133945, + 0.8755482659645383 + ], + "orientation_wxyz": [ + 0.6532814824381883, + 0.6532814824381883, + 0.2705980500730985, + 0.2705980500730985 + ], + "asset_role": "book_a" + } + }, + { + "op": "add", + "id": "sky", + "object": { + "kind": "light", + "light": { + "type": "dome" + }, + "intensity": 500.0 + } + }, + { + "op": "add", + "id": "key", + "object": { + "kind": "light", + "light": { + "type": "sphere", + "radius_m": 0.4 + }, + "intensity": 2000.0, + "position": [ + 0.0, + -2.5, + 4.5 + ] + } + }, + { + "op": "add", + "id": "drawer_fill", + "object": { + "kind": "light", + "light": { + "type": "sphere", + "radius_m": 0.15 + }, + "position": [ + -1.8, + -0.52, + 0.85 + ], + "intensity": 1600.0 + } + }, + { + "op": "add", + "id": "overview", + "object": { + "kind": "camera", + "position": [ + 1.4, + -4.6, + 2.65 + ], + "record_fps": 30, + "preview_fps": 1, + "camera": { + "resolution": [ + 1920, + 1080 + ], + "focal_length_mm": 45.0, + "horizontal_aperture_mm": 36.0, + "focus_distance_m": 4.8, + "clipping_range_m": [ + 0.01, + 100.0 + ] + }, + "orientation_wxyz": [ + 0.8185196451622787, + 0.5388608160686871, + 0.10949889232068281, + 0.1663267987119022 + ] + } + }, + { + "op": "add", + "id": "leg_lf", + "object": { + "kind": "box", + "size": [ + 0.09, + 0.09, + 0.75 + ], + "position": [ + -1.12, + -0.57, + 0.375 + ], + "color": [ + 0.16, + 0.15, + 0.14 + ] + } + }, + { + "op": "add", + "id": "leg_lb", + "object": { + "kind": "box", + "size": [ + 0.09, + 0.09, + 0.75 + ], + "position": [ + -1.12, + 0.57, + 0.375 + ], + "color": [ + 0.16, + 0.15, + 0.14 + ] + } + }, + { + "op": "add", + "id": "leg_rf", + "object": { + "kind": "box", + "size": [ + 0.09, + 0.09, + 0.75 + ], + "position": [ + 1.12, + -0.57, + 0.375 + ], + "color": [ + 0.16, + 0.15, + 0.14 + ] + } + }, + { + "op": "add", + "id": "leg_rb", + "object": { + "kind": "box", + "size": [ + 0.09, + 0.09, + 0.75 + ], + "position": [ + 1.12, + 0.57, + 0.375 + ], + "color": [ + 0.16, + 0.15, + 0.14 + ] + } + }, + { + "op": "add", + "id": "detail", + "object": { + "kind": "camera", + "position": [ + -1.7, + -0.9, + 1.8 + ], + "orientation_wxyz": [ + 0.9830976922196835, + 0.15659550134871766, + 0.014920563115266527, + 0.09367045054871734 + ], + "record_fps": 30, + "preview_fps": 1, + "camera": { + "resolution": [ + 1920, + 1080 + ], + "focal_length_mm": 35.0, + "horizontal_aperture_mm": 36.0, + "focus_distance_m": 1.8, + "clipping_range_m": [ + 0.01, + 100.0 + ] + } + } + }, + { + "op": "set_presentation", + "presentation": { + "profile": "technical_showcase_1080p", + "capture": { + "resolution": [ + 1920, + 1080 + ], + "fps": 30, + "anti_aliasing": "dlaa", + "renderer": "RealTimePathTracing", + "depth_of_field": false, + "motion_blur": false, + "exposure_mode": "manual", + "exposure_ev": 0 + }, + "budget": { + "max_cameras": 2, + "max_recording_bytes": 4294967296, + "min_free_bytes": 4294967296 + }, + "diagnostics": { + "png_seconds": 0.1, + "keyframe_interval_s": 2 + } + } + }, + { + "op": "set_observation", + "observation": { + "sample_interval_steps": 1, + "strict_start": true, + "record_contact_pairs": true + } + } + ], + "schema": "simscene.scene_recipe.v2" +} diff --git a/plugins/build.py b/plugins/build.py index 10243ca..8f83f91 100644 --- a/plugins/build.py +++ b/plugins/build.py @@ -92,6 +92,7 @@ def verify_source_snapshot(root, snapshot, commit): 'automatic_cabinet_layout':('assets.lock.json','case.json','recipe.json','supplemental-checks.json','check.py'), 'artvip_door':('assets.lock.json','case.json','recipe.json','supplement.json','check.py'), 'usdcraft_two_drawer':('assets.lock.json','case.json','recipe.json','recipe-control.json'), + 'integration_workspace':('README.md','assets.lock.json','case.json','recipe.json','recipe-control.json','check.py'), 'usdcraft_sdk_guide':('assets.lock.json','case.json','recipe-short.json','recipe-long.json','check_pair.py'), } EXAMPLE_HELPERS=('acquire_recipe_assets.py','apply_scene_recipe.py','freeze_recipe_case.py', diff --git a/skills/build-scene/references/integration-workspace.md b/skills/build-scene/references/integration-workspace.md index 9ffa9cb..c21599e 100644 --- a/skills/build-scene/references/integration-workspace.md +++ b/skills/build-scene/references/integration-workspace.md @@ -1,6 +1,6 @@ # Fixed integration examples -Read `simscene://recipes/examples` or `simscene recipe list` to discover four +Read `simscene://recipes/examples` or `simscene recipe list` to discover model-free examples. These are fixed scene inputs, separate from the role recipes accepted by `scene_compile_recipe`. The registry describes earlier evidence for selected configurations; it is not a pass for a new run. @@ -23,6 +23,16 @@ Other examples cover one explicitly repaired `artvip_door`, the scheduled `usdcraft_sdk_guide` two-size comparison. Their locks and case files record the exact assumptions. They do not certify every object in those sources. +`integration_workspace` is an experimental two-drawer and independent GSO +payload pair with ABO props. The control removes all lower-drawer commands; +the upper drive and everything else remain matched. Its case uses native joint +readback, actual rigid-body poses, collision geometry, observed contact callbacks +and a frozen support region. Prepare the three pinned roles, freeze a fresh +case and run each recipe independently before invoking its `check.py`. A +contact callback does not certify the absence of all penetration, and the +scheduled joint drives are not passive triggers. New results require their own +physical and visual review. + The package root is the value in a copied project's `build-scene/.simscene-plugin-root`; otherwise use the root that contains `server/`, `skills/` and `examples/`. Each `examples//` contains the diff --git a/src/simscene/recipes/data/fixed-examples.json b/src/simscene/recipes/data/fixed-examples.json index f2ce0cb..c7e50b9 100644 --- a/src/simscene/recipes/data/fixed-examples.json +++ b/src/simscene/recipes/data/fixed-examples.json @@ -48,6 +48,22 @@ "requires_new_physical_verification": true, "scope": "One three-link/two-slider graph; no payload or passive contact triggering is claimed." }, + { + "id": "integration_workspace", + "description": "Experimental two-drawer workspace with an independent GSO payload, two ABO props and a no-lower-drive control.", + "asset_sources": ["usdcraft", "abo-glb", "gso-glb"], + "profiles": ["articulated_prop_v2", "rigid_prop_v1"], + "asset_lock": "assets.lock.json", + "operations": ["recipe.json", "recipe-control.json"], + "case": "case.json", + "checker": "check.py", + "motion_profile": "usdcraft_two_drawer_v1", + "steps": 600, + "seed": 42, + "runtime_evidence": "exploratory_only", + "requires_new_physical_verification": true, + "scope": "One pinned cabinet and payload; scheduled drives, experimental prop mass and observed contacts are not general source certification." + }, { "id": "usdcraft_sdk_guide", "description": "Two generated guide lengths prepared as static box proxies for a falling-ball comparison.", diff --git a/src/simscene/verification/drawer_payload_pair.py b/src/simscene/verification/drawer_payload_pair.py new file mode 100644 index 0000000..3567dd4 --- /dev/null +++ b/src/simscene/verification/drawer_payload_pair.py @@ -0,0 +1,417 @@ +"""Read-only checks for a frozen two-drawer / independent-payload pair. + +The case describes a specific prepared cabinet, payload, command schedule and +geometry. Neither declared capabilities nor a rendered clip prove the result. +""" +import copy +import hashlib +import json +import math +import os +from pathlib import Path +import re + +from ..worker.mechanism import _mul, _quaternion, _rotate, _vector, measure_joint + + +def _normalize(value, root): + if isinstance(value, dict): + return {key: _normalize(item, root) for key, item in value.items()} + if isinstance(value, list): + return [_normalize(item, root) for item in value] + if isinstance(value, str) and value.startswith(str(root) + os.sep): + return '${RUN}/' + value[len(str(root)) + 1:] + return value + + +def only_lower_drive_removed(positive, control, expected_commands, positive_root, control_root): + """Require the same semantic scene with exactly the lower drives omitted.""" + try: + positive, control = copy.deepcopy(positive), copy.deepcopy(control) + pc = positive['objects']['cabinet']['mechanism']['commands'] + cc = control['objects']['cabinet']['mechanism']['commands'] + if (not isinstance(expected_commands, list) or pc != expected_commands + or not any(c.get('joint_id') == 'joint0' for c in pc) + or not any(c.get('joint_id') == 'joint1' for c in pc) + or cc != [c for c in pc if c.get('joint_id') != 'joint0']): + return False + positive['objects']['cabinet']['mechanism']['commands'] = cc + for obj in (positive, control): + for key in ('scene_id', 'revision', 'requests'): + obj.pop(key, None) + return _normalize(positive, positive_root) == _normalize(control, control_root) + except (AttributeError, KeyError, TypeError): + return False + + +def payload_corners_local(payload_position, payload_quaternion, drawer_position, drawer_quaternion, bounds): + """Transform the conservative prepared collider box into drawer coordinates.""" + pp = _vector(payload_position, 3, 'payload position') + dp = _vector(drawer_position, 3, 'drawer position') + pq, dq = _quaternion(payload_quaternion), _quaternion(drawer_quaternion) + lo, hi = _vector(bounds['min'], 3, 'collider minimum'), _vector(bounds['max'], 3, 'collider maximum') + if any(lo[i] >= hi[i] for i in range(3)): + raise ValueError('collider bounds must have positive extent') + inverse = [dq[0], -dq[1], -dq[2], -dq[3]] + points = [] + for x in (lo[0], hi[0]): + for y in (lo[1], hi[1]): + for z in (lo[2], hi[2]): + world = _rotate(pq, [x, y, z]) + points.append(_rotate(inverse, [world[i] + pp[i] - dp[i] for i in range(3)])) + return points + + +def corners_within(corners, bounds): + lo, hi = _vector(bounds['min'], 3, 'support minimum'), _vector(bounds['max'], 3, 'support maximum') + if any(lo[i] >= hi[i] for i in range(3)) or len(corners) != 8: + raise ValueError('invalid support or payload corners') + return all(all(lo[i] <= _vector(point, 3, 'collider corner')[i] <= hi[i] for i in range(3)) for point in corners) + + +def moving_contact_steps(frames, payload_body, drawer_body, joint_path, window): + """Return observed contacts only while the native drawer coordinate changes.""" + _window(frames,window,'lower motion') + found=[] + for step in range(max(1,window[0]),window[1]+1): + current=frames[step]['native_joint_positions'][joint_path] + previous=frames[step-1]['native_joint_positions'][joint_path] + if abs(current-previous)<1e-5: + continue + if any(set(pair.get('actor_paths',[]))=={payload_body,drawer_body} and pair.get('count',0)>0 + for pair in frames[step].get('contact_pairs',[])): + found.append(step) + return found + + +def _read(root, name): + path = root / name + if path.is_symlink() or not path.is_file(): + raise ValueError('required ordinary run file is missing: ' + name) + value = json.loads(path.read_text(encoding='utf8')) + if not isinstance(value, dict): + raise ValueError('run document must be an object: ' + name) + return value + + +def _sha(path): + digest = hashlib.sha256() + with Path(path).open('rb') as stream: + for block in iter(lambda: stream.read(1024 * 1024), b''): + digest.update(block) + return digest.hexdigest() + + +def _distance(a, b): + return math.sqrt(sum((x-y)**2 for x, y in zip(a, b))) + + +def _window(frames, value, name): + if (not isinstance(value, list) or len(value) != 2 + or any(type(i) is not int for i in value) or not 0 <= value[0] <= value[1] < len(frames)): + raise ValueError('invalid frozen ' + name + ' window') + return frames[value[0]:value[1]+1] + + +def _validate_case(case): + if (not isinstance(case, dict) or case.get('schema') != 'simscene.drawer_payload_pair.v1' + or case.get('steps') != 600 or case.get('seed') != 42 + or case.get('physics_device') != 'cpu' or case.get('physics_dt_s') != 1/60): + raise ValueError('unsupported fixed drawer payload case') + windows = case.get('windows') + if not isinstance(windows, dict) or set(windows) != {'reference_step', 'upper_hold', 'lower_hold', 'lower_motion', 'final'}: + raise ValueError('case requires all frozen measurement windows') + if type(windows['reference_step']) is not int or not 0 < windows['reference_step'] < 600: + raise ValueError('invalid payload reference step') + for name in ('upper_hold', 'lower_hold', 'lower_motion', 'final'): + _window([None]*601, windows[name], name) + if windows['final'][1]-windows['final'][0]+1 < 60: + raise ValueError('final observation requires at least 60 physical steps') + thresholds = case.get('thresholds') + limits = {'target_error_m': .01, 'control_displacement_m': .005, 'relative_drift_m': .02, + 'final_joint_error_m': .01, 'table_drift_m': .002, 'tilt_deg': 10., + 'joint_reconstruction_error_m': .001} + if not isinstance(thresholds, dict) or set(thresholds) != set(limits) | {'min_drawer_travel_m', 'min_payload_fraction'}: + raise ValueError('case requires the fixed payload acceptance thresholds') + for key, maximum in limits.items(): + value = thresholds[key] + if type(value) not in (int,float) or not math.isfinite(value) or not 0 < value <= maximum: + raise ValueError('threshold too loose or invalid: ' + key) + for key, minimum in [('min_drawer_travel_m', .2), ('min_payload_fraction', .8)]: + value = thresholds[key] + if type(value) not in (int,float) or not math.isfinite(value) or value < minimum: + raise ValueError('threshold too loose or invalid: ' + key) + for key in ('payload_collider_bounds_local', 'support_bounds_local'): + bounds = case.get(key) + if not isinstance(bounds, dict) or set(bounds) != {'min', 'max'}: + raise ValueError('missing frozen geometry bounds: ' + key) + lo, hi = _vector(bounds['min'],3,key), _vector(bounds['max'],3,key) + if any(lo[i] >= hi[i] for i in range(3)):raise ValueError('invalid geometry bounds: ' + key) + height = _vector(case.get('allowed_bottom_z_local'),2,'allowed payload bottom interval') + if height[0] >= height[1] or height[1]-height[0] > .02: + raise ValueError('invalid payload bottom height interval') + if (not isinstance(case.get('positive_commands'),list) or not case['positive_commands'] + or not isinstance(case.get('bindings'),dict) + or set(case['bindings']) != {'cabinet','box','book_a','book_b'}): + raise ValueError('missing fixed commands or prepared asset identities') + for binding in case['bindings'].values(): + if (not isinstance(binding,dict) or not re.fullmatch('[0-9a-f]{64}',str(binding.get('manifest_sha256',''))) + or not isinstance(binding.get('source_ref'),dict)): + raise ValueError('each prepared asset requires its source and manifest pin') + commands=case['positive_commands'];by_joint={'joint0':[],'joint1':[]};prior=-1 + for command in commands: + if not isinstance(command,dict) or command.get('joint_id') not in by_joint: + raise ValueError('unsupported drawer command') + trigger=command.get('trigger') + if (not isinstance(trigger,dict) or set(trigger)!={'type','physics_step'} or trigger.get('type')!='at_step' + or type(trigger.get('physics_step')) is not int or not 0<=trigger['physics_step']<=600 + or trigger['physics_step']=close_lower + or windows['lower_motion'][1]1e-6 for i in range(3)): + raise ValueError('payload collider geometry differs from frozen case') + lower_path=result['body_bindings']['cabinet']['bodies']['link1']['motion_body'] + lower=stage.GetPrimAtPath(lower_path) + named={} + for name in ('box_bottom','box_left','box_right','box_back','inner_front_rail'): + prim=stage.GetPrimAtPath(lower_path+'/Collisions/'+name+'/Geom') + api=UsdPhysics.CollisionAPI(prim) + if not prim or prim.GetTypeName()!='Cube' or not api or api.GetCollisionEnabledAttr().Get() is False: + raise ValueError('required separate lower drawer collider is missing: '+name) + bound=cache.ComputeRelativeBound(prim,lower).ComputeAlignedRange() + if bound.IsEmpty():raise ValueError('drawer collider has no measured bounds: '+name) + named[name]={'min':list(bound.GetMin()),'max':list(bound.GetMax())} + usable={'min':[named['box_left']['max'][0], named['inner_front_rail']['max'][1]], + 'max':[named['box_right']['min'][0], named['box_back']['min'][1]]} + declared=case['support_bounds_local'] + if any(declared['min'][i]usable['max'][i]+1e-6 for i in range(2)): + raise ValueError('frozen support extends outside actual drawer walls') + floor=named['box_bottom']['max'][2] + bottom=case['allowed_bottom_z_local'] + if not bottom[0] <= floor <= bottom[1] or floor-bottom[0]>.01 or bottom[1]-floor>.01: + raise ValueError('frozen payload height interval is inconsistent with actual floor') + return actual + + +def _metrics(result, case, positive): + frames=[result.get('initial_observation'),*result.get('samples',[])] + zero=result.get('run_zero_absolute_physics_step');absolute=result.get('run_zero_absolute_simulation_time_s') + if (result.get('actual_physics_steps') != case['steps'] or result.get('requested_physics_steps') != case['steps'] + or result.get('partial') is not False or result.get('samples_truncated') is not False + or result.get('seed') != case['seed'] + or result.get('observation_interval_steps') != 1 or len(frames) != case['steps']+1 + or type(zero) is not int or type(absolute) not in (int,float) or not math.isfinite(absolute)): + raise ValueError('run lacks a complete per-step physical timeline') + for index, frame in enumerate(frames): + if (not isinstance(frame,dict) or frame.get('physics_steps') != index + or frame.get('absolute_physics_step') != zero+index + or type(frame.get('simulation_time_s')) not in (int,float) or not math.isfinite(frame['simulation_time_s']) + or abs(frame['simulation_time_s']-index/60)>1e-6 + or type(frame.get('absolute_simulation_time_s')) not in (int,float) or not math.isfinite(frame['absolute_simulation_time_s']) + or abs(frame['absolute_simulation_time_s']-absolute-index/60)>1e-5): + raise ValueError('run contains a missing or inconsistent physical sample') + if result.get('followers') != {} or result.get('task_status') not in ('unverified','completed'): + raise ValueError('unexpected follower or failed task in physical run') + for phase in ('before_warmup','after_run'): + settings=result['physics_settings'][phase] + if (settings.get('requested_device')!='cpu' or settings.get('enable_gpu_dynamics') is not False + or settings.get('request_matches_observation') is not True + or abs(settings.get('authored_time_steps_per_second',0)-60)>1e-5 + or settings.get('gravity_magnitude_m_s2',0)<=0): + raise ValueError('actual physics settings differ from frozen case') + cb=result['body_bindings']['cabinet'];pb=result['body_bindings']['box'] + if cb.get('profile_id')!='articulated_prop_v2' or set(cb.get('joints',{}))!={'joint0','joint1'}: + raise ValueError('run is not the pinned two-joint articulation') + lower,upper=cb['joints']['joint0'],cb['joints']['joint1'] + body=pb['motion_body'];drawer=lower['child_body'];parent=lower['parent_body'] + if (lower['type']!='prismatic' or upper['type']!='prismatic' + or lower['joint_path']==upper['joint_path'] or lower['child_body']==upper['child_body']): + raise ValueError('drawer joint bindings are not two independent prismatic coordinates') + if body in cb.get('motion_bodies',[]) or pb.get('profile_id')!='rigid_prop_v1': + raise ValueError('payload is not an independent rigid body') + previous={};max_q_error=0. + for frame in frames: + if frame.get('native_joint_measurement_source')!='PhysX_articulation_tensor_DOF_readback_SI': + raise ValueError('native joint tensor source is missing') + for key,joint in cb['joints'].items(): + measured=measure_joint(joint,frame,previous.get(key),physics_step=frame['physics_steps'], + physics_dt_s=case['physics_dt_s'],require_unique_initial=True) + native=frame['native_joint_positions'][joint['joint_path']] + if type(native) not in (int,float) or not math.isfinite(native):raise ValueError('invalid native joint position') + max_q_error=max(max_q_error,abs(native-measured['position'])) + if not joint['limits'][0]-.001 <= native <= joint['limits'][1]+.001: + raise ValueError('actual joint exceeded native limits') + previous[key]=measured + if max_q_error>case['thresholds']['joint_reconstruction_error_m']: + raise ValueError('native joint positions disagree with same-step rigid body poses') + commands=case['positive_commands'] if positive else [c for c in case['positive_commands'] if c['joint_id']!='joint0'] + events=frames[-1]['mechanisms']['cabinet']['command_events'] + if len(events)!=len(commands):raise ValueError('actual command event count differs from the frozen schedule') + for index,(event,command) in enumerate(zip(events,commands)): + drive=event.get('drive_readback',{}) + if (event.get('command_index')!=index or event.get('joint_id')!=command['joint_id'] + or event.get('physics_step')!=command['trigger']['physics_step'] + or event.get('trigger')!=command['trigger'] or event.get('cause')!='declared_at_step_schedule' + or event.get('target_position')!=command['target_position'] + or any(abs(drive.get(field,float('inf'))-command[key])>1e-4 for field,key in + [('target_position','target_position'),('stiffness','stiffness'),('damping','damping'),('max_force','max_effort')])): + raise ValueError('actual drive event differs from the frozen schedule') + windows=case['windows'];reference=frames[windows['reference_step']] + pq=_quaternion(reference['orientations_wxyz'][parent]) + frame_rot=_mul(pq,lower['local_rot0_wxyz']) + local_axis=[0.,0.,0.];local_axis[('X','Y','Z').index(lower['axis'])]=1. + axis=_rotate(frame_rot,local_axis) + base=_vector(reference['positions'][body],3,'reference payload position') + def coordinate(frame):return frame['native_joint_positions'][lower['joint_path']] + def payload_travel(frame): + position=_vector(frame['positions'][body],3,'payload position') + return sum((position[i]-base[i])*axis[i] for i in range(3)) + def relative(frame): + pos=_vector(frame['positions'][body],3,'payload position');dp=_vector(frame['positions'][drawer],3,'drawer position') + dq=_quaternion(frame['orientations_wxyz'][drawer]);inv=[dq[0],-dq[1],-dq[2],-dq[3]] + return _rotate(inv,[pos[i]-dp[i] for i in range(3)]) + lh=_window(frames,windows['lower_hold'],'lower hold');uh=_window(frames,windows['upper_hold'],'upper hold') + final=_window(frames,windows['final'],'final') + lower0=coordinate(frames[0]);upper0=frames[0]['native_joint_positions'][upper['joint_path']] + qref=coordinate(reference);base_rel=relative(reference) + lower_hold=[coordinate(f) for f in lh];upper_hold=[f['native_joint_positions'][upper['joint_path']] for f in uh] + payload_hold=[payload_travel(f) for f in lh] + points=[payload_corners_local(f['positions'][body],f['orientations_wxyz'][body], + f['positions'][drawer],f['orientations_wxyz'][drawer],case['payload_collider_bounds_local']) for f in lh+final] + supported=all(corners_within(p,case['support_bounds_local']) and + case['allowed_bottom_z_local'][0] <= min(x[2] for x in p) <= case['allowed_bottom_z_local'][1] for p in points) + refq=_quaternion(reference['orientations_wxyz'][body]);tilts=[] + for f in final: + q=_quaternion(f['orientations_wxyz'][body]);dot=abs(sum(a*b for a,b in zip(q,refq))) + tilts.append(math.degrees(2*math.acos(max(-1.,min(1.,dot))))) + drift={} + for name in ('book_a','book_b'): + path=result['body_bindings'][name]['motion_body'];origin=_vector(final[0]['positions'][path],3,'table prop') + drift[name]=max(_distance(_vector(f['positions'][path],3,'table prop'),origin) for f in final) + contacts=moving_contact_steps(frames,body,drawer,lower['joint_path'],windows['lower_motion']) + t=case['thresholds'] + check={'upper_reached':all(abs(q-.35)<=t['target_error_m'] for q in upper_hold), + 'lower_closed':all(abs(coordinate(f)-lower0)<=t['final_joint_error_m'] for f in final), + 'upper_closed':all(abs(f['native_joint_positions'][upper['joint_path']]-upper0)<=t['final_joint_error_m'] for f in final), + 'payload_supported':supported,'payload_tilt':max(tilts)<=t['tilt_deg'], + 'table_props_stable':all(v<=t['table_drift_m'] for v in drift.values())} + if positive: + check.update(lower_reached=all(abs(q-.25)<=t['target_error_m'] for q in lower_hold), + payload_followed=all(q-qref>=t['min_drawer_travel_m'] and p>=t['min_payload_fraction']*(q-qref) + for q,p in zip(lower_hold,payload_hold)), + payload_relative_drift=max(_distance(relative(f),base_rel) for f in lh)<=t['relative_drift_m'], + actual_payload_drawer_contact=bool(contacts)) + else: + check.update(lower_undriven_stationary=max(abs(coordinate(f)-qref) for f in frames[windows['reference_step']:])<=t['control_displacement_m'], + payload_undriven_stationary=max(abs(payload_travel(f)) for f in frames[windows['reference_step']:])<=t['control_displacement_m']) + return {'checks':check,'lower_hold_minmax_m':[min(lower_hold),max(lower_hold)], + 'upper_hold_minmax_m':[min(upper_hold),max(upper_hold)], + 'payload_hold_displacement_minmax_m':[min(payload_hold),max(payload_hold)], + 'payload_relative_hold_drift_m':max(_distance(relative(f),base_rel) for f in lh), + 'final_table_drift_m':drift,'final_payload_tilt_deg':max(tilts), + 'native_pose_max_error_m':max_q_error,'actual_contact_samples':len(contacts), + 'contact_geometry_incomplete':result.get('contact_geometry_incomplete')} + + +def verify_pair(positive_directory, control_directory, case_path=None): + """Verify two same-case, same-runtime runs and one causal intervention.""" + report = {'schema': 'simscene.drawer_payload_pair_report.v1', 'passed': False, + 'checks': {}, 'errors': [], 'metrics': {}, + 'scope': 'Specific frozen pair; actual contact callbacks do not certify absence of all penetration.'} + try: + from ..run_integrity import verify as verify_inputs + from ..evidence_integrity import verify as verify_outputs + p,c=Path(positive_directory).resolve(),Path(control_directory).resolve() + if p==c:raise ValueError('positive and control must be distinct runs') + pl,cl=_read(p,'run-lock.json'),_read(c,'run-lock.json') + pc,cc=_read(p,'acceptance-case.json'),_read(c,'acceptance-case.json') + case=_validate_case(pc) + digest=_sha(p/'acceptance-case.json') + if (pc!=cc or _sha(c/'acceptance-case.json')!=digest or pl.get('acceptance_case_sha256')!=digest + or cl.get('acceptance_case_sha256')!=digest or case_path is not None and _sha(case_path)!=digest): + raise ValueError('the two runs do not use the same frozen case') + keys=('runtime_version','runtime_python_sha256','queue_launcher_python_sha256','worker_code_sha256', + 'seed','physics_device','physics_dt_s','requested_physics_steps','gpu_selection') + if (pl.get('run_id')==cl.get('run_id') or any(key not in pl or pl.get(key)!=cl.get(key) for key in keys) + or pl['seed']!=case['seed'] or pl['physics_device']!=case['physics_device'] + or pl['physics_dt_s']!=case['physics_dt_s'] or pl['requested_physics_steps']!=case['steps']): + raise ValueError('run identities, worker, runtime, seed, device or steps differ') + pi,ci,pe,ce=verify_inputs(p),verify_inputs(c),verify_outputs(p),verify_outputs(c) + if any(x.get('passed') is not True for x in (pi,ci,pe,ce)) or pe.get('partial') is not False or ce.get('partial') is not False: + raise ValueError('run inputs or evidence did not pass integrity checks') + ps,cs=_read(p,'spec.json'),_read(c,'spec.json') + if not only_lower_drive_removed(ps,cs,case['positive_commands'],p,c): + raise ValueError('control is not exactly the positive scene without lower drive commands') + pr,cr=_read(p,'result.json'),_read(c,'result.json') + if pr.get('body_bindings')!=cr.get('body_bindings'): + raise ValueError('run body or joint mappings differ') + _geometry(p,case,pr);_geometry(c,case,cr) + positive,control=_metrics(pr,case,True),_metrics(cr,case,False) + report['metrics']={'positive':positive,'control':control} + report['checks']={'same_frozen_case':True,'same_runtime_and_seed':True, + 'input_and_output_integrity':True,'only_lower_drive_removed':True, + 'actual_geometry_and_bindings':True, + **{'positive_'+k:v for k,v in positive['checks'].items()}, + **{'control_'+k:v for k,v in control['checks'].items()}} + report['passed']=all(value is True for value in report['checks'].values()) + except Exception as error: + report['errors'].append(type(error).__name__ + ': ' + str(error)) + return report diff --git a/tests/agent/test_package.py b/tests/agent/test_package.py index 150dcf1..7e66779 100644 --- a/tests/agent/test_package.py +++ b/tests/agent/test_package.py @@ -105,6 +105,11 @@ async def check_independent_metadata(root,plugin): 'examples/artvip_door/assets.lock.json', 'examples/artvip_door/check.py', 'examples/usdcraft_two_drawer/case.json', + 'examples/integration_workspace/recipe.json', + 'examples/integration_workspace/README.md', + 'examples/integration_workspace/recipe-control.json', + 'examples/integration_workspace/case.json', + 'examples/integration_workspace/check.py', 'examples/usdcraft_sdk_guide/assets.lock.json', 'examples/usdcraft_sdk_guide/check_pair.py', 'experiments/acquire_recipe_assets.py', diff --git a/tests/test_drawer_payload_pair.py b/tests/test_drawer_payload_pair.py new file mode 100644 index 0000000..99dd158 --- /dev/null +++ b/tests/test_drawer_payload_pair.py @@ -0,0 +1,93 @@ +"""The drawer control must differ only in its lower drive and fail closed.""" +import copy +import json +from pathlib import Path +import pytest + +from simscene.verification import drawer_payload_pair as pair + + +def scene(commands): + return {'scene_id':'positive', 'revision':1, 'world':{'units':'m'}, + 'objects':{'cabinet':{'kind':'asset','mechanism':{'commands':commands}}, + 'box':{'kind':'asset','dynamic':True,'position':[0,0,.2]}}} + + +def test_control_must_remove_all_and_only_lower_drive_commands(): + commands=[{'joint_id':'joint0','target_position':0.}, {'joint_id':'joint1','target_position':0.}, + {'joint_id':'joint1','target_position':.35}, {'joint_id':'joint0','target_position':.25}] + positive=scene(commands) + control=scene([c for c in commands if c['joint_id']!='joint0']) + control['scene_id']='negative' + assert pair.only_lower_drive_removed(positive,control,commands,'/run/a','/run/b') + altered=copy.deepcopy(control);altered['objects']['box']['position'][0]=1 + assert not pair.only_lower_drive_removed(positive,altered,commands,'/run/a','/run/b') + altered=copy.deepcopy(control);altered['objects']['cabinet']['mechanism']['commands'].pop() + assert not pair.only_lower_drive_removed(positive,altered,commands,'/run/a','/run/b') + + +def test_payload_corners_are_checked_in_rotated_drawer_coordinates(): + # A two-metre-wide payload rotated by 90 degrees is two metres long in Y. + half=2**-.5 + corners=pair.payload_corners_local([0,0,0],[half,0,0,half], + [0,0,0],[1,0,0,0],{'min':[-1,-.1,-.1],'max':[1,.1,.1]}) + assert max(abs(point[1]) for point in corners)>0.99 + assert not pair.corners_within(corners,{'min':[-.2,-.5,-.2],'max':[.2,.5,.2]}) + assert pair.corners_within(corners,{'min':[-.2,-1.1,-.2],'max':[.2,1.1,.2]}) + + +def test_missing_runs_never_pass(tmp_path): + result=pair.verify_pair(tmp_path/'positive',tmp_path/'negative') + assert result['passed'] is False + assert result['errors'] + + +def test_public_example_has_only_the_documented_intervention_and_no_local_paths(): + root=Path(__file__).resolve().parents[1]/'examples/integration_workspace' + positive=json.loads((root/'recipe.json').read_text()) + control=json.loads((root/'recipe-control.json').read_text()) + for value in (positive,control,json.loads((root/'assets.lock.json').read_text())): + assert '/data/' not in json.dumps(value) and '/home/' not in json.dumps(value) + def spec(recipe): + return {'objects':{op['id']:op['object'] for op in recipe['operations'] if op['op']=='add'}} + ps,cs=spec(positive),spec(control) + commands=ps['objects']['cabinet']['mechanism']['commands'] + assert pair.only_lower_drive_removed(ps,cs,commands,'/run/positive','/run/control') + + +def test_incomplete_trajectory_cannot_be_accepted(): + case={'steps':600,'seed':42,'physics_device':'cpu','physics_dt_s':1/60} + partial={'actual_physics_steps':600,'requested_physics_steps':600,'partial':False, + 'samples_truncated':False,'observation_interval_steps':1, + 'initial_observation':{},'samples':[]} + with pytest.raises(ValueError,match='complete per-step'): + pair._metrics(partial,case,True) + + +def test_static_contact_cannot_prove_contact_during_drawer_motion(): + frames=[{'native_joint_positions':{'/joint':q},'contact_pairs':[{'actor_paths':['/box','/drawer'],'count':1}]} + for q in (0.,0.,.01)] + assert pair.moving_contact_steps(frames,'/box','/drawer','/joint',[1,1]) == [] + assert pair.moving_contact_steps(frames,'/box','/drawer','/joint',[1,2]) == [2] + + +def test_hold_window_cannot_be_outside_its_driven_phase(): + def command(joint,step,target): + return {'joint_id':joint,'trigger':{'type':'at_step','physics_step':step},'target_position':target, + 'position_unit':'m','stiffness':2000.,'damping':100.,'max_effort':400.} + case={'schema':'simscene.drawer_payload_pair.v1','steps':600,'seed':42,'physics_device':'cpu', + 'physics_dt_s':1/60,'windows':{'reference_step':209,'upper_hold':[130,149], + 'lower_hold':[270,359],'lower_motion':[210,359],'final':[540,600]}, + 'thresholds':{'target_error_m':.01,'control_displacement_m':.005,'relative_drift_m':.02, + 'final_joint_error_m':.01,'table_drift_m':.002,'tilt_deg':10.,'joint_reconstruction_error_m':.001, + 'min_drawer_travel_m':.2,'min_payload_fraction':.8}, + 'payload_collider_bounds_local':{'min':[-.1,-.1,0.],'max':[.1,.1,.1]}, + 'support_bounds_local':{'min':[-.4,0.,-.2],'max':[.4,.4,.2]}, + 'allowed_bottom_z_local':[-.155,-.14], + 'positive_commands':[command('joint0',0,0.),command('joint1',0,0.),command('joint1',60,.35), + command('joint1',150,0.),command('joint0',210,.25),command('joint0',360,0.)], + 'bindings':{k:{'manifest_sha256':'a'*64,'source_ref':{'source_id':k}} for k in ('cabinet','box','book_a','book_b')}} + pair._validate_case(case) + case['windows']['upper_hold']=[160,170] + with pytest.raises(ValueError,match='window'): + pair._validate_case(case) diff --git a/tests/test_integration_example_registry.py b/tests/test_integration_example_registry.py index 4f436d7..4c1b83c 100644 --- a/tests/test_integration_example_registry.py +++ b/tests/test_integration_example_registry.py @@ -13,7 +13,7 @@ def test_fixed_examples_are_separate_from_compilable_role_recipes(): assert listing['schema'] == 'simscene.fixed_examples.v1' examples = {entry['id']: entry for entry in listing['examples']} assert set(examples) == {'automatic_cabinet_layout', 'artvip_door', - 'usdcraft_two_drawer', 'usdcraft_sdk_guide'} + 'usdcraft_two_drawer', 'usdcraft_sdk_guide', 'integration_workspace'} assert examples['automatic_cabinet_layout']['asset_sources'] == ['usdcraft', 'abo-glb', 'gso-glb'] assert examples['automatic_cabinet_layout']['runtime_evidence'] == 'prior_example_only' assert examples['automatic_cabinet_layout']['operations'] == ['recipe.json'] From 3a6c7a23e51e15130a5c4eaa164fb45678cdfbc9 Mon Sep 17 00:00:00 2001 From: shaoxiang <519517384@qq.com> Date: Tue, 17 Nov 2026 18:09:30 +0800 Subject: [PATCH 10/20] Harden package preflight and full-run control checks --- plugins/build.py | 2 +- src/simscene/verification/drawer_payload_pair.py | 16 ++++++++++++++-- tests/test_drawer_payload_pair.py | 5 +++++ 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/plugins/build.py b/plugins/build.py index 8f83f91..3851b83 100644 --- a/plugins/build.py +++ b/plugins/build.py @@ -169,11 +169,11 @@ def validate_vendor(vendor, python=sys.executable): def build(destination, use_installed_deps=False): - build_source=source_identity() requested=Path(destination).expanduser() if requested.is_symlink():raise FileExistsError(f'destination is a symlink: {requested}') destination=requested.resolve() if destination.exists():raise FileExistsError(f'destination already exists: {destination}') + build_source=source_identity() portable=destination/'portable'/'simscene';claude=destination/'claude'/'simscene';deepseek=destination/'deepseek'/'simscene' portable.mkdir(parents=True) try: diff --git a/src/simscene/verification/drawer_payload_pair.py b/src/simscene/verification/drawer_payload_pair.py index 3567dd4..7ea54aa 100644 --- a/src/simscene/verification/drawer_payload_pair.py +++ b/src/simscene/verification/drawer_payload_pair.py @@ -84,6 +84,16 @@ def moving_contact_steps(frames, payload_body, drawer_body, joint_path, window): return found +def max_axis_displacement(frames, body, axis): + """Measure maximum absolute displacement from the first observed frame.""" + if not isinstance(frames,list) or not frames: + raise ValueError('a complete observed trajectory is required') + axis=_vector(axis,3,'world joint axis') + origin=_vector(frames[0]['positions'][body],3,'initial body position') + return max(abs(sum((x-y)*direction for x,y,direction in + zip(_vector(frame['positions'][body],3,'body position'),origin,axis))) for frame in frames) + + def _read(root, name): path = root / name if path.is_symlink() or not path.is_file(): @@ -360,13 +370,15 @@ def relative(frame): payload_relative_drift=max(_distance(relative(f),base_rel) for f in lh)<=t['relative_drift_m'], actual_payload_drawer_contact=bool(contacts)) else: - check.update(lower_undriven_stationary=max(abs(coordinate(f)-qref) for f in frames[windows['reference_step']:])<=t['control_displacement_m'], - payload_undriven_stationary=max(abs(payload_travel(f)) for f in frames[windows['reference_step']:])<=t['control_displacement_m']) + check.update(lower_undriven_stationary=max(abs(coordinate(f)-lower0) for f in frames)<=t['control_displacement_m'], + payload_undriven_stationary=max_axis_displacement(frames,body,axis)<=t['control_displacement_m']) return {'checks':check,'lower_hold_minmax_m':[min(lower_hold),max(lower_hold)], 'upper_hold_minmax_m':[min(upper_hold),max(upper_hold)], 'payload_hold_displacement_minmax_m':[min(payload_hold),max(payload_hold)], 'payload_relative_hold_drift_m':max(_distance(relative(f),base_rel) for f in lh), 'final_table_drift_m':drift,'final_payload_tilt_deg':max(tilts), + 'full_run_drawer_displacement_max_m':max(abs(coordinate(f)-lower0) for f in frames), + 'full_run_payload_displacement_max_m':max_axis_displacement(frames,body,axis), 'native_pose_max_error_m':max_q_error,'actual_contact_samples':len(contacts), 'contact_geometry_incomplete':result.get('contact_geometry_incomplete')} diff --git a/tests/test_drawer_payload_pair.py b/tests/test_drawer_payload_pair.py index 99dd158..49a8f1a 100644 --- a/tests/test_drawer_payload_pair.py +++ b/tests/test_drawer_payload_pair.py @@ -71,6 +71,11 @@ def test_static_contact_cannot_prove_contact_during_drawer_motion(): assert pair.moving_contact_steps(frames,'/box','/drawer','/joint',[1,2]) == [2] +def test_control_displacement_includes_early_motion_that_later_returns(): + frames=[{'positions':{'/box':[0,y,0]}} for y in (0.,-.02,0.,0.)] + assert pair.max_axis_displacement(frames,'/box',[0.,-1.,0.]) == pytest.approx(.02) + + def test_hold_window_cannot_be_outside_its_driven_phase(): def command(joint,step,target): return {'joint_id':joint,'trigger':{'type':'at_step','physics_step':step},'target_position':target, From 86d8023ea4952a55e7ed8b51bd0b448e8dee1dae Mon Sep 17 00:00:00 2001 From: shaoxiang <519517384@qq.com> Date: Tue, 17 Nov 2026 18:25:29 +0800 Subject: [PATCH 11/20] Bind packaged resources and action review to frozen evidence --- plugins/build.py | 52 ++++++++------ src/simscene/recipes/integration_delivery.py | 71 +++++++++++++++++++- tests/test_build_identity.py | 36 ++++++++++ tests/test_integration_delivery.py | 29 ++++++-- 4 files changed, 160 insertions(+), 28 deletions(-) diff --git a/plugins/build.py b/plugins/build.py index 3851b83..d82d854 100644 --- a/plugins/build.py +++ b/plugins/build.py @@ -7,6 +7,7 @@ import re import hashlib import tempfile +import importlib.util from pathlib import Path from importlib import metadata @@ -38,10 +39,10 @@ def source_identity(root=ROOT): return {'source_commit':None,'source_clean':None} -def verify_source_snapshot(root, snapshot, commit): - """Reject ignored or changed files in a supposedly clean wheel snapshot.""" +def verify_source_snapshot(root, snapshot, commit, paths=None): + """Reject ignored or changed files in a supposedly clean build snapshot.""" root, snapshot = Path(root), Path(snapshot) - paths = ('src', 'pyproject.toml', 'README.md', 'LICENSE') + paths = paths or ('src', 'pyproject.toml', 'README.md', 'LICENSE') try: result = subprocess.check_output( ['git', 'ls-tree', '-r', '-z', '--full-tree', commit, '--', *paths], cwd=root) @@ -173,7 +174,7 @@ def build(destination, use_installed_deps=False): if requested.is_symlink():raise FileExistsError(f'destination is a symlink: {requested}') destination=requested.resolve() if destination.exists():raise FileExistsError(f'destination already exists: {destination}') - build_source=source_identity() + build_source=source_identity(ROOT) portable=destination/'portable'/'simscene';claude=destination/'claude'/'simscene';deepseek=destination/'deepseek'/'simscene' portable.mkdir(parents=True) try: @@ -182,12 +183,20 @@ def build(destination, use_installed_deps=False): # setuptools resource contract instead of bypassing it with copytree. with tempfile.TemporaryDirectory(prefix='simscene-wheel-') as temporary: snapshot=Path(temporary)/'project';snapshot.mkdir() - for filename in ('pyproject.toml','README.md','LICENSE'): + for filename in ('pyproject.toml','README.md','LICENSE','NOTICE','OPEN_SOURCE_NOTICES.md'): shutil.copyfile(ROOT/filename,snapshot/filename) shutil.copytree(ROOT/'src',snapshot/'src',ignore=shutil.ignore_patterns('__pycache__','*.pyc','*.egg-info')) + shutil.copytree(ROOT/'skills',snapshot/'skills',ignore=shutil.ignore_patterns('__pycache__','*.pyc','.simscene-plugin-root')) + extra_paths = ['plugins/install.py', 'plugins/deepseek_patch.py'] + extra_paths += [f'examples/{example}/{name}' for example,names in EXAMPLE_DATA.items() for name in names] + extra_paths += [f'experiments/{name}' for name in EXAMPLE_HELPERS] + for name in extra_paths: + target=snapshot/name;target.parent.mkdir(parents=True,exist_ok=True) + shutil.copyfile(ROOT/name,target) + snapshot_paths = ('src','skills','pyproject.toml','README.md','LICENSE','NOTICE','OPEN_SOURCE_NOTICES.md',*extra_paths) if build_source['source_clean'] is True: - verify_source_snapshot(ROOT,snapshot,build_source['source_commit']) - if source_identity()!=build_source: + verify_source_snapshot(ROOT,snapshot,build_source['source_commit'],snapshot_paths) + if source_identity(ROOT)!=build_source: raise RuntimeError('source revision or clean state changed while creating the build snapshot') wheels=Path(temporary)/'wheels';wheels.mkdir() subprocess.run([sys.executable,'-m','pip','wheel','--disable-pip-version-check', @@ -202,6 +211,19 @@ def build(destination, use_installed_deps=False): subprocess.run(command+[str(wheel)],check=True) destination.joinpath('wheels').mkdir() shutil.copyfile(wheel,destination/'wheels'/wheel.name) + # All shipped resources come from the same frozen snapshot as the + # wheel, even if the live checkout changes during dependency setup. + for notice in ('LICENSE','NOTICE','OPEN_SOURCE_NOTICES.md'): + shutil.copyfile(snapshot/notice,portable/notice) + shutil.copyfile(snapshot/'plugins'/'install.py',portable/'install.py') + shutil.copytree(snapshot/'skills',portable/'skills') + for example,names in EXAMPLE_DATA.items(): + target=portable/'examples'/example;target.mkdir(parents=True) + for name in names:shutil.copyfile(snapshot/'examples'/example/name,target/name) + helper_root=portable/'experiments';helper_root.mkdir() + for name in EXAMPLE_HELPERS:shutil.copyfile(snapshot/'experiments'/name,helper_root/name) + patch_spec=importlib.util.spec_from_file_location('simscene_snapshot_deepseek_patch',snapshot/'plugins'/'deepseek_patch.py') + patch_module=importlib.util.module_from_spec(patch_spec);patch_spec.loader.exec_module(patch_module) versions_lock={item.metadata['Name']:item.version for item in metadata.distributions(path=[str(vendor)])} write(portable/'server'/'dependency-lock.json',versions_lock) write(portable/'server'/'build-info.json',{'python_version':PYTHON_VERSION,'plugin_version':PACKAGE_VERSION, @@ -212,18 +234,6 @@ def build(destination, use_installed_deps=False): validate_vendor(vendor) (portable/'server'/'launch.py').write_text(LAUNCHER) (portable/'README.md').write_text(PACKAGE_README) - for notice in ('LICENSE','NOTICE','OPEN_SOURCE_NOTICES.md'): - shutil.copyfile(ROOT/notice,portable/notice) - shutil.copyfile(ROOT/'plugins'/'install.py',portable/'install.py') - shutil.copytree(ROOT/'skills',portable/'skills',ignore=shutil.ignore_patterns('__pycache__','*.pyc','.simscene-plugin-root')) - # Small, model-free reference recipes are read on demand by the skills. - # Copy only explicitly enumerated reference data and checker; never - # bundle source assets. - for example,names in EXAMPLE_DATA.items(): - target=portable/'examples'/example;target.mkdir(parents=True) - for name in names:shutil.copyfile(ROOT/'examples'/example/name,target/name) - helper_root=portable/'experiments';helper_root.mkdir() - for name in EXAMPLE_HELPERS:shutil.copyfile(ROOT/'experiments'/name,helper_root/name) write(portable/'plugin.json',{'$schema':'https://agent-plugins.org/schemas/1.0.0/plugin.schema.json','name':'simscene','version':PACKAGE_VERSION,'description':'Discover assets, compose and run experimental simulation scenes.'}) write(portable/'mcp.json',{'$schema':'https://agent-plugins.org/schemas/1.0.0/mcp.schema.json','mcpServers':{'simscene':{'type':'stdio','command':'python3','args':['${PLUGIN_ROOT}/server/launch.py'],'cwd':'${PLUGIN_ROOT}'}}}) claude.mkdir(parents=True) @@ -244,9 +254,7 @@ def build(destination, use_installed_deps=False): shutil.copyfile(portable/'README.md',deepseek/'README.md') for notice in ('LICENSE','NOTICE','OPEN_SOURCE_NOTICES.md'): shutil.copyfile(portable/notice,deepseek/notice) - try:from .deepseek_patch import write_patch - except ImportError:from deepseek_patch import write_patch - write_patch(deepseek,deepseek/'cordis.patch.yml',sys.executable) + patch_module.write_patch(deepseek,deepseek/'cordis.patch.yml',sys.executable) return {'portable':str(portable),'claude':str(claude),'deepseek':str(deepseek),'python':sys.version.split()[0], 'python_version':PYTHON_VERSION,'plugin_version':PACKAGE_VERSION,'wheel_sha256':wheel_sha256, 'status':'packages_built_not_registered_or_installed', diff --git a/src/simscene/recipes/integration_delivery.py b/src/simscene/recipes/integration_delivery.py index 66b2421..154d4ac 100644 --- a/src/simscene/recipes/integration_delivery.py +++ b/src/simscene/recipes/integration_delivery.py @@ -36,6 +36,11 @@ def check_edit_binding(edit, video, run): segments = edit.get('segments') if isinstance(edit, dict) else None if not isinstance(segments, list) or not segments: return errors + ['edited video has no source segments'] + if lock.get('requested_physics_steps') != 600 or not math.isclose(lock.get('physics_dt_s', 0), 1 / 60, abs_tol=1e-9): + errors.append('fixed example requires 600 physics steps at 60 Hz') + next_frame = 0 + next_output = 0.0 + frame_tables = {} for index, segment in enumerate(segments): if not isinstance(segment, dict): errors.append(f'segment {index} is invalid'); continue @@ -49,12 +54,48 @@ def check_edit_binding(edit, video, run): and segment.get('evidence_lock_sha256') == _sha(run / 'evidence-lock.json')) if not valid: errors.append(f'segment {index} does not match the run, camera or frame table') + continue + if segment['camera'] not in frame_tables: + if record.get('fps') != 30 or record.get('frames') != 300: + errors.append(f'segment {index} does not use the native 30 fps recording') + continue + frame_file = Path(record['frame_manifest']) + if frame_file.stat().st_size > 5_000_000: + errors.append(f'segment {index} frame table is too large') + continue + frames = [json.loads(line) for line in frame_file.read_text().splitlines()] + if (len(frames) != 300 or any( + row.get('frame_id') != i or row.get('physics_step') != 2 + 2 * i + or not math.isclose(row.get('sim_time_s', -1), (2 + 2 * i) / 60, abs_tol=1e-8) + for i, row in enumerate(frames))): + errors.append(f'segment {index} frame table does not cover the fixed run') + continue + frame_tables[segment['camera']] = frames + start, end = segment.get('source_start_frame'), segment.get('source_end_frame_exclusive') + if (type(start) is not int or type(end) is not int or not 0 <= start < end <= 300 + or start != next_frame or segment.get('source_fps') != 30 + or segment.get('speed') != 1 or segment.get('output_frames') != end - start): + errors.append(f'segment {index} skips frames or changes their playback speed') + continue + expected = {'source_sim_start_s': (2 + 2 * start) / 60, + 'source_sim_end_s': (2 + 2 * end) / 60, + 'output_start_s': next_output, + 'output_end_s': next_output + (end - start) / 30} + if any(type(segment.get(key)) not in (int, float) + or not math.isclose(segment[key], value, abs_tol=1e-6) + for key, value in expected.items()): + errors.append(f'segment {index} has inconsistent source or output timing') + continue + next_frame = end + next_output = expected['output_end_s'] + if next_frame != 300 or not math.isclose(next_output, 10., abs_tol=1e-6): + errors.append('technical video must cover the complete 10-second run in order') except (OSError, ValueError, TypeError, KeyError, AttributeError) as error: errors.append('cannot verify edited source binding: ' + str(error)) return errors -def check_visual_review(review, video, duration_s): +def check_visual_review(review, video, duration_s, required_windows=None): """Validate an attributed review record; its content remains a declaration.""" errors = [] try: @@ -68,6 +109,7 @@ def check_visual_review(review, video, duration_s): if (not isinstance(windows, list) or not windows or type(duration_s) not in (int, float) or not math.isfinite(duration_s) or duration_s <= 0): return errors + ['reviewed action windows and finite video duration are required'] + observed = [] for window in windows: if not isinstance(window, dict): errors.append('visual window is invalid'); continue @@ -77,6 +119,15 @@ def check_visual_review(review, video, duration_s): or not 0 <= start < end <= duration_s + 1e-6 or not isinstance(window.get('observation'), str) or not window['observation'].strip()): errors.append('visual window is outside the video or lacks an observation') + else: + observed.append((start, end)) + for required in required_windows or (): + cursor = required['start_s'] + for start, end in sorted(observed): + if start <= cursor + 1e-6: + cursor = max(cursor, end) + if cursor < required['end_s'] - 1e-6: + errors.append('visual review does not cover a required action or final-result window') except (OSError, ValueError, TypeError) as error: errors.append('cannot read visual-review evidence: ' + str(error)) return errors @@ -205,6 +256,14 @@ def collect_delivery(paths): inspected = inspect(video, representative_count=1) if not (inspected.get('simulation_timeline') or {}).get('passed'): media_errors.append('edited video provenance or timeline did not pass') + metadata = inspected.get('metadata') or {} + streams = metadata.get('streams') or [] + stream = streams[0] if streams else {} + if (inspected.get('decoded_frame_count') != 300 + or not math.isclose(inspected.get('duration_s', 0), 10., abs_tol=.02) + or stream.get('width') != 1920 or stream.get('height') != 1080 + or stream.get('avg_frame_rate') not in ('30/1', '30')): + media_errors.append('technical video must decode as 10 seconds of native 1080p30') report['media_status'] = 'failed' if media_errors else 'passed' report['errors'].extend(media_errors) except Exception as error: @@ -213,7 +272,15 @@ def collect_delivery(paths): if inspected and present('review', 'video'): try: review = json.loads(Path(paths['review']).read_text()) - report['errors'].extend(check_visual_review(review, paths['video'], inspected.get('duration_s'))) + # Frame zero corresponds to physics step two; the one-run edit has + # already been checked for contiguous original-speed coverage. + required_windows = [ + {'start_s': 0., 'end_s': 1. - 2 / 60}, + {'start_s': 4. - 2 / 60, 'end_s': 5. - 2 / 60}, + {'start_s': 9. - 2 / 60, 'end_s': 10.}, + ] + report['errors'].extend(check_visual_review( + review, paths['video'], inspected.get('duration_s'), required_windows)) report['visual_review'] = review.get('decision', 'not_checked') if isinstance(review, dict) else 'not_checked' if report['visual_review'] != 'accept':report['errors'].append('visual review is not accepted') except (OSError, ValueError, TypeError) as error: diff --git a/tests/test_build_identity.py b/tests/test_build_identity.py index 34966f3..35accf2 100644 --- a/tests/test_build_identity.py +++ b/tests/test_build_identity.py @@ -1,6 +1,7 @@ """Package version must not substitute for its source revision and dirty state.""" import subprocess import shutil +from pathlib import Path import pytest @@ -46,3 +47,38 @@ def test_clean_build_snapshot_must_equal_the_committed_source_tree(tmp_path): (snapshot / 'src/simscene/ignored.py').write_text('extra\n') with pytest.raises(RuntimeError, match='snapshot'): build.verify_source_snapshot(repo, snapshot, commit) + + +def test_packaged_resources_are_from_the_frozen_commit_even_if_checkout_changes(tmp_path, monkeypatch): + original = build.ROOT + repo = tmp_path / 'repo'; repo.mkdir() + for name in ('pyproject.toml', 'README.md', 'LICENSE', 'NOTICE', 'OPEN_SOURCE_NOTICES.md'): + shutil.copyfile(original / name, repo / name) + for directory in ('src', 'skills'): + shutil.copytree(original / directory, repo / directory, + ignore=shutil.ignore_patterns('__pycache__', '*.pyc', '*.egg-info', '.simscene-plugin-root')) + for name in ('plugins/install.py', 'plugins/deepseek_patch.py', + *(f'examples/{example}/{name}' for example, names in build.EXAMPLE_DATA.items() for name in names), + *(f'experiments/{name}' for name in build.EXAMPLE_HELPERS)): + target = repo / name; target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(original / name, target) + subprocess.run(['git', 'init', '-q', str(repo)], check=True) + subprocess.run(['git', '-C', str(repo), 'add', '.'], check=True) + subprocess.run(['git', '-C', str(repo), '-c', 'user.name=Test', '-c', + 'user.email=test@example.invalid', 'commit', '-qm', 'baseline'], check=True) + changed = ('skills/build-scene/SKILL.md', 'examples/integration_workspace/recipe.json', + 'experiments/assemble_integration_receipt.py', 'plugins/install.py', 'NOTICE') + expected = {name: (repo / name).read_bytes() for name in changed} + run = subprocess.run + def change_during_wheel(command, *args, **kwargs): + if isinstance(command, list) and len(command) > 3 and command[1:4] == ['-m', 'pip', 'wheel']: + for name in changed: + with (repo / name).open('ab') as stream: stream.write(b'\nchanged during wheel build\n') + return run(command, *args, **kwargs) + monkeypatch.setattr(build, 'ROOT', repo) + monkeypatch.setattr(build.subprocess, 'run', change_during_wheel) + result = build.build(tmp_path / 'dist', use_installed_deps=True) + package = Path(result['portable']) + for name, content in expected.items(): + relative = 'install.py' if name == 'plugins/install.py' else name + assert (package / relative).read_bytes() == content, name diff --git a/tests/test_integration_delivery.py b/tests/test_integration_delivery.py index 1157cf8..bf8e70a 100644 --- a/tests/test_integration_delivery.py +++ b/tests/test_integration_delivery.py @@ -25,22 +25,25 @@ def media_fixture(tmp_path): run = tmp_path / 'run-a' run.mkdir() lock = run / 'run-lock.json' - lock.write_text(json.dumps({'run_id': 'run-a'})) + lock.write_text(json.dumps({'run_id': 'run-a', 'requested_physics_steps': 600, 'physics_dt_s': 1/60})) evidence = run / 'evidence-lock.json' evidence.write_text('{}') source = run / 'camera_overview.mp4' source.write_bytes(b'source') frames = run / 'camera_overview.frames.jsonl' - frames.write_text('{}\n') + frames.write_text(''.join(json.dumps({'frame_id': i, 'physics_step': 2+2*i, 'sim_time_s': (2+2*i)/60})+'\n' for i in range(300))) (run / 'result.json').write_text(json.dumps({'videos': {'overview': { - 'path': str(source), 'frame_manifest': str(frames)}}})) + 'path': str(source), 'frame_manifest': str(frames), 'fps': 30, 'frames': 300}}})) video = tmp_path / 'edit.mp4' video.write_bytes(b'edited') manifest = {'schema': 'simscene.video_edit.v1', 'path': str(video), 'sha256': digest(video), 'segments': [{'run_id': 'run-a', 'run_directory': str(run), 'camera': 'overview', 'source': str(source), 'source_sha256': digest(source), 'source_frame_manifest_sha256': digest(frames), - 'run_lock_sha256': digest(lock), 'evidence_lock_sha256': digest(evidence)}]} + 'run_lock_sha256': digest(lock), 'evidence_lock_sha256': digest(evidence), + 'source_start_frame': 0, 'source_end_frame_exclusive': 300, 'source_fps': 30, + 'source_sim_start_s': 2/60, 'source_sim_end_s': 10+2/60, + 'speed': 1, 'output_start_s': 0., 'output_end_s': 10., 'output_frames': 300}]} return run, video, manifest @@ -77,6 +80,12 @@ def test_media_mapping_requires_the_actual_run_camera_and_frame_manifest(tmp_pat wrong = json.loads(json.dumps(edit)) wrong['segments'][0]['camera'] = 'another-camera' assert mod.check_edit_binding(wrong, video, run) + wrong = json.loads(json.dumps(edit)) + wrong['segments'][0]['speed'] = 2 + assert mod.check_edit_binding(wrong, video, run) + wrong = json.loads(json.dumps(edit)) + wrong['segments'][0]['source_start_frame'] = 60 + assert mod.check_edit_binding(wrong, video, run) (run / 'camera_overview.frames.jsonl').write_text('tampered\n') assert mod.check_edit_binding(edit, video, run) @@ -95,6 +104,18 @@ def test_visual_review_is_bound_to_the_actual_video_and_remains_a_declaration(tm assert mod.check_visual_review(review, video, duration_s=1.) +def test_visual_review_must_cover_open_close_and_final_result(tmp_path): + mod=implementation(); video=tmp_path/'film.mp4';video.write_bytes(b'candidate') + review={'decision':'accept','reviewer':'reviewer','video_sha256':digest(video), + 'reviewed_windows':[{'start_s':9.9,'end_s':10.,'observation':'last still frame'}]} + required=[{'start_s':0.,'end_s':1.},{'start_s':4.,'end_s':5.},{'start_s':9.,'end_s':10.}] + assert mod.check_visual_review(review,video,10.,required_windows=required) + review['reviewed_windows']=[{'start_s':0.,'end_s':1.,'observation':'open'}, + {'start_s':4.,'end_s':5.,'observation':'close'}, + {'start_s':9.,'end_s':10.,'observation':'result'}] + assert mod.check_visual_review(review,video,10.,required_windows=required)==[] + + def test_missing_review_does_not_hide_an_available_physical_result(tmp_path, monkeypatch): mod = implementation() from simscene.verification import automatic_cabinet_layout From 260bdc46f86386d90d2c13e62508f14820c025ad Mon Sep 17 00:00:00 2001 From: shaoxiang <519517384@qq.com> Date: Tue, 17 Nov 2026 18:57:46 +0800 Subject: [PATCH 12/20] Batch fixed cabinet MCP workflow and retain full evidence --- docs/validation/integration-release-matrix.md | 19 ++ experiments/run_cabinet_mcp.py | 29 ++ plugins/build.py | 5 +- skills/build-scene/SKILL.md | 7 + .../references/integration-workspace.md | 21 ++ src/simscene/recipes/cabinet_mcp_workflow.py | 247 ++++++++++++++++++ tests/agent/test_package.py | 3 +- tests/test_cabinet_mcp_workflow.py | 67 +++++ 8 files changed, 395 insertions(+), 3 deletions(-) create mode 100644 experiments/run_cabinet_mcp.py create mode 100644 src/simscene/recipes/cabinet_mcp_workflow.py create mode 100644 tests/test_cabinet_mcp_workflow.py diff --git a/docs/validation/integration-release-matrix.md b/docs/validation/integration-release-matrix.md index 621e0bd..4e97c3d 100644 --- a/docs/validation/integration-release-matrix.md +++ b/docs/validation/integration-release-matrix.md @@ -16,6 +16,25 @@ worker, checker, and independent backend runtimes for each qualification. | MobilityGen | Standalone fixed-route Jetbot pair | Experimental and outside the general scene job/MCP workflow; native velocity consistency is not verified. | | DyCraft authoring | Separate development branch and its own recorded outcomes | Its earlier client qualifications remain incomplete; this integration line does not inherit them. | +## Pinned integration examples + +The following results apply only to the pinned inputs, settings and recorded +runs, not to every object from the named sources: + +| Example | Evidence and boundary | +| --- | --- | +| `automatic_cabinet_layout` | An installed MCP session queried and prepared a USDCraft cabinet, two ABO notebook instances and a GSO box, applied a clearance-aware layout and passed a real 600-step Isaac run and independent case check. The technical video was reviewed through decoded samples; uninterrupted playback was not reviewed. Repeat the case for a new package or scene. | +| `integration_workspace` | The pinned USDCraft `ds_R022_02` two-drawer cabinet carried one independent GSO box in the lower drawer. The matched control removed only lower-drawer commands; the upper drawer still moved. Actual contact and relative poses were recorded. Drives were scheduled, and the observed contact data are not a general penetration certification. | +| Motion keepouts | The supplied hinge and two-slider profiles cover their inspected native geometry and stated joint ranges. Unknown geometry is not assessed. Layout feasibility remains a geometric precheck, not a physics result. | +| ArtVIP and SDK examples | The pinned door and guide-plate pair retain their previous limited checks. They do not qualify arbitrary ArtVIP objects or SDK-generated assets. | +| Client use | A real first Codex QI1 attempt exhausted its token budget before starting physics. A new package, compact workflow and any subsequent qualification must be identified and reported separately. The package version alone does not demonstrate a successful client session. | +| Showcase video | An independently captured, source-mapped candidate exists; its visual review is `change_needed`. Video acceptance and physical acceptance are separate. | + +The compact installed cabinet helper records real MCP requests and responses; +it does not make a visual judgment. For a new job, retain the actual run, +checker output, source mapping and attributed review. No cross-task token +advantage has been established by this evidence. + The recorded physical examples use Isaac Sim 6.2.0-rc.14 on the documented Linux host. Prepared assets, callbacks and frame records must be checked for each new run. Hashes support integrity comparisons; they are not signatures. diff --git a/experiments/run_cabinet_mcp.py b/experiments/run_cabinet_mcp.py new file mode 100644 index 0000000..d937ea3 --- /dev/null +++ b/experiments/run_cabinet_mcp.py @@ -0,0 +1,29 @@ +"""Execute the fixed cabinet example with actual installed MCP operations.""" +import argparse +import asyncio +import json +from pathlib import Path + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--output', required=True, help='new directory for full MCP records and artifacts') + parser.add_argument('--wheel', required=True, help='wheel matching the installed package build-info') + parser.add_argument('--scene-id', default='compact_cabinet_reproduction') + parser.add_argument('--mcp-launcher', help='optional Python stdio launcher for this installed MCP server') + args = parser.parse_args() + plugin = Path(__file__).resolve().parents[1] + from simscene.recipes.cabinet_mcp_workflow import WorkflowError, run_installed + try: + result = asyncio.run(run_installed(plugin, args.wheel, args.output, args.scene_id, args.mcp_launcher)) + except (WorkflowError, OSError, ValueError, KeyError, TypeError) as error: + print(json.dumps({'status': 'incomplete', 'error': str(error)[:500], 'directory': args.output, + 'recovery': 'If physics-job.json exists, reconnect to that exact job ID; do not start a duplicate.'}, + ensure_ascii=False)) + return 2 + print(json.dumps(result, ensure_ascii=False)) + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/plugins/build.py b/plugins/build.py index d82d854..757374d 100644 --- a/plugins/build.py +++ b/plugins/build.py @@ -97,7 +97,7 @@ def verify_source_snapshot(root, snapshot, commit, paths=None): 'usdcraft_sdk_guide':('assets.lock.json','case.json','recipe-short.json','recipe-long.json','check_pair.py'), } EXAMPLE_HELPERS=('acquire_recipe_assets.py','apply_scene_recipe.py','freeze_recipe_case.py', - 'check_motion_clearance.py','assemble_integration_receipt.py') + 'check_motion_clearance.py','assemble_integration_receipt.py','run_cabinet_mcp.py') def write(path, value): path.parent.mkdir(parents=True,exist_ok=True) path.write_text(json.dumps(value,indent=2)+'\n') @@ -153,7 +153,8 @@ def copy_installed_dependencies(vendor): 'worker/gpu_queue.py','generation/worker.py','generation/backend_worker.py', 'generation/templates/guide_plate_v1.py','generation/templates/usdcraft_sdk_guide_plate_v1.py', 'generation/usdcraft_backend_worker.py','preparation/articulation_v2.py', - 'verification/articulated_asset_two_joint_pair.py','catalog/providers/artvip.py'): + 'verification/articulated_asset_two_joint_pair.py','catalog/providers/artvip.py', + 'recipes/cabinet_mcp_workflow.py'): assert root.joinpath(name).is_file(),name from simscene.catalog.registry import load_registry from simscene.recipes.registry import list_recipes diff --git a/skills/build-scene/SKILL.md b/skills/build-scene/SKILL.md index d0ff9d0..0db50be 100644 --- a/skills/build-scene/SKILL.md +++ b/skills/build-scene/SKILL.md @@ -13,6 +13,13 @@ modules, compact first-handoff diagnosis and machine-side waiting, read they remove repeated geometry or log-reading work; unsupported cases remain explicit rather than inheriting a previous example's physical pass. +For the exact installed `automatic_cabinet_layout` reproduction, the fixed +example reference describes a compact MCP workflow that performs the real +search, preparation, layout, simulation, verification and video export in one +machine-side call. It saves full MCP responses and returns short artifact +paths. Read and visually review the recorded action windows yourself; the +workflow never writes an acceptance decision. + Use `environment_probe` to establish the available backend. Configure a supplied Isaac launcher with `environment_configure` when needed. Start with `catalog_search`: it returns bounded metadata, critical gaps and detail links; diff --git a/skills/build-scene/references/integration-workspace.md b/skills/build-scene/references/integration-workspace.md index c21599e..6aa201a 100644 --- a/skills/build-scene/references/integration-workspace.md +++ b/skills/build-scene/references/integration-workspace.md @@ -42,6 +42,27 @@ not bundled. Search metadata with `catalog_search`, then use `asset_plan` and prepared bindings. Record transfer categories rather than assuming a warm cache proves a cold download. Check per-asset license and missing dependencies. +For this exact cabinet reproduction, a shell-capable client can combine these +real MCP calls without returning each long response to the model. Set `PLUGIN` +to the installed package root and supply its matching wheel and a **new** +output directory: + +```sh +PYTHONPATH="$PLUGIN/server/vendor" python3 "$PLUGIN/experiments/run_cabinet_mcp.py" \ + --wheel /path/to/rosclaw_simscene.whl --output /path/to/new-work-directory +``` + +The optional `--mcp-launcher` selects a Python stdio launcher for the *same* +installed package (for example, a client's budgeted MCP wrapper). The command +checks the reported installed module and wheel, calls the actual MCP search, +prepare, layout, simulation, verification and video tools, and writes complete +responses and job IDs under the output directory. Its compact result points to +`delivery-paths.json`, the decoded frames, and the unreviewed technical film. +Use the existing backend environment settings for Isaac, USD and layout. +The command does not supply a visual review or create a final receipt. If it is +interrupted after `physics-job.json` is saved, reconnect using that exact job ID +and the existing `job_status`; do not start a duplicate run. + For shell-capable clients, the installed package also contains the same small helpers as the source tree: `experiments/acquire_recipe_assets.py`, `experiments/apply_scene_recipe.py`, `experiments/freeze_recipe_case.py` and diff --git a/src/simscene/recipes/cabinet_mcp_workflow.py b/src/simscene/recipes/cabinet_mcp_workflow.py new file mode 100644 index 0000000..b119a20 --- /dev/null +++ b/src/simscene/recipes/cabinet_mcp_workflow.py @@ -0,0 +1,247 @@ +"""Compact, evidence-preserving MCP workflow for one pinned cabinet recipe. + +The workflow performs real MCP calls and records their complete responses. +It does not create a visual review or turn a completed job into acceptance. +""" +import asyncio +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from datetime import timedelta + + +class WorkflowError(RuntimeError): + """A selected asset, operation or verification could not be completed.""" + + +def _sha(path): + h = hashlib.sha256() + with Path(path).open('rb') as stream: + for block in iter(lambda: stream.read(1024 * 1024), b''): + h.update(block) + return h.hexdigest() + + +def _write(path, value): + with Path(path).open('x', encoding='utf8') as stream: + json.dump(value, stream, ensure_ascii=False, indent=2, allow_nan=False) + stream.write('\n') + + +def check_identity(identity, plugin, wheel): + plugin, wheel = Path(plugin).resolve(), Path(wheel).resolve() + module = plugin / 'server/vendor/simscene/__init__.py' + if not module.is_file() or Path(identity.get('module_path', '')).resolve() != module: + raise WorkflowError('MCP is not running the requested installed package') + info = identity.get('build_info') + if (not wheel.is_file() or not isinstance(info, dict) or info.get('source_clean') is not True + or info.get('wheel_sha256') != _sha(wheel)): + raise WorkflowError('installed build does not match the supplied clean-source wheel') + try: + installed_info = json.loads((plugin/'server/build-info.json').read_text()) + except (OSError, ValueError) as error: + raise WorkflowError('installed build identity is unreadable') from error + if installed_info != info: + raise WorkflowError('installed build record differs from the MCP identity') + if identity.get('module_sha256') and identity['module_sha256'] != _sha(module): + raise WorkflowError('installed module changed after MCP startup') + + +class MCPJournal: + """Keep complete responses in files while returning ordinary Python values.""" + def __init__(self, session, directory): + self.session = session + self.directory = Path(directory) + self.counter = 0 + + async def call(self, name, arguments): + self.counter += 1 + started = time.time() + response = await self.session.call_tool(name, arguments) + raw = response.model_dump(mode='json', exclude_none=True) + _write(self.directory / f'{self.counter:03d}-{name}.json', + {'tool': name, 'arguments': arguments, 'started_unix': started, + 'finished_unix': time.time(), 'response': raw}) + if response.isError: + raise WorkflowError(f'{name} failed; inspect the recorded MCP response') + value = response.structuredContent + if value is None: + try: + value = json.loads(response.content[0].text) + except (IndexError, AttributeError, ValueError, TypeError) as error: + raise WorkflowError(f'{name} did not return structured JSON') from error + if not isinstance(value, dict): + raise WorkflowError(f'{name} returned an unexpected result') + return value + + +async def wait_for_job(journal, job_id, receipt, timeout): + waited = await journal.call('job_status', {'job_id': job_id, 'wait_seconds': float(timeout), + 'receipt_path': str(receipt)}) + if waited.get('state') != 'completed': + raise WorkflowError(f'job {job_id} {waited.get("state", "unknown")}; reconnect using its saved job ID') + actual = await journal.call('job_status', {'job_id': job_id}) + if actual.get('state') != 'completed': + raise WorkflowError(f'job {job_id} {actual.get("state", "unknown")} after waiting') + return actual + + +def _helper(plugin, directory, name, arguments): + command = [sys.executable, str(plugin/'experiments'/name), *map(str, arguments)] + env = dict(os.environ, PYTHONPATH=str(plugin/'server/vendor')) + process = subprocess.run(command, env=env, capture_output=True, text=True) + log = directory / f'helper-{len(list(directory.glob("helper-*.json")))+1:03d}.json' + _write(log, {'command': command, 'returncode': process.returncode, + 'stdout': process.stdout, 'stderr': process.stderr}) + if process.returncode: + raise WorkflowError(f'{name} failed; inspect {log}') + try: + return json.loads(process.stdout) + except ValueError as error: + raise WorkflowError(f'{name} did not return JSON; inspect {log}') from error + + +async def run(session, plugin, wheel, root, scene_id): + plugin, wheel, root = Path(plugin).resolve(), Path(wheel).resolve(), Path(root).resolve() + example = plugin/'examples/automatic_cabinet_layout' + journal_dir = root/'mcp-calls'; journal_dir.mkdir() + journal = MCPJournal(session, journal_dir) + response = await session.read_resource('simscene://runtime/identity') + identity = json.loads(response.contents[0].text) + check_identity(identity, plugin, wheel) + _write(root/'identity.json', {'runtime_identity': identity, 'wheel_path': str(wheel)}) + response = await session.read_resource('simscene://recipes/examples') + examples = json.loads(response.contents[0].text) + _write(root/'examples.json', examples) + if not any(x.get('id') == 'automatic_cabinet_layout' for x in examples.get('examples', [])): + raise WorkflowError('installed fixed cabinet recipe is unavailable') + lock = json.loads((example/'assets.lock.json').read_text()) + bindings = {} + for role, query in [('cabinet', 'Lift-Up Wall Cabinet'), + ('book_a', 'AmazonBasics Classic Blank Notebook'), + ('box', 'Ready to Use Rolled Fondant Pure White')]: + selected = lock['assets'][role] + found = await journal.call('catalog_search', {'query': query, + 'filters': {'source_ids': [selected['source_ref']['source_id']]}, 'limit': 20}) + budgets = found.get('budgets', {}) + if budgets.get('model_bytes') != 0 or budgets.get('preview_bytes') != 0: + raise WorkflowError(f'{role} metadata search downloaded a model or preview, or did not report bytes') + item = next((x for x in found.get('items', []) if x.get('ref') == selected['source_ref']), None) + if not item: + raise WorkflowError(f'locked {role} was not returned by the catalog') + plan = await journal.call('asset_plan', {'asset_ref': item['ref'], 'profile_id': selected['profile_id'], + 'parameters': selected['parameters'], 'budget_bytes': 50_000_000}) + if not plan.get('ready_to_fetch'): + raise WorkflowError(f'locked {role} is blocked; inspect asset_plan') + job = await journal.call('asset_prepare', {'plan_id': plan['plan_id'], + 'request_id': f'{scene_id}-prepare-{role}'}) + _write(root/f'prepare-{role}-job.json', job) + done = await wait_for_job(journal, job['job_id'], root/f'prepare-{role}-wait.json', 300) + prepared = done['result'] + bindings[role] = {'asset_path': prepared['root'], 'asset_binding': { + 'manifest_path': prepared['manifest_path'], 'manifest_sha256': prepared['manifest_sha256']}} + _write(root/'bindings.json', bindings) + _helper(plugin, root, 'apply_scene_recipe.py', [example/'recipe.json', '--asset-catalog', root/'bindings.json', + '--asset-lock', example/'assets.lock.json', '--save-directory', root/'ops', '--operations-only']) + operations = json.loads((root/'ops/resolved-operations.json').read_text()) + opened = await journal.call('scene_open', {'scene_id': scene_id}) + await journal.call('scene_apply', {'scene_id': scene_id, 'base_revision': opened['revision'], + 'request_id': f'{scene_id}-create', 'operations': operations}) + scene = await journal.call('scene_get', {'scene_id': scene_id}) + _write(root/'scene-before-layout.json', scene) + _helper(plugin, root, 'check_motion_clearance.py', ['--scene', root/'scene-before-layout.json', + '--owner', 'cabinet', '--profile', 'usdcraft_lift_cabinet_v1', '--output', root/'motion-before.json']) + sweep = json.loads((root/'motion-before.json').read_text()) + if sweep.get('status') != 'not_checked' or not sweep.get('keepout_bounds'): + raise WorkflowError('cabinet motion envelope was not computed') + reserve = json.loads((example/'supplemental-checks.json').read_text())['reserved_volume'] + if not all(all(reserve['min'][i] <= bound['min'][i] and reserve['max'][i] >= bound['max'][i] + for i in range(3)) for bound in sweep['keepout_bounds']): + raise WorkflowError('fixed reserved volume no longer encloses the measured cabinet sweep') + proposal = await journal.call('scene_plan_layout', {'scene_id': scene_id, 'ids': ['box','book_a','book_b'], + 'support': 'table', 'seed': 42, 'clearance_m': .05, 'gap_m': .04, + 'avoid_ids': ['cabinet'], 'keepout_bounds': [reserve]}) + await journal.call('scene_apply', {'scene_id': scene_id, 'base_revision': proposal['base_revision'], + 'request_id': f'{scene_id}-layout', 'operations': proposal['operations']}) + scene = await journal.call('scene_get', {'scene_id': scene_id}); _write(root/'scene.json', scene) + _helper(plugin, root, 'check_motion_clearance.py', ['--scene', root/'scene.json', '--owner', 'cabinet', + '--profile', 'usdcraft_lift_cabinet_v1', '--object', 'box', '--object', 'book_a', '--object', 'book_b', + '--output', root/'motion-after.json']) + if json.loads((root/'motion-after.json').read_text()).get('status') != 'clear': + raise WorkflowError('the applied layout conflicts with the cabinet motion envelope') + measurements = await journal.call('scene_measure', {'scene_id': scene_id, + 'ids': ['floor','table','cabinet','box','book_a','book_b'], 'include_overlap_candidates': True}) + _write(root/'measurements.json', measurements) + validation = await journal.call('scene_validate', {'scene_id': scene_id}) + if validation.get('issues') != []: + raise WorkflowError('scene validation reported issues; inspect MCP transcript') + _helper(plugin, root, 'freeze_recipe_case.py', [example/'case.json', '--bindings', root/'bindings.json', + '--asset-lock', example/'assets.lock.json', '--output', root/'case.json']) + job = await journal.call('simulation_start', {'scene_id': scene_id, 'steps': 600, 'seed': 42, + 'case_path': str(root/'case.json'), 'request_id': f'{scene_id}-physics'}) + _write(root/'physics-job.json', job) # The durable ID remains available if the client disconnects. + status = await wait_for_job(journal, job['job_id'], root/'physics-wait.json', 1800) + result_file = status.get('result_file') + if not isinstance(result_file, str) or not Path(result_file).is_file(): + raise WorkflowError('completed job did not expose a result file') + run_directory = Path(result_file).resolve().parent + if run_directory.name != job.get('run_id'): + raise WorkflowError('job and run identifiers do not match') + for name in ('run_verify_lock','run_verify_evidence','run_verify'): + verified = await journal.call(name, {'job_id': job['job_id']}) + _write(root/f'{name}.json', verified) + if verified.get('passed') is not True: + raise WorkflowError(f'{name} did not pass') + command = [sys.executable, str(example/'check.py'), '--run', str(run_directory), + '--output', str(root/'physical-check.json')] + checked = subprocess.run(command, env=dict(os.environ, PYTHONPATH=str(plugin/'server/vendor')), + capture_output=True, text=True) + _write(root/'physical-check-process.json', {'command': command, 'returncode': checked.returncode, + 'stdout': checked.stdout, 'stderr': checked.stderr}) + if checked.returncode or json.loads((root/'physical-check.json').read_text()).get('passed') is not True: + raise WorkflowError('independent fixed-cabinet physical checker did not pass') + segments = [{'run_directory': str(run_directory), 'camera': camera, + 'start_sim_time_s': start, 'end_sim_time_s': end} for camera,start,end in + [('overview',2/60,1.),('detail',1.,6.),('overview',6.,10+2/60)]] + movie = root/'technical-1080p.mp4' + exported = await journal.call('video_export', {'segments': segments, 'destination': str(movie), + 'output_resolution': [1920,1080]}) + _write(root/'video-export.json', exported) + inspected = await journal.call('video_inspect', {'path': str(movie), 'output_dir': str(root/'decoded'), + 'representative_count': 9}) + _write(root/'video-inspection.json', inspected) + if not (inspected.get('simulation_timeline') or {}).get('passed'): + raise WorkflowError('video timeline inspection did not pass') + from .integration_delivery import check_edit_binding + media_errors = check_edit_binding(json.loads(movie.with_suffix('.edit.json').read_text()), movie, run_directory) + if media_errors or inspected.get('decoded_frame_count') != 300: + raise WorkflowError('technical video does not match the complete recorded run: ' + '; '.join(media_errors)) + paths = {'scene': str(root/'scene.json'), 'run': str(run_directory), 'case': str(root/'case.json'), + 'recipe': str(example/'recipe.json'), 'identity': str(root/'identity.json'), 'video': str(movie), + 'edit_map': str(movie.with_suffix('.edit.json')), 'example_directory': str(example)} + _write(root/'delivery-paths.json', paths) + return {'status': 'physical_and_media_checked_needs_visual_review', 'job_id': job['job_id'], + 'run_id': job['run_id'], 'directory': str(root), 'delivery_paths': str(root/'delivery-paths.json'), + 'video_inspection': str(root/'video-inspection.json'), 'video': str(movie), + 'next': 'Actually inspect the opening, closing and final video windows; save an attributed review and assemble a receipt.', + 'scope': 'Fixed example only; sampled frames are not uninterrupted playback or an automatic visual acceptance.'} + + +async def run_installed(plugin, wheel, root, scene_id, launcher=None): + from mcp import ClientSession, StdioServerParameters + from mcp.client.stdio import stdio_client + plugin, root = Path(plugin).resolve(), Path(root).resolve() + root.mkdir(parents=True, exist_ok=False) + launcher = Path(launcher).resolve() if launcher else plugin/'server/launch.py' + if not launcher.is_file(): + raise WorkflowError('MCP launcher does not exist') + params = StdioServerParameters(command=sys.executable, args=[str(launcher)], env=dict(os.environ), cwd=str(root)) + with (root/'mcp-stderr.log').open('w', encoding='utf8') as error_log: + async with stdio_client(params, errlog=error_log) as (reader, writer): + async with ClientSession(reader, writer, read_timeout_seconds=timedelta(seconds=1900)) as session: + await session.initialize() + return await run(session, plugin, wheel, root, scene_id) diff --git a/tests/agent/test_package.py b/tests/agent/test_package.py index 7e66779..cc9d212 100644 --- a/tests/agent/test_package.py +++ b/tests/agent/test_package.py @@ -116,7 +116,8 @@ async def check_independent_metadata(root,plugin): 'experiments/apply_scene_recipe.py', 'experiments/freeze_recipe_case.py', 'experiments/check_motion_clearance.py', - 'experiments/assemble_integration_receipt.py'): + 'experiments/assemble_integration_receipt.py', + 'experiments/run_cabinet_mcp.py'): self.assertEqual((plugin/sample).read_bytes(),(ROOT/sample).read_bytes(),sample) for original in (ROOT/'skills').rglob('*.md'): reference=plugin/'skills'/original.relative_to(ROOT/'skills') diff --git a/tests/test_cabinet_mcp_workflow.py b/tests/test_cabinet_mcp_workflow.py new file mode 100644 index 0000000..4d3e50e --- /dev/null +++ b/tests/test_cabinet_mcp_workflow.py @@ -0,0 +1,67 @@ +"""The compact client workflow must retain real evidence and fail closed.""" +import asyncio +import hashlib +import importlib +import json +from pathlib import Path + +import pytest + + +def module(): + return importlib.import_module('simscene.recipes.cabinet_mcp_workflow') + + +class Result: + def __init__(self, value, is_error=False): + self.structuredContent = value + self.isError = is_error + self.content = [] + def model_dump(self, **_): + return {'structuredContent': self.structuredContent, 'isError': self.isError} + + +class Session: + def __init__(self, results): + self.results = list(results); self.calls = [] + async def call_tool(self, name, args): + self.calls.append((name, args)) + return self.results.pop(0) + + +def test_journal_persists_complete_mcp_responses_and_rejects_tool_errors(tmp_path): + mod = module(); session = Session([Result({'id': 'chosen', 'metadata': 'x' * 10000}), + Result({'message': 'dependency missing'}, is_error=True)]) + journal = mod.MCPJournal(session, tmp_path) + assert asyncio.run(journal.call('catalog_search', {'query': 'cabinet'}))['id'] == 'chosen' + saved = json.loads(next(tmp_path.glob('*catalog_search.json')).read_text()) + assert saved['response']['structuredContent']['metadata'] == 'x' * 10000 + with pytest.raises(mod.WorkflowError, match='asset_prepare'): + asyncio.run(journal.call('asset_prepare', {'plan_id': 'pinned'})) + assert len(list(tmp_path.glob('*.json'))) == 2 + + +def test_wait_uses_real_job_result_and_never_treats_failed_jobs_as_success(tmp_path): + mod = module() + good = Session([Result({'state': 'completed'}), Result({'state': 'completed', 'result': {'root': '/asset'}})]) + value = asyncio.run(mod.wait_for_job(mod.MCPJournal(good, tmp_path), 'job-a', tmp_path/'wait.json', 60)) + assert value['result']['root'] == '/asset' + assert [name for name, _ in good.calls] == ['job_status', 'job_status'] + other = tmp_path/'failed'; other.mkdir() + failed = Session([Result({'state': 'failed', 'error': 'unavailable'})]) + with pytest.raises(mod.WorkflowError, match='failed'): + asyncio.run(mod.wait_for_job(mod.MCPJournal(failed, other), 'job-b', other/'wait.json', 60)) + assert len(failed.calls) == 1 + + +def test_identity_rejects_wrong_wheel_or_development_checkout(tmp_path): + mod = module(); plugin = tmp_path/'plugin'; package=plugin/'server/vendor/simscene'; package.mkdir(parents=True) + (package/'__init__.py').write_text('installed') + wheel=tmp_path/'plugin.whl';wheel.write_bytes(b'actual') + identity={'module_path':str(package/'__init__.py'),'build_info':{'wheel_sha256':hashlib.sha256(b'actual').hexdigest(),'source_clean':True}} + (plugin/'server/build-info.json').write_text(json.dumps(identity['build_info'])) + mod.check_identity(identity, plugin, wheel) + with pytest.raises(mod.WorkflowError, match='wheel'): + mod.check_identity({**identity, 'build_info':{'wheel_sha256':'0'*64,'source_clean':True}},plugin,wheel) + with pytest.raises(mod.WorkflowError, match='installed'): + mod.check_identity({**identity, 'module_path':str(tmp_path/'checkout/simscene/__init__.py')},plugin,wheel) From 6462191be8dfa2c5adc37efe5bf0eba882cfd2d7 Mon Sep 17 00:00:00 2001 From: shaoxiang <519517384@qq.com> Date: Tue, 17 Nov 2026 19:06:37 +0800 Subject: [PATCH 13/20] Constrain compact workflow identity, budget routing and recovery --- experiments/run_cabinet_mcp.py | 23 +- plugins/build.py | 13 +- .../references/integration-workspace.md | 10 +- src/simscene/recipes/cabinet_mcp_workflow.py | 322 ++++++++++++------ tests/test_build_identity.py | 7 + tests/test_cabinet_mcp_workflow.py | 83 ++++- 6 files changed, 347 insertions(+), 111 deletions(-) diff --git a/experiments/run_cabinet_mcp.py b/experiments/run_cabinet_mcp.py index d937ea3..671d1ef 100644 --- a/experiments/run_cabinet_mcp.py +++ b/experiments/run_cabinet_mcp.py @@ -3,22 +3,35 @@ import asyncio import json from pathlib import Path +import traceback def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--output', required=True, help='new directory for full MCP records and artifacts') parser.add_argument('--wheel', required=True, help='wheel matching the installed package build-info') - parser.add_argument('--scene-id', default='compact_cabinet_reproduction') + parser.add_argument('--scene-id', help='optional new unique scene ID') parser.add_argument('--mcp-launcher', help='optional Python stdio launcher for this installed MCP server') + parser.add_argument('--resume', action='store_true', help='reconnect using the exact saved physics request') args = parser.parse_args() plugin = Path(__file__).resolve().parents[1] - from simscene.recipes.cabinet_mcp_workflow import WorkflowError, run_installed + from simscene.recipes.cabinet_mcp_workflow import new_scene_id, run_installed try: - result = asyncio.run(run_installed(plugin, args.wheel, args.output, args.scene_id, args.mcp_launcher)) - except (WorkflowError, OSError, ValueError, KeyError, TypeError) as error: + scene_id = args.scene_id if args.resume else (args.scene_id or new_scene_id()) + result = asyncio.run(run_installed(plugin, args.wheel, args.output, scene_id, args.mcp_launcher, + resume=args.resume)) + except Exception as error: + directory = Path(args.output) + if directory.is_dir(): + for index in range(10000): + log = directory/f'workflow-error-{index:04d}.log' + try: + with log.open('x', encoding='utf8') as stream:stream.write(traceback.format_exc()) + break + except FileExistsError: + continue print(json.dumps({'status': 'incomplete', 'error': str(error)[:500], 'directory': args.output, - 'recovery': 'If physics-job.json exists, reconnect to that exact job ID; do not start a duplicate.'}, + 'recovery': 'If physics-request.json exists, rerun with --resume and the same output and wheel; the exact request ID is reused.'}, ensure_ascii=False)) return 2 print(json.dumps(result, ensure_ascii=False)) diff --git a/plugins/build.py b/plugins/build.py index 757374d..0d7ba8f 100644 --- a/plugins/build.py +++ b/plugins/build.py @@ -227,14 +227,23 @@ def build(destination, use_installed_deps=False): patch_module=importlib.util.module_from_spec(patch_spec);patch_spec.loader.exec_module(patch_module) versions_lock={item.metadata['Name']:item.version for item in metadata.distributions(path=[str(vendor)])} write(portable/'server'/'dependency-lock.json',versions_lock) + (portable/'server'/'launch.py').write_text(LAUNCHER) + (portable/'README.md').write_text(PACKAGE_README) + resource_files = [portable/name for name in ('LICENSE','NOTICE','OPEN_SOURCE_NOTICES.md', + 'README.md','server/launch.py')] + for name in ('skills','examples','experiments'): + resource_files.extend(path for path in (portable/name).rglob('*') if path.is_file()) + resource_hashes = {str(path.relative_to(portable)):hashlib.sha256(path.read_bytes()).hexdigest() + for path in sorted(resource_files)} + resource_manifest = portable/'server'/'resource-manifest.json' + write(resource_manifest,{'schema':'simscene.packaged_resources.v1','files':resource_hashes}) write(portable/'server'/'build-info.json',{'python_version':PYTHON_VERSION,'plugin_version':PACKAGE_VERSION, 'builder_python':sys.version.split()[0],'wheel_sha256':wheel_sha256, + 'resource_manifest_sha256':hashlib.sha256(resource_manifest.read_bytes()).hexdigest(), **build_source, 'dependency_mode':'installed' if use_installed_deps else 'pip', 'optional_backends':'Isaac/USD, isolated GLB decoder, layout, Sand3D and USDCraft SDK runtimes are configured separately'}) validate_vendor(vendor) - (portable/'server'/'launch.py').write_text(LAUNCHER) - (portable/'README.md').write_text(PACKAGE_README) write(portable/'plugin.json',{'$schema':'https://agent-plugins.org/schemas/1.0.0/plugin.schema.json','name':'simscene','version':PACKAGE_VERSION,'description':'Discover assets, compose and run experimental simulation scenes.'}) write(portable/'mcp.json',{'$schema':'https://agent-plugins.org/schemas/1.0.0/mcp.schema.json','mcpServers':{'simscene':{'type':'stdio','command':'python3','args':['${PLUGIN_ROOT}/server/launch.py'],'cwd':'${PLUGIN_ROOT}'}}}) claude.mkdir(parents=True) diff --git a/skills/build-scene/references/integration-workspace.md b/skills/build-scene/references/integration-workspace.md index 6aa201a..0eaf23e 100644 --- a/skills/build-scene/references/integration-workspace.md +++ b/skills/build-scene/references/integration-workspace.md @@ -53,15 +53,19 @@ PYTHONPATH="$PLUGIN/server/vendor" python3 "$PLUGIN/experiments/run_cabinet_mcp. ``` The optional `--mcp-launcher` selects a Python stdio launcher for the *same* -installed package (for example, a client's budgeted MCP wrapper). The command +installed package (for example, a client's budgeted MCP wrapper). A configured +`SIMSCENE_MCP_LAUNCHER` takes precedence and cannot be silently replaced by a +different command-line launcher. The command checks the reported installed module and wheel, calls the actual MCP search, prepare, layout, simulation, verification and video tools, and writes complete responses and job IDs under the output directory. Its compact result points to `delivery-paths.json`, the decoded frames, and the unreviewed technical film. Use the existing backend environment settings for Isaac, USD and layout. The command does not supply a visual review or create a final receipt. If it is -interrupted after `physics-job.json` is saved, reconnect using that exact job ID -and the existing `job_status`; do not start a duplicate run. +interrupted after `physics-request.json` is saved, use the same command and add +`--resume` with the original output directory and wheel. It reconnects to the +saved job or reissues the exact persisted request ID and payload, then verifies +the run before any export. It does not replace an existing partial video. For shell-capable clients, the installed package also contains the same small helpers as the source tree: `experiments/acquire_recipe_assets.py`, diff --git a/src/simscene/recipes/cabinet_mcp_workflow.py b/src/simscene/recipes/cabinet_mcp_workflow.py index b119a20..2d3fe9f 100644 --- a/src/simscene/recipes/cabinet_mcp_workflow.py +++ b/src/simscene/recipes/cabinet_mcp_workflow.py @@ -11,6 +11,8 @@ import subprocess import sys import time +import uuid +import zipfile from datetime import timedelta @@ -49,6 +51,84 @@ def check_identity(identity, plugin, wheel): raise WorkflowError('installed build record differs from the MCP identity') if identity.get('module_sha256') and identity['module_sha256'] != _sha(module): raise WorkflowError('installed module changed after MCP startup') + package = module.parent + try: + with zipfile.ZipFile(wheel) as archive: + names = [name for name in archive.namelist() if name.startswith('simscene/') and not name.endswith('/')] + expected = {name[len('simscene/'):] for name in names} + required = {'__init__.py', 'mcp_server.py', 'worker/isaac_run.py', + 'recipes/cabinet_mcp_workflow.py'} + actual = {str(path.relative_to(package)) for path in package.rglob('*') + if path.is_file() and not path.is_symlink() and '__pycache__' not in path.parts + and path.suffix != '.pyc'} + if len(expected) != len(names) or not required <= expected or actual != expected: + raise WorkflowError('installed package inventory differs from the wheel') + for name in expected: + if '..' in Path(name).parts or hashlib.sha256(archive.read('simscene/'+name)).hexdigest() != _sha(package/name): + raise WorkflowError('installed package content differs from the wheel: ' + name) + except (OSError, ValueError, zipfile.BadZipFile, KeyError) as error: + raise WorkflowError('cannot verify installed package against its wheel') from error + manifest_file = plugin/'server/resource-manifest.json' + try: + if info.get('resource_manifest_sha256') != _sha(manifest_file): + raise WorkflowError('installed resource manifest differs from the build record') + manifest = json.loads(manifest_file.read_text()) + files = manifest.get('files') + if manifest.get('schema') != 'simscene.packaged_resources.v1' or not isinstance(files, dict) or not files: + raise WorkflowError('installed resource manifest is invalid') + for name, digest in files.items(): + relative = Path(name) + if relative.is_absolute() or '..' in relative.parts or not name or '\\' in name: + raise WorkflowError('installed resource manifest contains an unsafe path') + path = plugin/relative + if path.is_symlink() or not path.is_file() or _sha(path) != digest: + raise WorkflowError('installed resource changed: ' + name) + except (OSError, ValueError, TypeError, AttributeError) as error: + raise WorkflowError('cannot verify installed resources') from error + + +def new_scene_id(): + return 'compact_cabinet_' + uuid.uuid4().hex[:16] + + +def read_recovery_request(root): + root = Path(root).resolve() + try: + request = json.loads((root/'physics-request.json').read_text()) + if (set(request) != {'scene_id', 'steps', 'seed', 'case_path', 'request_id'} + or request['steps'] != 600 or request['seed'] != 42 + or Path(request['case_path']).resolve() != root/'case.json' + or not isinstance(request['scene_id'], str) or not request['scene_id'] + or request['request_id'] != request['scene_id'] + '-physics'): + raise ValueError('invalid fixed request') + return request + except (OSError, ValueError, TypeError, KeyError) as error: + raise WorkflowError('original physics recovery request is missing or invalid') from error + + +def _scene_hash(scene): + return hashlib.sha256(json.dumps(scene, sort_keys=True, separators=(',', ':'), allow_nan=False).encode()).hexdigest() + + +def check_run_scene(scene, run_directory): + try: + lock = json.loads((Path(run_directory)/'run-lock.json').read_text()) + if (lock.get('source_scene_sha256') != _scene_hash(scene) + or lock.get('scene_revision') != scene.get('revision')): + raise WorkflowError('run scene or revision differs from the saved scene') + except (OSError, ValueError, TypeError, AttributeError) as error: + raise WorkflowError('cannot bind the run to the saved scene') from error + + +def _next_path(path): + path = Path(path) + if not path.exists(): + return path + for index in range(1, 10000): + candidate = path.with_name(f'{path.stem}-recheck-{index}{path.suffix}') + if not candidate.exists(): + return candidate + raise WorkflowError('too many retained recovery records') class MCPJournal: @@ -56,16 +136,21 @@ class MCPJournal: def __init__(self, session, directory): self.session = session self.directory = Path(directory) - self.counter = 0 + self.counter = len(list(self.directory.glob('*-request.json'))) async def call(self, name, arguments): self.counter += 1 started = time.time() - response = await self.session.call_tool(name, arguments) + base = f'{self.counter:03d}-{name}' + _write(self.directory/f'{base}-request.json', {'tool': name, 'arguments': arguments, 'started_unix': started}) + try: + response = await self.session.call_tool(name, arguments) + except Exception as error: + _write(self.directory/f'{base}-response.json', {'tool': name, 'finished_unix': time.time(), + 'exception': {'type': type(error).__name__, 'message': str(error)[:1000]}}) + raise WorkflowError(f'{name} failed; inspect the recorded MCP exception') from error raw = response.model_dump(mode='json', exclude_none=True) - _write(self.directory / f'{self.counter:03d}-{name}.json', - {'tool': name, 'arguments': arguments, 'started_unix': started, - 'finished_unix': time.time(), 'response': raw}) + _write(self.directory/f'{base}-response.json', {'tool': name, 'finished_unix': time.time(), 'response': raw}) if response.isError: raise WorkflowError(f'{name} failed; inspect the recorded MCP response') value = response.structuredContent @@ -105,115 +190,144 @@ def _helper(plugin, directory, name, arguments): raise WorkflowError(f'{name} did not return JSON; inspect {log}') from error -async def run(session, plugin, wheel, root, scene_id): +async def run(session, plugin, wheel, root, scene_id, resume=False): plugin, wheel, root = Path(plugin).resolve(), Path(wheel).resolve(), Path(root).resolve() example = plugin/'examples/automatic_cabinet_layout' - journal_dir = root/'mcp-calls'; journal_dir.mkdir() + journal_dir = root/'mcp-calls' + if resume and not journal_dir.is_dir(): + raise WorkflowError('recovery requires the original MCP journal') + journal_dir.mkdir(exist_ok=resume) journal = MCPJournal(session, journal_dir) response = await session.read_resource('simscene://runtime/identity') identity = json.loads(response.contents[0].text) check_identity(identity, plugin, wheel) - _write(root/'identity.json', {'runtime_identity': identity, 'wheel_path': str(wheel)}) - response = await session.read_resource('simscene://recipes/examples') - examples = json.loads(response.contents[0].text) - _write(root/'examples.json', examples) - if not any(x.get('id') == 'automatic_cabinet_layout' for x in examples.get('examples', [])): - raise WorkflowError('installed fixed cabinet recipe is unavailable') - lock = json.loads((example/'assets.lock.json').read_text()) - bindings = {} - for role, query in [('cabinet', 'Lift-Up Wall Cabinet'), - ('book_a', 'AmazonBasics Classic Blank Notebook'), - ('box', 'Ready to Use Rolled Fondant Pure White')]: - selected = lock['assets'][role] - found = await journal.call('catalog_search', {'query': query, - 'filters': {'source_ids': [selected['source_ref']['source_id']]}, 'limit': 20}) - budgets = found.get('budgets', {}) - if budgets.get('model_bytes') != 0 or budgets.get('preview_bytes') != 0: - raise WorkflowError(f'{role} metadata search downloaded a model or preview, or did not report bytes') - item = next((x for x in found.get('items', []) if x.get('ref') == selected['source_ref']), None) - if not item: - raise WorkflowError(f'locked {role} was not returned by the catalog') - plan = await journal.call('asset_plan', {'asset_ref': item['ref'], 'profile_id': selected['profile_id'], - 'parameters': selected['parameters'], 'budget_bytes': 50_000_000}) - if not plan.get('ready_to_fetch'): - raise WorkflowError(f'locked {role} is blocked; inspect asset_plan') - job = await journal.call('asset_prepare', {'plan_id': plan['plan_id'], - 'request_id': f'{scene_id}-prepare-{role}'}) - _write(root/f'prepare-{role}-job.json', job) - done = await wait_for_job(journal, job['job_id'], root/f'prepare-{role}-wait.json', 300) - prepared = done['result'] - bindings[role] = {'asset_path': prepared['root'], 'asset_binding': { - 'manifest_path': prepared['manifest_path'], 'manifest_sha256': prepared['manifest_sha256']}} - _write(root/'bindings.json', bindings) - _helper(plugin, root, 'apply_scene_recipe.py', [example/'recipe.json', '--asset-catalog', root/'bindings.json', - '--asset-lock', example/'assets.lock.json', '--save-directory', root/'ops', '--operations-only']) - operations = json.loads((root/'ops/resolved-operations.json').read_text()) - opened = await journal.call('scene_open', {'scene_id': scene_id}) - await journal.call('scene_apply', {'scene_id': scene_id, 'base_revision': opened['revision'], - 'request_id': f'{scene_id}-create', 'operations': operations}) - scene = await journal.call('scene_get', {'scene_id': scene_id}) - _write(root/'scene-before-layout.json', scene) - _helper(plugin, root, 'check_motion_clearance.py', ['--scene', root/'scene-before-layout.json', - '--owner', 'cabinet', '--profile', 'usdcraft_lift_cabinet_v1', '--output', root/'motion-before.json']) - sweep = json.loads((root/'motion-before.json').read_text()) - if sweep.get('status') != 'not_checked' or not sweep.get('keepout_bounds'): - raise WorkflowError('cabinet motion envelope was not computed') - reserve = json.loads((example/'supplemental-checks.json').read_text())['reserved_volume'] - if not all(all(reserve['min'][i] <= bound['min'][i] and reserve['max'][i] >= bound['max'][i] - for i in range(3)) for bound in sweep['keepout_bounds']): - raise WorkflowError('fixed reserved volume no longer encloses the measured cabinet sweep') - proposal = await journal.call('scene_plan_layout', {'scene_id': scene_id, 'ids': ['box','book_a','book_b'], - 'support': 'table', 'seed': 42, 'clearance_m': .05, 'gap_m': .04, - 'avoid_ids': ['cabinet'], 'keepout_bounds': [reserve]}) - await journal.call('scene_apply', {'scene_id': scene_id, 'base_revision': proposal['base_revision'], - 'request_id': f'{scene_id}-layout', 'operations': proposal['operations']}) - scene = await journal.call('scene_get', {'scene_id': scene_id}); _write(root/'scene.json', scene) - _helper(plugin, root, 'check_motion_clearance.py', ['--scene', root/'scene.json', '--owner', 'cabinet', - '--profile', 'usdcraft_lift_cabinet_v1', '--object', 'box', '--object', 'book_a', '--object', 'book_b', - '--output', root/'motion-after.json']) - if json.loads((root/'motion-after.json').read_text()).get('status') != 'clear': - raise WorkflowError('the applied layout conflicts with the cabinet motion envelope') - measurements = await journal.call('scene_measure', {'scene_id': scene_id, - 'ids': ['floor','table','cabinet','box','book_a','book_b'], 'include_overlap_candidates': True}) - _write(root/'measurements.json', measurements) - validation = await journal.call('scene_validate', {'scene_id': scene_id}) - if validation.get('issues') != []: - raise WorkflowError('scene validation reported issues; inspect MCP transcript') - _helper(plugin, root, 'freeze_recipe_case.py', [example/'case.json', '--bindings', root/'bindings.json', - '--asset-lock', example/'assets.lock.json', '--output', root/'case.json']) - job = await journal.call('simulation_start', {'scene_id': scene_id, 'steps': 600, 'seed': 42, - 'case_path': str(root/'case.json'), 'request_id': f'{scene_id}-physics'}) - _write(root/'physics-job.json', job) # The durable ID remains available if the client disconnects. - status = await wait_for_job(journal, job['job_id'], root/'physics-wait.json', 1800) + identity_record = {'runtime_identity': identity, 'wheel_path': str(wheel)} + if resume: + if json.loads((root/'identity.json').read_text()) != identity_record: + raise WorkflowError('recovery requires the same installed package and wheel') + physics_request = read_recovery_request(root) + if scene_id and scene_id != physics_request['scene_id']: + raise WorkflowError('recovery scene ID differs from the saved request') + scene_id = physics_request['scene_id'] + scene = json.loads((root/'scene.json').read_text()) + else: + _write(root/'identity.json', identity_record) + response = await session.read_resource('simscene://recipes/examples') + examples = json.loads(response.contents[0].text) + _write(root/'examples.json', examples) + if not any(x.get('id') == 'automatic_cabinet_layout' for x in examples.get('examples', [])): + raise WorkflowError('installed fixed cabinet recipe is unavailable') + lock = json.loads((example/'assets.lock.json').read_text()) + bindings = {} + for role, query in [('cabinet', 'Lift-Up Wall Cabinet'), + ('book_a', 'AmazonBasics Classic Blank Notebook'), + ('box', 'Ready to Use Rolled Fondant Pure White')]: + selected = lock['assets'][role] + found = await journal.call('catalog_search', {'query': query, + 'filters': {'source_ids': [selected['source_ref']['source_id']]}, 'limit': 20}) + budgets = found.get('budgets', {}) + if budgets.get('model_bytes') != 0 or budgets.get('preview_bytes') != 0: + raise WorkflowError(f'{role} metadata search downloaded a model or preview, or did not report bytes') + item = next((x for x in found.get('items', []) if x.get('ref') == selected['source_ref']), None) + if not item: + raise WorkflowError(f'locked {role} was not returned by the catalog') + plan = await journal.call('asset_plan', {'asset_ref': item['ref'], 'profile_id': selected['profile_id'], + 'parameters': selected['parameters'], 'budget_bytes': 50_000_000}) + if not plan.get('ready_to_fetch'): + raise WorkflowError(f'locked {role} is blocked; inspect asset_plan') + job = await journal.call('asset_prepare', {'plan_id': plan['plan_id'], + 'request_id': f'{scene_id}-prepare-{role}'}) + _write(root/f'prepare-{role}-job.json', job) + done = await wait_for_job(journal, job['job_id'], root/f'prepare-{role}-wait.json', 300) + prepared = done['result'] + bindings[role] = {'asset_path': prepared['root'], 'asset_binding': { + 'manifest_path': prepared['manifest_path'], 'manifest_sha256': prepared['manifest_sha256']}} + _write(root/'bindings.json', bindings) + _helper(plugin, root, 'apply_scene_recipe.py', [example/'recipe.json', '--asset-catalog', root/'bindings.json', + '--asset-lock', example/'assets.lock.json', '--save-directory', root/'ops', '--operations-only']) + operations = json.loads((root/'ops/resolved-operations.json').read_text()) + opened = await journal.call('scene_open', {'scene_id': scene_id}) + await journal.call('scene_apply', {'scene_id': scene_id, 'base_revision': opened['revision'], + 'request_id': f'{scene_id}-create', 'operations': operations}) + scene = await journal.call('scene_get', {'scene_id': scene_id}) + _write(root/'scene-before-layout.json', scene) + _helper(plugin, root, 'check_motion_clearance.py', ['--scene', root/'scene-before-layout.json', + '--owner', 'cabinet', '--profile', 'usdcraft_lift_cabinet_v1', '--output', root/'motion-before.json']) + sweep = json.loads((root/'motion-before.json').read_text()) + if sweep.get('status') != 'not_checked' or not sweep.get('keepout_bounds'): + raise WorkflowError('cabinet motion envelope was not computed') + reserve = json.loads((example/'supplemental-checks.json').read_text())['reserved_volume'] + if not all(all(reserve['min'][i] <= bound['min'][i] and reserve['max'][i] >= bound['max'][i] + for i in range(3)) for bound in sweep['keepout_bounds']): + raise WorkflowError('fixed reserved volume no longer encloses the measured cabinet sweep') + proposal = await journal.call('scene_plan_layout', {'scene_id': scene_id, 'ids': ['box','book_a','book_b'], + 'support': 'table', 'seed': 42, 'clearance_m': .05, 'gap_m': .04, + 'avoid_ids': ['cabinet'], 'keepout_bounds': [reserve]}) + await journal.call('scene_apply', {'scene_id': scene_id, 'base_revision': proposal['base_revision'], + 'request_id': f'{scene_id}-layout', 'operations': proposal['operations']}) + scene = await journal.call('scene_get', {'scene_id': scene_id}); _write(root/'scene.json', scene) + _helper(plugin, root, 'check_motion_clearance.py', ['--scene', root/'scene.json', '--owner', 'cabinet', + '--profile', 'usdcraft_lift_cabinet_v1', '--object', 'box', '--object', 'book_a', '--object', 'book_b', + '--output', root/'motion-after.json']) + if json.loads((root/'motion-after.json').read_text()).get('status') != 'clear': + raise WorkflowError('the applied layout conflicts with the cabinet motion envelope') + measurements = await journal.call('scene_measure', {'scene_id': scene_id, + 'ids': ['floor','table','cabinet','box','book_a','book_b'], 'include_overlap_candidates': True}) + _write(root/'measurements.json', measurements) + validation = await journal.call('scene_validate', {'scene_id': scene_id}) + if validation.get('issues') != []: + raise WorkflowError('scene validation reported issues; inspect MCP transcript') + _helper(plugin, root, 'freeze_recipe_case.py', [example/'case.json', '--bindings', root/'bindings.json', + '--asset-lock', example/'assets.lock.json', '--output', root/'case.json']) + physics_request = {'scene_id': scene_id, 'steps': 600, 'seed': 42, + 'case_path': str(root/'case.json'), 'request_id': f'{scene_id}-physics'} + _write(root/'physics-request.json', physics_request) + job_file = root/'physics-job.json' + if resume and job_file.exists(): + job = json.loads(job_file.read_text()) + else: + current_scene = await journal.call('scene_get', {'scene_id': scene_id}) + if _scene_hash(current_scene) != _scene_hash(scene): + raise WorkflowError('current scene differs from the saved preflight scene') + job = await journal.call('simulation_start', physics_request) + _write(job_file, job) + status = await wait_for_job(journal, job['job_id'], _next_path(root/'physics-wait.json'), 1800) result_file = status.get('result_file') if not isinstance(result_file, str) or not Path(result_file).is_file(): raise WorkflowError('completed job did not expose a result file') run_directory = Path(result_file).resolve().parent if run_directory.name != job.get('run_id'): raise WorkflowError('job and run identifiers do not match') + check_run_scene(scene, run_directory) for name in ('run_verify_lock','run_verify_evidence','run_verify'): verified = await journal.call(name, {'job_id': job['job_id']}) - _write(root/f'{name}.json', verified) + _write(_next_path(root/f'{name}.json'), verified) if verified.get('passed') is not True: raise WorkflowError(f'{name} did not pass') + physical_check = _next_path(root/'physical-check.json') command = [sys.executable, str(example/'check.py'), '--run', str(run_directory), - '--output', str(root/'physical-check.json')] + '--output', str(physical_check)] checked = subprocess.run(command, env=dict(os.environ, PYTHONPATH=str(plugin/'server/vendor')), capture_output=True, text=True) - _write(root/'physical-check-process.json', {'command': command, 'returncode': checked.returncode, + _write(_next_path(root/'physical-check-process.json'), {'command': command, 'returncode': checked.returncode, 'stdout': checked.stdout, 'stderr': checked.stderr}) - if checked.returncode or json.loads((root/'physical-check.json').read_text()).get('passed') is not True: + if checked.returncode or json.loads(physical_check.read_text()).get('passed') is not True: raise WorkflowError('independent fixed-cabinet physical checker did not pass') segments = [{'run_directory': str(run_directory), 'camera': camera, 'start_sim_time_s': start, 'end_sim_time_s': end} for camera,start,end in [('overview',2/60,1.),('detail',1.,6.),('overview',6.,10+2/60)]] movie = root/'technical-1080p.mp4' - exported = await journal.call('video_export', {'segments': segments, 'destination': str(movie), - 'output_resolution': [1920,1080]}) - _write(root/'video-export.json', exported) - inspected = await journal.call('video_inspect', {'path': str(movie), 'output_dir': str(root/'decoded'), + if movie.exists(): + if not resume or not movie.with_suffix('.edit.json').is_file(): + raise WorkflowError('existing video is incomplete or unexpected; preserve it and inspect manually') + else: + exported = await journal.call('video_export', {'segments': segments, 'destination': str(movie), + 'output_resolution': [1920,1080]}) + _write(_next_path(root/'video-export.json'), exported) + inspected = await journal.call('video_inspect', {'path': str(movie), 'output_dir': str(_next_path(root/'decoded')), 'representative_count': 9}) - _write(root/'video-inspection.json', inspected) + inspection_path = _next_path(root/'video-inspection.json') + _write(inspection_path, inspected) if not (inspected.get('simulation_timeline') or {}).get('passed'): raise WorkflowError('video timeline inspection did not pass') from .integration_delivery import check_edit_binding @@ -223,25 +337,43 @@ async def run(session, plugin, wheel, root, scene_id): paths = {'scene': str(root/'scene.json'), 'run': str(run_directory), 'case': str(root/'case.json'), 'recipe': str(example/'recipe.json'), 'identity': str(root/'identity.json'), 'video': str(movie), 'edit_map': str(movie.with_suffix('.edit.json')), 'example_directory': str(example)} - _write(root/'delivery-paths.json', paths) + delivery_file = root/'delivery-paths.json' + if delivery_file.exists(): + if json.loads(delivery_file.read_text()) != paths: + raise WorkflowError('existing delivery paths do not match the recovered run') + else: + _write(delivery_file, paths) return {'status': 'physical_and_media_checked_needs_visual_review', 'job_id': job['job_id'], 'run_id': job['run_id'], 'directory': str(root), 'delivery_paths': str(root/'delivery-paths.json'), - 'video_inspection': str(root/'video-inspection.json'), 'video': str(movie), + 'video_inspection': str(inspection_path), 'video': str(movie), 'next': 'Actually inspect the opening, closing and final video windows; save an attributed review and assemble a receipt.', 'scope': 'Fixed example only; sampled frames are not uninterrupted playback or an automatic visual acceptance.'} -async def run_installed(plugin, wheel, root, scene_id, launcher=None): +def select_launcher(plugin, requested=None): + configured = os.environ.get('SIMSCENE_MCP_LAUNCHER') + if configured: + selected = Path(configured).expanduser().resolve() + if requested and Path(requested).expanduser().resolve() != selected: + raise WorkflowError('requested launcher differs from the configured MCP launcher') + return selected + return Path(requested).expanduser().resolve() if requested else Path(plugin).resolve()/'server/launch.py' + + +async def run_installed(plugin, wheel, root, scene_id, launcher=None, resume=False): from mcp import ClientSession, StdioServerParameters from mcp.client.stdio import stdio_client plugin, root = Path(plugin).resolve(), Path(root).resolve() - root.mkdir(parents=True, exist_ok=False) - launcher = Path(launcher).resolve() if launcher else plugin/'server/launch.py' + if resume: + if not root.is_dir():raise WorkflowError('recovery output directory does not exist') + else: + root.mkdir(parents=True, exist_ok=False) + launcher = select_launcher(plugin, launcher) if not launcher.is_file(): raise WorkflowError('MCP launcher does not exist') params = StdioServerParameters(command=sys.executable, args=[str(launcher)], env=dict(os.environ), cwd=str(root)) - with (root/'mcp-stderr.log').open('w', encoding='utf8') as error_log: + with _next_path(root/'mcp-stderr.log').open('x', encoding='utf8') as error_log: async with stdio_client(params, errlog=error_log) as (reader, writer): async with ClientSession(reader, writer, read_timeout_seconds=timedelta(seconds=1900)) as session: await session.initialize() - return await run(session, plugin, wheel, root, scene_id) + return await run(session, plugin, wheel, root, scene_id, resume=resume) diff --git a/tests/test_build_identity.py b/tests/test_build_identity.py index 35accf2..f1c0562 100644 --- a/tests/test_build_identity.py +++ b/tests/test_build_identity.py @@ -2,6 +2,8 @@ import subprocess import shutil from pathlib import Path +import hashlib +import json import pytest @@ -79,6 +81,11 @@ def change_during_wheel(command, *args, **kwargs): monkeypatch.setattr(build.subprocess, 'run', change_during_wheel) result = build.build(tmp_path / 'dist', use_installed_deps=True) package = Path(result['portable']) + manifest_path = package/'server/resource-manifest.json' + manifest = json.loads(manifest_path.read_text()) + info = json.loads((package/'server/build-info.json').read_text()) + assert info['resource_manifest_sha256'] == hashlib.sha256(manifest_path.read_bytes()).hexdigest() + assert manifest['files']['skills/build-scene/SKILL.md'] == hashlib.sha256(expected['skills/build-scene/SKILL.md']).hexdigest() for name, content in expected.items(): relative = 'install.py' if name == 'plugins/install.py' else name assert (package / relative).read_bytes() == content, name diff --git a/tests/test_cabinet_mcp_workflow.py b/tests/test_cabinet_mcp_workflow.py index 4d3e50e..3920d14 100644 --- a/tests/test_cabinet_mcp_workflow.py +++ b/tests/test_cabinet_mcp_workflow.py @@ -4,6 +4,7 @@ import importlib import json from pathlib import Path +import zipfile import pytest @@ -26,7 +27,10 @@ def __init__(self, results): self.results = list(results); self.calls = [] async def call_tool(self, name, args): self.calls.append((name, args)) - return self.results.pop(0) + value = self.results.pop(0) + if isinstance(value, Exception): + raise value + return value def test_journal_persists_complete_mcp_responses_and_rejects_tool_errors(tmp_path): @@ -34,11 +38,23 @@ def test_journal_persists_complete_mcp_responses_and_rejects_tool_errors(tmp_pat Result({'message': 'dependency missing'}, is_error=True)]) journal = mod.MCPJournal(session, tmp_path) assert asyncio.run(journal.call('catalog_search', {'query': 'cabinet'}))['id'] == 'chosen' - saved = json.loads(next(tmp_path.glob('*catalog_search.json')).read_text()) + saved = json.loads(next(tmp_path.glob('*catalog_search-response.json')).read_text()) assert saved['response']['structuredContent']['metadata'] == 'x' * 10000 with pytest.raises(mod.WorkflowError, match='asset_prepare'): asyncio.run(journal.call('asset_prepare', {'plan_id': 'pinned'})) - assert len(list(tmp_path.glob('*.json'))) == 2 + assert len(list(tmp_path.glob('*-request.json'))) == 2 + assert len(list(tmp_path.glob('*-response.json'))) == 2 + + +def test_journal_persists_rpc_exception_as_an_incomplete_operation(tmp_path): + mod = module(); journal = mod.MCPJournal(Session([RuntimeError('budget denied')]), tmp_path) + with pytest.raises(mod.WorkflowError, match='simulation_start'): + asyncio.run(journal.call('simulation_start', {'steps': 600})) + request = json.loads(next(tmp_path.glob('*-request.json')).read_text()) + assert request['arguments']['steps'] == 600 + record = json.loads(next(tmp_path.glob('*-response.json')).read_text()) + assert record['exception']['type'] == 'RuntimeError' + assert 'budget denied' in record['exception']['message'] def test_wait_uses_real_job_result_and_never_treats_failed_jobs_as_success(tmp_path): @@ -56,12 +72,67 @@ def test_wait_uses_real_job_result_and_never_treats_failed_jobs_as_success(tmp_p def test_identity_rejects_wrong_wheel_or_development_checkout(tmp_path): mod = module(); plugin = tmp_path/'plugin'; package=plugin/'server/vendor/simscene'; package.mkdir(parents=True) - (package/'__init__.py').write_text('installed') - wheel=tmp_path/'plugin.whl';wheel.write_bytes(b'actual') - identity={'module_path':str(package/'__init__.py'),'build_info':{'wheel_sha256':hashlib.sha256(b'actual').hexdigest(),'source_clean':True}} + contents = {'__init__.py': b'installed', 'mcp_server.py': b'server', 'worker/isaac_run.py': b'worker', + 'recipes/cabinet_mcp_workflow.py': b'workflow'} + wheel=tmp_path/'plugin.whl' + with zipfile.ZipFile(wheel, 'w') as archive: + for name, value in contents.items(): + path=package/name;path.parent.mkdir(parents=True,exist_ok=True);path.write_bytes(value) + archive.writestr('simscene/'+name,value) + resource=plugin/'examples/automatic_cabinet_layout/recipe.json';resource.parent.mkdir(parents=True) + resource.write_text('frozen recipe') + manifest={'schema':'simscene.packaged_resources.v1','files':{'examples/automatic_cabinet_layout/recipe.json':hashlib.sha256(resource.read_bytes()).hexdigest()}} + manifest_path=plugin/'server/resource-manifest.json';manifest_path.write_text(json.dumps(manifest)) + info={'wheel_sha256':hashlib.sha256(wheel.read_bytes()).hexdigest(),'source_clean':True, + 'resource_manifest_sha256':hashlib.sha256(manifest_path.read_bytes()).hexdigest()} + identity={'module_path':str(package/'__init__.py'),'build_info':info} (plugin/'server/build-info.json').write_text(json.dumps(identity['build_info'])) mod.check_identity(identity, plugin, wheel) + (package/'mcp_server.py').write_text('changed server') + with pytest.raises(mod.WorkflowError, match='wheel'): + mod.check_identity(identity,plugin,wheel) + (package/'mcp_server.py').write_bytes(contents['mcp_server.py']) + resource.write_text('changed recipe') + with pytest.raises(mod.WorkflowError, match='resource'): + mod.check_identity(identity,plugin,wheel) + resource.write_text('frozen recipe') with pytest.raises(mod.WorkflowError, match='wheel'): mod.check_identity({**identity, 'build_info':{'wheel_sha256':'0'*64,'source_clean':True}},plugin,wheel) with pytest.raises(mod.WorkflowError, match='installed'): mod.check_identity({**identity, 'module_path':str(tmp_path/'checkout/simscene/__init__.py')},plugin,wheel) + + +def test_configured_mcp_launcher_cannot_be_silently_bypassed(tmp_path, monkeypatch): + mod = module(); plugin = tmp_path/'plugin'; configured=tmp_path/'bounded_proxy.py' + configured.write_text('# bounded MCP launcher\n') + monkeypatch.setenv('SIMSCENE_MCP_LAUNCHER', str(configured)) + assert mod.select_launcher(plugin, None) == configured.resolve() + assert mod.select_launcher(plugin, configured) == configured.resolve() + with pytest.raises(mod.WorkflowError, match='configured MCP launcher'): + mod.select_launcher(plugin, tmp_path/'unbounded.py') + + +def test_default_scene_ids_do_not_collide_between_new_workspaces(): + mod = module() + assert mod.new_scene_id() != mod.new_scene_id() + + +def test_resume_uses_only_the_original_persisted_physics_request(tmp_path): + mod = module(); case=tmp_path/'case.json';case.write_text('{}') + request={'scene_id':'cabinet_123','steps':600,'seed':42,'case_path':str(case), + 'request_id':'cabinet_123-physics'} + (tmp_path/'physics-request.json').write_text(json.dumps(request)) + assert mod.read_recovery_request(tmp_path) == request + request['steps']=601 + (tmp_path/'physics-request.json').write_text(json.dumps(request)) + with pytest.raises(mod.WorkflowError, match='recovery'): + mod.read_recovery_request(tmp_path) + + +def test_run_must_bind_the_saved_scene_and_revision_before_export(tmp_path): + mod = module();run=tmp_path/'run';run.mkdir();scene={'id':'cabinet','revision':2,'objects':{}} + digest=hashlib.sha256(json.dumps(scene,sort_keys=True,separators=(',',':')).encode()).hexdigest() + (run/'run-lock.json').write_text(json.dumps({'source_scene_sha256':digest,'scene_revision':2})) + mod.check_run_scene(scene,run) + with pytest.raises(mod.WorkflowError, match='scene'): + mod.check_run_scene({**scene,'revision':3},run) From b6f37c0df00cecba0cf7b7b6be25bd4905edb911 Mon Sep 17 00:00:00 2001 From: shaoxiang <519517384@qq.com> Date: Wed, 25 Nov 2026 13:24:06 +0800 Subject: [PATCH 14/20] Make cabinet video export a reconnectable job --- docs/validation/integration-release-matrix.md | 8 +- experiments/run_cabinet_mcp.py | 9 +- .../references/integration-workspace.md | 8 +- src/simscene/jobs.py | 4 + src/simscene/mcp_server.py | 8 + src/simscene/recipes/cabinet_mcp_workflow.py | 46 +++- src/simscene/video_export_jobs.py | 235 ++++++++++++++++++ src/simscene/workflows.py | 15 +- tests/agent/test_catalog_mcp_contract.py | 11 +- tests/test_cabinet_mcp_workflow.py | 30 +++ tests/test_video_export_jobs.py | 67 +++++ 11 files changed, 423 insertions(+), 18 deletions(-) create mode 100644 src/simscene/video_export_jobs.py create mode 100644 tests/test_video_export_jobs.py diff --git a/docs/validation/integration-release-matrix.md b/docs/validation/integration-release-matrix.md index 4e97c3d..471a690 100644 --- a/docs/validation/integration-release-matrix.md +++ b/docs/validation/integration-release-matrix.md @@ -27,9 +27,15 @@ runs, not to every object from the named sources: | `integration_workspace` | The pinned USDCraft `ds_R022_02` two-drawer cabinet carried one independent GSO box in the lower drawer. The matched control removed only lower-drawer commands; the upper drawer still moved. Actual contact and relative poses were recorded. Drives were scheduled, and the observed contact data are not a general penetration certification. | | Motion keepouts | The supplied hinge and two-slider profiles cover their inspected native geometry and stated joint ranges. Unknown geometry is not assessed. Layout feasibility remains a geometric precheck, not a physics result. | | ArtVIP and SDK examples | The pinned door and guide-plate pair retain their previous limited checks. They do not qualify arbitrary ArtVIP objects or SDK-generated assets. | -| Client use | A real first Codex QI1 attempt exhausted its token budget before starting physics. A new package, compact workflow and any subsequent qualification must be identified and reported separately. The package version alone does not demonstrate a successful client session. | +| Client use | Both historical QI1 attempts failed to submit. The first reached its token limit before physics. The retry passed physics and began synchronous export, which was interrupted during submission reserve. The durable export path has its own engineering checks and awaits a fresh client qualification. | | Showcase video | An independently captured, source-mapped candidate exists; its visual review is `change_needed`. Video acceptance and physical acceptance are separate. | +The development helper starts video export as a durable job. A client can save +the request ID, wait using `job_status` and reconnect to the same job. The +synchronous `video_export` tool remains available for existing integrations. +Capture and media checks, visual review and on-time submission each require +their own evidence. + The compact installed cabinet helper records real MCP requests and responses; it does not make a visual judgment. For a new job, retain the actual run, checker output, source mapping and attributed review. No cross-task token diff --git a/experiments/run_cabinet_mcp.py b/experiments/run_cabinet_mcp.py index 671d1ef..aa4dd8c 100644 --- a/experiments/run_cabinet_mcp.py +++ b/experiments/run_cabinet_mcp.py @@ -12,14 +12,17 @@ def main(): parser.add_argument('--wheel', required=True, help='wheel matching the installed package build-info') parser.add_argument('--scene-id', help='optional new unique scene ID') parser.add_argument('--mcp-launcher', help='optional Python stdio launcher for this installed MCP server') - parser.add_argument('--resume', action='store_true', help='reconnect using the exact saved physics request') + parser.add_argument('--resume', action='store_true', help='reconnect using saved physics and export requests') + parser.add_argument('--collect-only', action='store_true', help='wait for saved jobs without starting new jobs') args = parser.parse_args() + if args.collect_only and not args.resume: + parser.error('--collect-only requires --resume') plugin = Path(__file__).resolve().parents[1] from simscene.recipes.cabinet_mcp_workflow import new_scene_id, run_installed try: scene_id = args.scene_id if args.resume else (args.scene_id or new_scene_id()) result = asyncio.run(run_installed(plugin, args.wheel, args.output, scene_id, args.mcp_launcher, - resume=args.resume)) + resume=args.resume, collect_only=args.collect_only)) except Exception as error: directory = Path(args.output) if directory.is_dir(): @@ -31,7 +34,7 @@ def main(): except FileExistsError: continue print(json.dumps({'status': 'incomplete', 'error': str(error)[:500], 'directory': args.output, - 'recovery': 'If physics-request.json exists, rerun with --resume and the same output and wheel; the exact request ID is reused.'}, + 'recovery': 'If physics-request.json exists, rerun with --resume and the same output and wheel; existing jobs keep their original request IDs.'}, ensure_ascii=False)) return 2 print(json.dumps(result, ensure_ascii=False)) diff --git a/skills/build-scene/references/integration-workspace.md b/skills/build-scene/references/integration-workspace.md index 0eaf23e..a9439ad 100644 --- a/skills/build-scene/references/integration-workspace.md +++ b/skills/build-scene/references/integration-workspace.md @@ -65,7 +65,13 @@ The command does not supply a visual review or create a final receipt. If it is interrupted after `physics-request.json` is saved, use the same command and add `--resume` with the original output directory and wheel. It reconnects to the saved job or reissues the exact persisted request ID and payload, then verifies -the run before any export. It does not replace an existing partial video. +the run. For video it uses the persisted `video_export_start` request and waits +with `job_status`. With `video-request.json` present, recovery queries the +original export job even if its start reply was lost. A disconnected client or +a wait timeout leaves the job running. During budget reserve, use +`--resume --collect-only` to query saved jobs without issuing new starts. An export receipt records +completion time and pending visual review. Complete the review and submit +separately before the applicable deadline. For shell-capable clients, the installed package also contains the same small helpers as the source tree: `experiments/acquire_recipe_assets.py`, diff --git a/src/simscene/jobs.py b/src/simscene/jobs.py index 3708b64..c1d3629 100644 --- a/src/simscene/jobs.py +++ b/src/simscene/jobs.py @@ -450,6 +450,8 @@ def robot_profile_start(model, asset_path): return {'job_id':job_id} def status(job_id): + from . import video_export_jobs + if video_export_jobs.owns(job_id):return video_export_jobs.status(job_id) from .generation import jobs as generation_jobs if generation_jobs.owns(job_id):return generation_jobs.status(job_id) from .preparation import jobs as preparation_jobs @@ -679,6 +681,8 @@ def video_chunk(job_id, camera, offset=0, length=262144): 'chunk_sha256':hashlib.sha256(data).hexdigest(), 'next_offset':offset+len(data) if offset+len(data) dict: + """Start a durable native video export to an absolute MP4 path. Use job_status to wait or reconnect. An identical request ID replays the original job handle. Review the video separately after completion.""" + from .video_export_jobs import start + return start(segments, destination, request_id, output_resolution, output, allow_upscale, font_file) + @threaded_tool() def video_inspect(path: str, output_dir: str | None = None, representative_count: int = 5, job_id: str | None = None, camera: str | None = None) -> dict: """Probe/decode real video; when job_id/camera supplied, bind to intact source and verify native capture dimensions and physics frame clock. Representative PNG paths are returned for actual visual review.""" diff --git a/src/simscene/recipes/cabinet_mcp_workflow.py b/src/simscene/recipes/cabinet_mcp_workflow.py index 2d3fe9f..adcbe9e 100644 --- a/src/simscene/recipes/cabinet_mcp_workflow.py +++ b/src/simscene/recipes/cabinet_mcp_workflow.py @@ -175,6 +175,31 @@ async def wait_for_job(journal, job_id, receipt, timeout): return actual +async def wait_for_export(journal, root, request, resume, *, collect_only=False): + from ..video_export_jobs import export_job_id + + request_path = root/'video-request.json' + job_id = export_job_id(request['request_id']) + if not request_path.exists(): + if collect_only: + raise WorkflowError('no saved video export request; collection cannot start a new job') + _write(request_path, request) + handle = await journal.call('video_export_start', request) + if handle.get('job_id') != job_id: + raise WorkflowError('export job ID differs from the saved request') + _write(root/'video-job.json', handle) + elif not resume or json.loads(request_path.read_text()) != request: + raise WorkflowError('existing video request differs or recovery was not requested') + # A lost start response still identifies the same durable reservation. + actual = await wait_for_job(journal, job_id, _next_path(root/'video-wait.json'), 1800) + movie = Path(request['destination']) + result = actual.get('result') or {} + if (actual.get('job_id') != job_id or result.get('video') != str(movie) + or result.get('edit_map') != str(movie.with_suffix('.edit.json'))): + raise WorkflowError('export job does not match the requested movie and edit map') + return actual + + def _helper(plugin, directory, name, arguments): command = [sys.executable, str(plugin/'experiments'/name), *map(str, arguments)] env = dict(os.environ, PYTHONPATH=str(plugin/'server/vendor')) @@ -190,8 +215,10 @@ def _helper(plugin, directory, name, arguments): raise WorkflowError(f'{name} did not return JSON; inspect {log}') from error -async def run(session, plugin, wheel, root, scene_id, resume=False): +async def run(session, plugin, wheel, root, scene_id, resume=False, *, collect_only=False): plugin, wheel, root = Path(plugin).resolve(), Path(wheel).resolve(), Path(root).resolve() + if collect_only and not resume: + raise WorkflowError('collection mode requires recovery of a previous invocation') example = plugin/'examples/automatic_cabinet_layout' journal_dir = root/'mcp-calls' if resume and not journal_dir.is_dir(): @@ -285,6 +312,8 @@ async def run(session, plugin, wheel, root, scene_id, resume=False): job_file = root/'physics-job.json' if resume and job_file.exists(): job = json.loads(job_file.read_text()) + elif collect_only: + raise WorkflowError('no saved physics job ID; collection cannot start a new job') else: current_scene = await journal.call('scene_get', {'scene_id': scene_id}) if _scene_hash(current_scene) != _scene_hash(scene): @@ -317,13 +346,10 @@ async def run(session, plugin, wheel, root, scene_id, resume=False): 'start_sim_time_s': start, 'end_sim_time_s': end} for camera,start,end in [('overview',2/60,1.),('detail',1.,6.),('overview',6.,10+2/60)]] movie = root/'technical-1080p.mp4' - if movie.exists(): - if not resume or not movie.with_suffix('.edit.json').is_file(): - raise WorkflowError('existing video is incomplete or unexpected; preserve it and inspect manually') - else: - exported = await journal.call('video_export', {'segments': segments, 'destination': str(movie), - 'output_resolution': [1920,1080]}) - _write(_next_path(root/'video-export.json'), exported) + export_request = {'segments': segments, 'destination': str(movie), + 'request_id': f'{scene_id}-video', 'output_resolution': [1920, 1080]} + exported = await wait_for_export(journal, root, export_request, resume, collect_only=collect_only) + _write(_next_path(root/'video-export.json'), exported) inspected = await journal.call('video_inspect', {'path': str(movie), 'output_dir': str(_next_path(root/'decoded')), 'representative_count': 9}) inspection_path = _next_path(root/'video-inspection.json') @@ -360,7 +386,7 @@ def select_launcher(plugin, requested=None): return Path(requested).expanduser().resolve() if requested else Path(plugin).resolve()/'server/launch.py' -async def run_installed(plugin, wheel, root, scene_id, launcher=None, resume=False): +async def run_installed(plugin, wheel, root, scene_id, launcher=None, resume=False, *, collect_only=False): from mcp import ClientSession, StdioServerParameters from mcp.client.stdio import stdio_client plugin, root = Path(plugin).resolve(), Path(root).resolve() @@ -376,4 +402,4 @@ async def run_installed(plugin, wheel, root, scene_id, launcher=None, resume=Fal async with stdio_client(params, errlog=error_log) as (reader, writer): async with ClientSession(reader, writer, read_timeout_seconds=timedelta(seconds=1900)) as session: await session.initialize() - return await run(session, plugin, wheel, root, scene_id, resume=resume) + return await run(session, plugin, wheel, root, scene_id, resume=resume, collect_only=collect_only) diff --git a/src/simscene/video_export_jobs.py b/src/simscene/video_export_jobs.py new file mode 100644 index 0000000..289fcc6 --- /dev/null +++ b/src/simscene/video_export_jobs.py @@ -0,0 +1,235 @@ +"""Durable, reconnectable exports from recorded SimScene runs.""" +from contextlib import contextmanager +import fcntl +import hashlib +import json +import os +from pathlib import Path +import re +import signal +import subprocess +import sys +import tempfile +import time + +from .preparation.jobs import write +from .request_registry import invoke +from .scene import SceneError, SceneStore, _id + +TERMINAL = {'completed', 'failed', 'cancelled', 'uncertain'} + + +def export_job_id(request_id): + return 'export-' + hashlib.sha256(_id(request_id).encode()).hexdigest() + + +def owns(job_id): + return isinstance(job_id, str) and job_id.startswith('export-') + + +def directory(job_id): + if not isinstance(job_id, str) or not re.fullmatch(r'export-[0-9a-f]{64}', job_id): + raise SceneError('invalid video export job ID') + return SceneStore().path/'video_exports'/job_id + + +@contextmanager +def locked(path, mode=fcntl.LOCK_EX): + with path.open('a') as file: + fcntl.flock(file, mode) + yield + + +def read(path): + return json.loads(path.read_text()) + + +def start(segments, destination, request_id, output_resolution=None, output=None, + allow_upscale=False, font_file=None): + from .jobs import _process_identity + + if not isinstance(segments, list) or not 1 <= len(segments) <= 64: + raise SceneError('export requires 1..64 source segments') + if not Path(destination).expanduser().is_absolute(): + raise SceneError('background export requires an absolute destination') + destination = Path(destination).expanduser().resolve() + if destination.suffix.lower() != '.mp4': + raise SceneError('background export destination must be an MP4 path') + job_id = export_job_id(request_id) + root = directory(job_id) + options = {'segments': segments, 'destination': str(destination), + 'output_resolution': output_resolution, 'output': output, + 'allow_upscale': allow_upscale, 'font_file': font_file} + receipt = {'job_id': job_id, 'type': 'video_export'} + + def recover(identifier, digest): + try: + record = read(root/'job.json') + except (OSError, ValueError): + return None + if record.get('request_id') == identifier and record.get('request_payload_sha256') == digest: + return receipt + return None + + def launch(identifier, digest): + root.mkdir(parents=True, exist_ok=False) + write(root/'request.json', options) + write(root/'job.json', {**receipt, 'state': 'queued', 'request_id': identifier, + 'request_payload_sha256': digest}) + package_root = Path(__file__).resolve().parents[1] + env = dict(os.environ, PYTHONPATH=os.pathsep.join(filter(None, ( + str(package_root), os.environ.get('PYTHONPATH'))))) + with (root/'worker.log').open('ab') as log: + child = subprocess.Popen( + [sys.executable, '-m', 'simscene.video_export_jobs', str(root)], + env=env, stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT, + start_new_session=True, + ) + write(root/'launch.json', {'pid': child.pid, 'identity': _process_identity(child.pid)}) + return receipt + + home = root.parents[1] + return invoke(home, request_id, {'operation': 'video_export', **options}, launch, recover) + + +def status(job_id): + from .jobs import _process_identity + + root = directory(job_id) + try: + record = read(root/'job.json') + except (OSError, ValueError) as error: + raise SceneError('video export job not found or record unreadable') from error + if record.get('job_id') != job_id: + raise SceneError('invalid video export job record') + # Wait for the reservation and launcher metadata to finish publishing. + with locked(root.parents[1]/'job-requests'/(_id(record['request_id'])+'.lock'), fcntl.LOCK_SH): + record = read(root/'job.json') + if record['state'] not in TERMINAL: + try: + launch = read(root/'launch.json') + alive = launch['identity'] and _process_identity(launch['pid']) == launch['identity'] + except (OSError, ValueError, KeyError): + alive = False + if not alive: + record = read(root/'job.json') + if record['state'] not in TERMINAL: + record.update(state='uncertain', error='Export worker exited without a durable completion record.') + response = {key: record[key] for key in ('job_id', 'type', 'state', 'result', 'error', 'finished_unix_ns') + if key in record} + response.update(record_path=str(root/'job.json'), log=str(root/'worker.log')) + if (root/'cancel-request.json').is_file(): + response['cancel_requested'] = True + if record['state'] == 'completed': + response['completion_confirmed'] = True + return response + + +def cancel(job_id): + from .jobs import _process_identity + + root = directory(job_id) + status(job_id) + with locked(root/'finish.lock'): + record = read(root/'job.json') + if record['state'] not in TERMINAL: + write(root/'cancel-request.json', {'requested_unix_ns': time.time_ns()}) + launch_path = root/'launch.json' + if (record['state'] == 'running' and launch_path.is_file() + and hasattr(os, 'pidfd_open') and hasattr(signal, 'pidfd_send_signal')): + launch = read(launch_path) + try: + descriptor = os.pidfd_open(launch['pid']) + except ProcessLookupError: + pass + else: + try: + if launch['identity'] and _process_identity(launch['pid']) == launch['identity']: + signal.pidfd_send_signal(descriptor, signal.SIGTERM) + except ProcessLookupError: + pass + finally: + os.close(descriptor) + return status(job_id) + + +class Cancelled(Exception): + pass + + +def _interrupt(*_): + raise Cancelled() + + +def _publish(manifest, staged_movie, destination): + """Publish the mapping last and roll back links created by this attempt.""" + staged_manifest = Path(manifest.pop('manifest_path')) + manifest['path'] = str(destination) + files = [(staged_movie, destination)] + for segment in manifest['segments']: + image = Path(segment['composed_keyframe']) + final_image = destination.parent/image.name + files.append((image, final_image)) + segment['composed_keyframe'] = str(final_image) + write(staged_manifest, manifest) + final_manifest = destination.with_suffix('.edit.json') + files.append((staged_manifest, final_manifest)) + linked = [] + try: + for original, final in files: + with original.open('rb') as stream: + os.fsync(stream.fileno()) + os.link(original, final) + linked.append((original, final)) + descriptor = os.open(destination.parent, os.O_RDONLY | os.O_DIRECTORY) + try: + os.fsync(descriptor) + finally: + os.close(descriptor) + except BaseException: + for original, final in reversed(linked): + if final.exists() and original.samefile(final): + final.unlink() + raise + return {'video': str(destination), 'edit_map': str(final_manifest), + 'video_sha256': manifest['sha256'], 'edit_map_sha256': hashlib.sha256(staged_manifest.read_bytes()).hexdigest(), + 'visual_review': 'pending'} + + +def worker(root): + from .video_tools import export + + record = read(root/'job.json') + try: + signal.signal(signal.SIGTERM, _interrupt) + if (root/'cancel-request.json').is_file(): + raise Cancelled() + options = read(root/'request.json') + destination = Path(options.pop('destination')) + destination.parent.mkdir(parents=True, exist_ok=True) + if destination.exists() or destination.with_suffix('.edit.json').exists(): + raise SceneError('video or edit map destination exists') + with locked(root/'finish.lock'): + if (root/'cancel-request.json').is_file(): + raise Cancelled() + write(root/'job.json', dict(record, state='running')) + with tempfile.TemporaryDirectory(prefix='.simscene-video-export-', dir=destination.parent) as temp: + staged_movie = Path(temp)/destination.name + manifest = export(destination=staged_movie, **options) + with locked(root/'finish.lock'): + if (root/'cancel-request.json').is_file(): + raise Cancelled() + result = _publish(manifest, staged_movie, destination) + write(root/'job.json', dict(record, state='completed', result=result, finished_unix_ns=time.time_ns())) + return + except Cancelled: + terminal = {'state': 'cancelled'} + except Exception as error: + if isinstance(error, subprocess.CalledProcessError) and isinstance(error.stderr, bytes): + print(error.stderr[-4096:].decode(errors='replace'), file=sys.stderr) + terminal = {'state': 'failed', 'error': f'{type(error).__name__}: {error}'[:1500]} + write(root/'job.json', {**record, **terminal, 'finished_unix_ns': time.time_ns()}) + + +if __name__ == '__main__': + worker(Path(sys.argv[1])) diff --git a/src/simscene/workflows.py b/src/simscene/workflows.py index 67bf018..5639ee9 100644 --- a/src/simscene/workflows.py +++ b/src/simscene/workflows.py @@ -16,14 +16,19 @@ def wait_job(job_id, receipt_path, timeout_s=1800, poll_interval_s=1): raise ValueError('preserve an existing job receipt') output.parent.mkdir(parents=True, exist_ok=True) started = time.monotonic() + cutoff_unix_ns = time.time_ns() + round(timeout_s * 1e9) started_at = datetime.now(timezone.utc).isoformat() while True: state = status(job_id) + finished = state.get('finished_unix_ns') + if state.get('type') == 'video_export' and type(finished) is int and finished > cutoff_unix_ns: + raise TimeoutError('wait budget exhausted; original job is preserved, not restarted or cancelled') if state['state'] not in ('queued', 'running', 'paused', 'stalled', 'acquiring', 'converting', 'inspecting', 'generating'): break - if time.monotonic()-started >= timeout_s: + remaining = timeout_s - (time.monotonic() - started) + if remaining <= 0: raise TimeoutError('wait budget exhausted; original job is preserved, not restarted or cancelled') - time.sleep(poll_interval_s) + time.sleep(min(poll_interval_s, remaining)) observed_exit = type(state.get('exit_code')) is int and state.get('exit_code_inferred') is False result = state.get('result') or {} receipt = {'schema': 'simscene.job_wait_receipt.v1', 'job_id': job_id, @@ -44,6 +49,12 @@ def wait_job(job_id, receipt_path, timeout_s=1800, poll_interval_s=1): receipt.update(job_type='asset_generation',completion_confirmed=state.get('completion_confirmed') is True, generation_record=state.get('record_path'),generated_source=result.get('asset_ref'), scope='Durable generated-source completion; preparation and physical verification are separate required steps.') + if state.get('type')=='video_export': + receipt.update(job_type='video_export', completion_confirmed=state.get('completion_confirmed') is True, + export_record=state.get('record_path'), video=result.get('video'), edit_map=result.get('edit_map'), + video_sha256=result.get('video_sha256'), edit_map_sha256=result.get('edit_map_sha256'), + visual_review=result.get('visual_review'), finished_unix_ns=state.get('finished_unix_ns'), + scope='Durable export status. Media verification, visual review and submission are separate steps.') with output.open('x') as f: json.dump(receipt, f, ensure_ascii=False, indent=2, allow_nan=False); f.write('\n') summary={k: receipt[k] for k in ('job_id', 'run_id', 'state', 'exit_code', 'exit_code_observed', 'physics_accepted')} diff --git a/tests/agent/test_catalog_mcp_contract.py b/tests/agent/test_catalog_mcp_contract.py index 18d5faa..52dd761 100644 --- a/tests/agent/test_catalog_mcp_contract.py +++ b/tests/agent/test_catalog_mcp_contract.py @@ -27,7 +27,7 @@ run_observe run_contacts run_verify_lock run_verify run_verify_passive_suite run_verify_evidence run_video_chunk scene_observe job_cancel simulation_pause simulation_resume'''.split()) -NEW_TOOLS = frozenset({'catalog_search', 'asset_plan', 'asset_prepare', 'catalog_discover', 'scene_compile_recipe', 'asset_generate', 'scene_plan_layout'}) +NEW_TOOLS = frozenset({'catalog_search', 'asset_plan', 'asset_prepare', 'catalog_discover', 'scene_compile_recipe', 'asset_generate', 'scene_plan_layout', 'video_export_start'}) def nullable(kind, title): @@ -41,6 +41,15 @@ def schema(name, properties, required): return {'properties': properties, 'required': required, 'title': name + 'Arguments', 'type': 'object'} NEW_SCHEMAS = { + 'video_export_start': schema('video_export_start', { + 'segments': {'items': {'additionalProperties': True, 'type': 'object'}, 'title': 'Segments', 'type': 'array'}, + 'destination': {'title': 'Destination', 'type': 'string'}, + 'request_id': {'title': 'Request Id', 'type': 'string'}, + 'output_resolution': {'anyOf': [{'items': {'type': 'integer'}, 'type': 'array'}, {'type': 'null'}], + 'default': None, 'title': 'Output Resolution'}, + 'output': nullable('object', 'Output'), + 'allow_upscale': {'default': False, 'title': 'Allow Upscale', 'type': 'boolean'}, + 'font_file': nullable('string', 'Font File')}, ['segments', 'destination', 'request_id']), 'asset_generate': schema('asset_generate', { 'recipe_id': {'title': 'Recipe Id', 'type': 'string'}, 'parameters': {'additionalProperties': True, 'title': 'Parameters', 'type': 'object'}, diff --git a/tests/test_cabinet_mcp_workflow.py b/tests/test_cabinet_mcp_workflow.py index 3920d14..9a9ed44 100644 --- a/tests/test_cabinet_mcp_workflow.py +++ b/tests/test_cabinet_mcp_workflow.py @@ -136,3 +136,33 @@ def test_run_must_bind_the_saved_scene_and_revision_before_export(tmp_path): mod.check_run_scene(scene,run) with pytest.raises(mod.WorkflowError, match='scene'): mod.check_run_scene({**scene,'revision':3},run) + + +def test_video_recovery_reuses_job_status_after_losing_the_start_response(tmp_path): + mod = module() + from simscene.video_export_jobs import export_job_id + + movie = tmp_path/'technical.mp4' + edit = movie.with_suffix('.edit.json') + request = {'destination': str(movie), 'request_id': 'cabinet-video', + 'segments': [{'camera': 'overview'}], 'output_resolution': [1920, 1080]} + mod._write(tmp_path/'video-request.json', request) + expected_job = export_job_id(request['request_id']) + lost = Session([Result({'state': 'completed'}), + Result({'job_id': expected_job, 'state': 'completed', + 'result': {'video': str(movie), 'edit_map': str(edit)}})]) + journal = mod.MCPJournal(lost, tmp_path) + assert asyncio.run(mod.wait_for_export(journal, tmp_path, request, resume=True))['job_id'] == expected_job + assert [name for name, _ in lost.calls] == ['job_status', 'job_status'] + assert {args['job_id'] for _, args in lost.calls} == {expected_job} + + +def test_collection_does_not_start_an_export_without_a_saved_request(tmp_path): + mod = module() + session = Session([]) + journal = mod.MCPJournal(session, tmp_path) + request = {'destination': str(tmp_path/'technical.mp4'), 'request_id': 'cabinet-video'} + with pytest.raises(mod.WorkflowError, match='no saved video export'): + asyncio.run(mod.wait_for_export(journal, tmp_path, request, resume=True, collect_only=True)) + assert session.calls == [] + assert not (tmp_path/'video-request.json').exists() diff --git a/tests/test_video_export_jobs.py b/tests/test_video_export_jobs.py new file mode 100644 index 0000000..b9e8741 --- /dev/null +++ b/tests/test_video_export_jobs.py @@ -0,0 +1,67 @@ +"""Export reservations must survive losing the initiating client.""" +import hashlib +import json +import subprocess +import sys +import time + +import pytest + +from simscene import jobs +from simscene.scene import SceneError + + +def test_failed_export_reuses_the_original_job_after_a_lost_response(tmp_path, monkeypatch): + from simscene import mcp_server + monkeypatch.setenv('SIMSCENE_HOME', str(tmp_path/'state')) + destination = tmp_path/'movie.mp4' + segments = [{'run_directory': str(tmp_path/'missing-run'), 'camera': 'overview'}] + request_id = 'cabinet-export' + handle = mcp_server.video_export_start(segments, str(destination), request_id) + job_id = 'export-' + hashlib.sha256(request_id.encode()).hexdigest() + + # The tool response was lost. Read the stable ID via another interpreter. + status = json.loads(subprocess.check_output( + [sys.executable, '-c', f'import json; from simscene.jobs import status; print(json.dumps(status({job_id!r})))'], + text=True, + )) + assert status['job_id'] == job_id == handle['job_id'] + again = mcp_server.video_export_start(segments, str(destination), request_id) + assert again['job_id'] == job_id and again['replayed'] is True + with pytest.raises(SceneError, match='different job parameters'): + mcp_server.video_export_start(segments, str(tmp_path/'other.mp4'), request_id) + + deadline = time.monotonic()+12 + while time.monotonic() < deadline: + status = jobs.status(job_id) + if status['state'] not in {'queued', 'running'}: + break + time.sleep(.05) + assert status['state'] == 'failed' + assert 'run-lock.json' in status['error'] + assert not destination.exists() + assert not destination.with_suffix('.edit.json').exists() + assert len(list((tmp_path/'state'/'video_exports').iterdir())) == 1 + + +def test_late_export_is_recoverable_but_does_not_produce_an_on_time_wait_receipt(tmp_path, monkeypatch): + from simscene import workflows + + actual_clock = time.time_ns() + finished = actual_clock + 2_000_000_000 + state = {'job_id': 'export-test', 'type': 'video_export', 'state': 'completed', + 'finished_unix_ns': finished, 'completion_confirmed': True, + 'result': {'visual_review': 'pending'}} + monkeypatch.setattr(jobs, 'status', lambda _: state) + original = tmp_path/'original.json' + monkeypatch.setattr(workflows.time, 'time_ns', lambda: actual_clock) + with pytest.raises(TimeoutError, match='original job is preserved'): + workflows.wait_job('export-test', original, timeout_s=1) + assert not original.exists() + late = tmp_path/'recovered.json' + monkeypatch.setattr(workflows.time, 'time_ns', lambda: finished) + assert workflows.wait_job('export-test', late, timeout_s=1)['completion_confirmed'] is True + evidence = json.loads(late.read_text()) + assert evidence['finished_unix_ns'] == finished + assert evidence['visual_review'] == 'pending' + assert evidence['physics_accepted'] is False From 3907351bade41462a4be12105c70ce40ce1d06ab Mon Sep 17 00:00:00 2001 From: shaoxiang <519517384@qq.com> Date: Wed, 25 Nov 2026 14:29:31 +0800 Subject: [PATCH 15/20] Ship an installed one-object first delivery example --- README.md | 3 + ...53\351\200\237\345\274\200\345\247\213.md" | 2 + examples/first_delivery/README.md | 62 ++++++ examples/first_delivery/assets.lock.json | 144 ++++++++++++++ examples/first_delivery/case.json | 34 ++++ examples/first_delivery/recipe.json | 182 ++++++++++++++++++ experiments/run_first_delivery.py | 41 ++++ plugins/build.py | 3 +- skills/build-scene/SKILL.md | 2 + src/simscene/recipes/cabinet_mcp_workflow.py | 49 ++--- src/simscene/recipes/data/fixed-examples.json | 15 ++ src/simscene/recipes/first_delivery.py | 144 ++++++++++++++ src/simscene/recipes/integration_delivery.py | 18 +- tests/agent/test_package.py | 7 +- tests/test_integration_example_registry.py | 24 ++- 15 files changed, 697 insertions(+), 33 deletions(-) create mode 100644 examples/first_delivery/README.md create mode 100644 examples/first_delivery/assets.lock.json create mode 100644 examples/first_delivery/case.json create mode 100644 examples/first_delivery/recipe.json create mode 100644 experiments/run_first_delivery.py create mode 100644 src/simscene/recipes/first_delivery.py diff --git a/README.md b/README.md index e3a6c89..1253744 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,9 @@ see the [results and limitations](docs/validation/catalog-efficiency.md). ## Get started +**Development package (dev2):** try the [one-object first delivery](examples/first_delivery/README.md) +for a checked drop onto a SimScene worktop and a four-second native video. + **Recommended first run:** pin [v0.2.0-dev.1](docs/releases/v0.2.0-dev.1.md#安装与第一次尝试) → configure the tested runtime → select a small ABO/GSO object → check a single object's fall, contact and settling → expand to multiple instances → record video. diff --git "a/docs/\345\277\253\351\200\237\345\274\200\345\247\213.md" "b/docs/\345\277\253\351\200\237\345\274\200\345\247\213.md" index ffb3b73..a611ded 100644 --- "a/docs/\345\277\253\351\200\237\345\274\200\345\247\213.md" +++ "b/docs/\345\277\253\351\200\237\345\274\200\345\247\213.md" @@ -1,5 +1,7 @@ # SimScene 快速开始 +本地开发候选(dev2)提供[单物体首次交付](../examples/first_delivery/README.md),从已安装插件完成选定模型获取、落体检查和原生视频导出。 + SimScene 将在线资产发现、可编辑 USD 场景、Isaac Sim 运行和影片制作接入智能体。 先在仿真主机上完成安装,再按需选择资产;不需要预下载完整资产库。 diff --git a/examples/first_delivery/README.md b/examples/first_delivery/README.md new file mode 100644 index 0000000..e4da532 --- /dev/null +++ b/examples/first_delivery/README.md @@ -0,0 +1,62 @@ +# First delivery · one gravity drop + +Use an installed development package that includes this example. The fixed input +is one GSO scan of a fondant box. The scene uses editable SimScene boxes for its +worktop, stand and floor. The model is fetched on demand with its source notice. +The prepared 120 mm size and 0.12 kg mass are experimental parameters. + +## Run on the simulation host + +Use a Python with USD bindings, the tested Isaac Sim 6.2.0-rc.14 runtime, +Node.js 22.23.2 with npm, and FFmpeg with libx264 and zscale. Supply paths to an +installed portable plugin and the matching wheel. Use a directory you own for +this example's state and cache. + +~~~sh +export PLUGIN=/absolute/path/to/installed/simscene +export WHEEL=/absolute/path/to/rosclaw_simscene-0.2.0.dev2-py3-none-any.whl +export SIMSCENE_ISAAC_PYTHON=/absolute/path/to/isaac-sim/python.sh +export WORK="$PWD/first-delivery-local" +export SIMSCENE_HOME="$WORK/state" +export SIMSCENE_CACHE="$WORK/source-cache" +export SIMSCENE_V2_CONFIG="$WORK/v2.json" +export SIMSCENE_GLTF_TRANSFORM_PREFIX="$WORK/decoder" +export PYTHONPATH="$PLUGIN/server/vendor" + +mkdir "$WORK" +python3 -m simscene.cli asset setup-decoder --output "$SIMSCENE_GLTF_TRANSFORM_PREFIX" +python3 -m simscene.cli asset probe +python3 "$PLUGIN/experiments/run_first_delivery.py" --wheel "$WHEEL" --output "$WORK/output" +~~~ + +Setup and probing are reusable within this environment. Repeat the last command +with a new output directory for another run. An interrupted invocation with a +saved physics request can use the same output directory, wheel and flags plus +`--resume`. Add `--collect-only` during budget reserve to query and wait on +existing jobs. Preparation that was interrupted before the saved physics +request needs a new output directory. Missing runtime details are recorded with +the failing MCP request in `mcp-calls/`. + +## Read and review the results + +- `scene.json` and `case.json` contain the applied scene and frozen case. +- `physical-check.json` checks measurable drop, direct worktop contact, full + bounds containment and two seconds of settling, with input and output hashes. +- `first-delivery.mp4`, its `.edit.json` and `video-inspection.json` contain the + native 4-second, 1080p30 clip, original run mapping and decoded samples. +- `delivery.json` records engineering checks and leaves visual review pending. + +Play the complete MP4 and check that the falling box, contact and settled result +are visible. Save a JSON review with `reviewer`, `decision` (`accept` or +`change_needed`), the `video_sha256` in `delivery.json` and +`reviewed_windows`. Cover playback seconds 0–0.5 and 2–4 with entries containing +`start_s`, `end_s` and a concrete `observation`. You can use a single 0–4 +entry after reviewing the whole clip. + +~~~sh +python3 "$PLUGIN/experiments/run_first_delivery.py" --output "$WORK/output" --review "$WORK/review.json" +~~~ + +The reviewed receipt binds the declaration to the checked movie and can reach +`ready_for_submission`. The eventual submission belongs to the client or host +that requested the work. This example verifies a fixed asset and configuration. diff --git a/examples/first_delivery/assets.lock.json b/examples/first_delivery/assets.lock.json new file mode 100644 index 0000000..9dd4f80 --- /dev/null +++ b/examples/first_delivery/assets.lock.json @@ -0,0 +1,144 @@ +{ + "schema": "simscene.selected_assets.v2", + "assets": { + "box": { + "provider": "prepared", + "source_ref": { + "source_id": "gso-glb", + "asset_id": "ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box", + "revision": "75e8895e4f4e854cddd7009a7e60f86812041012", + "variant_id": null + }, + "profile_id": "rigid_prop_v1", + "profile_version": 1, + "parameters": { + "ccd": true, + "collision_method": "convex_hull", + "dynamic_friction": 0.5, + "mass_kg": 0.12, + "mass_note": "Experimental120mm scaled scanned box/.12kg assumption; not manufacturer values.", + "proxy_tolerance_m": 0.002, + "restitution": 0.05, + "scale_mode": "fit_longest", + "source_physics_policy": "reject_if_physics", + "static_friction": 0.6, + "target_longest_extent_m": 0.12 + }, + "target": { + "engine": "physx", + "isaac_version": "6.2.0-rc.14+release.52805.02189a84.gl", + "platform": "linux-x86_64", + "usd_version": "0.25.11" + }, + "toolchain": { + "backend": "omni.kit.asset_converter", + "canonicalization": "explicit_Rx90_once", + "codec_policy_version": 2, + "predecoder": { + "backend": "gltf-transform-meshopt", + "core_version": "4.5.1", + "extensions_version": "4.5.1", + "max_decoded_bytes": 268435456, + "meshoptimizer_version": "1.3.0", + "node_modules_sha256": "3bfdef144f9a32d73ab5147f5be0dcd2e9e731a28b56f9ae7e521a46e590c302", + "node_version": "v22.23.2", + "package_lock_sha256": "bac0ab1332c821de5680b887f828014d86a71eb930b14d91fd938e36c45bdff0", + "script_sha256": "06af0eaf70d3cfda095cadef3de0afde388d1c9b4ba1e930d408e95c002602e4" + }, + "usd_version": "0.25.11", + "version": "6.1.0" + }, + "source_sha256": "5454424606ed780b806c99a5a3ffc0f4b0b9ade2fc9afa9c63fbf932ea187949", + "source_closure_sha256": "c2800268fbde5b01d93558746942ffc8446780f390573605f2979056c6223975", + "source_files": [ + { + "path": "README.md", + "size_bytes": 11624, + "sha256": "a283318ac5c8990a1fb49ddd5b2f2f91aaaddece678e3a97941e90b29deb8ad9" + }, + { + "path": "objects/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box.glb", + "size_bytes": 263232, + "sha256": "5454424606ed780b806c99a5a3ffc0f4b0b9ade2fc9afa9c63fbf932ea187949" + } + ], + "previous_preparation": { + "prepared_id": "dd50547b39fed14df8ddecbe15ee71952928b21b43fb302cc105aece9e66947b", + "manifest_sha256": "52de9211b27fc73eaaadedd4725f1122224c0f31d5ab07a95baa340902244990", + "source_manifest_sha256": "bd310cb197a405b1671b990a1daeb72be6062d4419fadf252dd88ed8f23e6c67", + "scope": "informational; rebuild may change absolute provenance; no physics verdict reused" + }, + "source_record": { + "ref": { + "asset_id": "ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box", + "revision": "75e8895e4f4e854cddd7009a7e60f86812041012", + "source_id": "gso-glb", + "variant_id": null + }, + "title": "Ready-to-Use Rolled Fondant, Pure White - 24 oz box", + "format": "glb", + "entry_path": "objects/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box.glb", + "license": { + "basis": "object_metadata_row", + "evidence": "declared", + "license": "CC-BY-4.0", + "notices_required": true, + "status": "known" + }, + "availability": { + "acquisition": { + "additional_paths": [ + "README.md" + ], + "kind": "hf_single_glb", + "path": "objects/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box.glb", + "repository": "codepawl/scanned-objects-glb", + "revision": "75e8895e4f4e854cddd7009a7e60f86812041012" + }, + "estimated_download_bytes": 263232, + "files_complete": null, + "granularity": "single_file", + "status": "declared" + }, + "provenance": { + "mass_estimate_note": "metadata estimates are not measured/manufacturer dynamics", + "metadata_revision": "75e8895e4f4e854cddd7009a7e60f86812041012", + "original_metadata": { + "brand": "Ready-to-Use", + "category": "food and drink", + "category_source": "name rule", + "file": "objects/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box.glb", + "file_name": "engine/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box.glb", + "id": "ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box", + "license": "CC-BY-4.0", + "mass_estimate_kg": 0.2866, + "mpn": null, + "name": "Ready-to-Use Rolled Fondant, Pure White - 24 oz box", + "pack_bytes": 263232, + "pack_texture_px": 2048, + "size_metres": [ + 0.1217, + 0.1687, + 0.0491 + ], + "sku": "00070896423016", + "source": "https://fuel.gazebosim.org/1.0/GoogleResearch/models/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box", + "source_bytes": 13264125, + "source_categories": [ + "Consumer Goods" + ], + "source_texture_px": 4096, + "thumb": "thumbs/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box.webp", + "triangles": 1744, + "vertices": 949 + }, + "relationship": "community_conversion", + "repository": "codepawl/scanned-objects-glb", + "selected_variant": "standard_objects_glb", + "upstream_source": "https://fuel.gazebosim.org/1.0/GoogleResearch/models/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box", + "viewer_variant_not_selected": "engine/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box/ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box.glb" + } + } + } + } +} diff --git a/examples/first_delivery/case.json b/examples/first_delivery/case.json new file mode 100644 index 0000000..df162c1 --- /dev/null +++ b/examples/first_delivery/case.json @@ -0,0 +1,34 @@ +{ + "schema": "simscene.rigid_asset_smoke.v1", + "schema_version": 1, + "source_ref": "${box.source_ref}", + "prepared_manifest_sha256": "${box.manifest_sha256}", + "objects": { + "box": { + "motion_body": "/World/box/Asset/Body", + "contact_bodies": [ + "/World/box/Asset/Body" + ], + "visual_roots": [ + "/World/box/Asset/Body/Visual" + ], + "support_actors": [ + "/World/table" + ], + "initial_height_m": 0.97, + "min_drop_m": 0.18, + "target_bounds": { + "min": [ + -0.27, + -0.21, + 0.704 + ], + "max": [ + 0.27, + 0.21, + 0.83 + ] + } + } + } +} diff --git a/examples/first_delivery/recipe.json b/examples/first_delivery/recipe.json new file mode 100644 index 0000000..9d1aa35 --- /dev/null +++ b/examples/first_delivery/recipe.json @@ -0,0 +1,182 @@ +{ + "schema": "simscene.scene_recipe.v2", + "description": "One prepared GSO scan falls under gravity onto an editable SimScene box worktop.", + "operations": [ + { + "op": "add", + "id": "floor", + "object": { + "kind": "box", + "size": [ + 3.0, + 3.0, + 0.1 + ], + "position": [ + 0, + 0, + -0.05 + ], + "color": [ + 0.12, + 0.16, + 0.2 + ], + "collision": true + } + }, + { + "op": "add", + "id": "table", + "object": { + "kind": "box", + "size": [ + 0.66, + 0.5, + 0.07 + ], + "position": [ + 0, + 0, + 0.685 + ], + "color": [ + 0.34, + 0.49, + 0.58 + ], + "collision": true + } + }, + { + "op": "add", + "id": "pedestal", + "object": { + "kind": "box", + "size": [ + 0.36, + 0.31, + 0.65 + ], + "position": [ + 0, + 0, + 0.325 + ], + "color": [ + 0.21, + 0.27, + 0.32 + ] + } + }, + { + "op": "add", + "id": "box", + "object": { + "kind": "asset", + "dynamic": true, + "position": [ + 0, + 0, + 0.97 + ], + "asset_role": "box", + "orientation_wxyz": [ + 0.7071067811865476, + 0.7071067811865476, + 0, + 0 + ] + } + }, + { + "op": "add", + "id": "sky", + "object": { + "kind": "light", + "light": { + "type": "dome" + }, + "intensity": 420.0 + } + }, + { + "op": "add", + "id": "key", + "object": { + "kind": "light", + "light": { + "type": "sphere", + "radius_m": 0.32 + }, + "intensity": 850.0, + "position": [ + -0.3, + -0.7, + 2.2 + ] + } + }, + { + "op": "add", + "id": "drop", + "object": { + "kind": "camera", + "position": [ + 0.68, + -0.92, + 1.16 + ], + "orientation_wxyz": [ + 0.7651138463631999, + 0.5546901069203404, + 0.19192608411662257, + 0.2647339525328595 + ], + "record_fps": 30, + "camera": { + "resolution": [ + 1920, + 1080 + ], + "focal_length_mm": 52.0, + "horizontal_aperture_mm": 36.0, + "focus_distance_m": 1.2, + "clipping_range_m": [ + 0.01, + 20.0 + ] + } + } + }, + { + "op": "set_presentation", + "presentation": { + "profile": "technical_showcase_1080p", + "capture": { + "resolution": [ + 1920, + 1080 + ], + "fps": 30, + "renderer": "RealTimePathTracing", + "anti_aliasing": "dlaa", + "depth_of_field": false, + "motion_blur": false, + "exposure_mode": "manual", + "exposure_ev": 0 + }, + "budget": { + "max_cameras": 1, + "max_recording_bytes": 536870912, + "min_free_bytes": 1073741824 + }, + "diagnostics": { + "keyframe_interval_s": 1, + "png_seconds": 0.1 + } + } + } + ] +} diff --git a/experiments/run_first_delivery.py b/experiments/run_first_delivery.py new file mode 100644 index 0000000..12936e6 --- /dev/null +++ b/experiments/run_first_delivery.py @@ -0,0 +1,41 @@ +"""Build, verify and record the installed first delivery example.""" +import argparse +import asyncio +import json +from pathlib import Path + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--output', required=True, help='new output directory, or original directory for recovery or review') + parser.add_argument('--wheel', help='wheel matching the installed package') + parser.add_argument('--resume', action='store_true', help='recover the same scene and job requests') + parser.add_argument('--collect-only', action='store_true', help='recover existing jobs without new starts') + parser.add_argument('--review', help='record an attributed review of a verified delivery') + args = parser.parse_args() + if args.collect_only and not args.resume: + parser.error('--collect-only requires --resume') + if args.review and args.resume: + parser.error('--review records the review of an already completed delivery') + if not args.review and not args.wheel: + parser.error('--wheel is required to start or recover a run') + plugin = Path(__file__).resolve().parents[1] + from simscene.recipes.cabinet_mcp_workflow import new_scene_id, run_installed + from simscene.recipes.first_delivery import record_review, run + try: + if args.review: + result = record_review(args.output, args.review) + else: + scene_id = new_scene_id().replace('compact_cabinet_', 'first_delivery_', 1) + result = asyncio.run(run_installed(plugin, args.wheel, args.output, scene_id, + resume=args.resume, collect_only=args.collect_only, workflow=run)) + except Exception as error: + print(json.dumps({'status': 'incomplete', 'directory': args.output, 'error': str(error)[:900]}, + ensure_ascii=False)) + return 2 + print(json.dumps(result, indent=2, ensure_ascii=False)) + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/plugins/build.py b/plugins/build.py index 0d7ba8f..f0cd41b 100644 --- a/plugins/build.py +++ b/plugins/build.py @@ -90,6 +90,7 @@ def verify_source_snapshot(root, snapshot, commit, paths=None): small pinned example recipes are included without model payloads. ''' EXAMPLE_DATA={ + 'first_delivery':('README.md', 'assets.lock.json', 'case.json', 'recipe.json'), 'automatic_cabinet_layout':('assets.lock.json','case.json','recipe.json','supplemental-checks.json','check.py'), 'artvip_door':('assets.lock.json','case.json','recipe.json','supplement.json','check.py'), 'usdcraft_two_drawer':('assets.lock.json','case.json','recipe.json','recipe-control.json'), @@ -97,7 +98,7 @@ def verify_source_snapshot(root, snapshot, commit, paths=None): 'usdcraft_sdk_guide':('assets.lock.json','case.json','recipe-short.json','recipe-long.json','check_pair.py'), } EXAMPLE_HELPERS=('acquire_recipe_assets.py','apply_scene_recipe.py','freeze_recipe_case.py', - 'check_motion_clearance.py','assemble_integration_receipt.py','run_cabinet_mcp.py') + 'check_motion_clearance.py','assemble_integration_receipt.py','run_cabinet_mcp.py','run_first_delivery.py') def write(path, value): path.parent.mkdir(parents=True,exist_ok=True) path.write_text(json.dumps(value,indent=2)+'\n') diff --git a/skills/build-scene/SKILL.md b/skills/build-scene/SKILL.md index 0db50be..0972835 100644 --- a/skills/build-scene/SKILL.md +++ b/skills/build-scene/SKILL.md @@ -3,6 +3,8 @@ name: build-scene description: Discover online simulation assets, compose editable scenes with measured support relationships, run Isaac Sim and improve the result from camera and physical observations. --- +For a first verified delivery, use the installed [one-object example](../../examples/first_delivery/README.md). + Choose reproduction, modification or original construction first. Reproduce a locked recipe directly; test changed interfaces locally; build new mechanisms on a small bench before assembling the full scene. For the installed fixed diff --git a/src/simscene/recipes/cabinet_mcp_workflow.py b/src/simscene/recipes/cabinet_mcp_workflow.py index adcbe9e..9a68a52 100644 --- a/src/simscene/recipes/cabinet_mcp_workflow.py +++ b/src/simscene/recipes/cabinet_mcp_workflow.py @@ -175,6 +175,29 @@ async def wait_for_job(journal, job_id, receipt, timeout): return actual +async def prepare_fixed_asset(journal, root, scene_id, role, query, selected, budget_bytes): + found = await journal.call('catalog_search', {'query': query, + 'filters': {'source_ids': [selected['source_ref']['source_id']]}, 'limit': 20}) + budgets = found.get('budgets', {}) + if budgets.get('model_bytes') != 0 or budgets.get('preview_bytes') != 0: + raise WorkflowError(f'{role} metadata search downloaded a model or preview, or did not report bytes') + item = next((x for x in found.get('items', []) if x.get('ref') == selected['source_ref']), None) + if not item: + raise WorkflowError(f'locked {role} was not returned by the catalog') + plan = await journal.call('asset_plan', {'asset_ref': item['ref'], 'profile_id': selected['profile_id'], + 'parameters': selected['parameters'], 'budget_bytes': budget_bytes}) + if not plan.get('ready_to_fetch'): + reasons = json.dumps(plan.get('blocking_reasons', []), ensure_ascii=False)[:650] + raise WorkflowError(f'locked {role} asset plan is blocked: {reasons}') + job = await journal.call('asset_prepare', {'plan_id': plan['plan_id'], + 'request_id': f'{scene_id}-prepare-{role}'}) + _write(root/f'prepare-{role}-job.json', job) + done = await wait_for_job(journal, job['job_id'], root/f'prepare-{role}-wait.json', 300) + prepared = done['result'] + return {'asset_path': prepared['root'], 'asset_binding': { + 'manifest_path': prepared['manifest_path'], 'manifest_sha256': prepared['manifest_sha256']}} + + async def wait_for_export(journal, root, request, resume, *, collect_only=False): from ..video_export_jobs import export_job_id @@ -249,26 +272,8 @@ async def run(session, plugin, wheel, root, scene_id, resume=False, *, collect_o for role, query in [('cabinet', 'Lift-Up Wall Cabinet'), ('book_a', 'AmazonBasics Classic Blank Notebook'), ('box', 'Ready to Use Rolled Fondant Pure White')]: - selected = lock['assets'][role] - found = await journal.call('catalog_search', {'query': query, - 'filters': {'source_ids': [selected['source_ref']['source_id']]}, 'limit': 20}) - budgets = found.get('budgets', {}) - if budgets.get('model_bytes') != 0 or budgets.get('preview_bytes') != 0: - raise WorkflowError(f'{role} metadata search downloaded a model or preview, or did not report bytes') - item = next((x for x in found.get('items', []) if x.get('ref') == selected['source_ref']), None) - if not item: - raise WorkflowError(f'locked {role} was not returned by the catalog') - plan = await journal.call('asset_plan', {'asset_ref': item['ref'], 'profile_id': selected['profile_id'], - 'parameters': selected['parameters'], 'budget_bytes': 50_000_000}) - if not plan.get('ready_to_fetch'): - raise WorkflowError(f'locked {role} is blocked; inspect asset_plan') - job = await journal.call('asset_prepare', {'plan_id': plan['plan_id'], - 'request_id': f'{scene_id}-prepare-{role}'}) - _write(root/f'prepare-{role}-job.json', job) - done = await wait_for_job(journal, job['job_id'], root/f'prepare-{role}-wait.json', 300) - prepared = done['result'] - bindings[role] = {'asset_path': prepared['root'], 'asset_binding': { - 'manifest_path': prepared['manifest_path'], 'manifest_sha256': prepared['manifest_sha256']}} + bindings[role] = await prepare_fixed_asset(journal, root, scene_id, role, query, + lock['assets'][role], 50_000_000) _write(root/'bindings.json', bindings) _helper(plugin, root, 'apply_scene_recipe.py', [example/'recipe.json', '--asset-catalog', root/'bindings.json', '--asset-lock', example/'assets.lock.json', '--save-directory', root/'ops', '--operations-only']) @@ -386,7 +391,7 @@ def select_launcher(plugin, requested=None): return Path(requested).expanduser().resolve() if requested else Path(plugin).resolve()/'server/launch.py' -async def run_installed(plugin, wheel, root, scene_id, launcher=None, resume=False, *, collect_only=False): +async def run_installed(plugin, wheel, root, scene_id, launcher=None, resume=False, *, collect_only=False, workflow=run): from mcp import ClientSession, StdioServerParameters from mcp.client.stdio import stdio_client plugin, root = Path(plugin).resolve(), Path(root).resolve() @@ -402,4 +407,4 @@ async def run_installed(plugin, wheel, root, scene_id, launcher=None, resume=Fal async with stdio_client(params, errlog=error_log) as (reader, writer): async with ClientSession(reader, writer, read_timeout_seconds=timedelta(seconds=1900)) as session: await session.initialize() - return await run(session, plugin, wheel, root, scene_id, resume=resume, collect_only=collect_only) + return await workflow(session, plugin, wheel, root, scene_id, resume=resume, collect_only=collect_only) diff --git a/src/simscene/recipes/data/fixed-examples.json b/src/simscene/recipes/data/fixed-examples.json index c7e50b9..704d757 100644 --- a/src/simscene/recipes/data/fixed-examples.json +++ b/src/simscene/recipes/data/fixed-examples.json @@ -1,6 +1,21 @@ { "schema": "simscene.fixed_examples.v1", "examples": [ + { + "id": "first_delivery", + "description": "One GSO scanned box drops onto an editable primitive worktop and produces a short native video.", + "asset_sources": ["gso-glb"], + "profiles": ["rigid_prop_v1"], + "asset_lock": "assets.lock.json", + "operations": ["recipe.json"], + "case": "case.json", + "checker": "builtin:simscene verify", + "steps": 240, + "seed": 42, + "runtime_evidence": "prior_example_only", + "requires_new_physical_verification": true, + "scope": "A pinned 120 mm scan and an experimental 0.12 kg mass; verify fall, direct table contact, full bounds and settling on each run." + }, { "id": "automatic_cabinet_layout", "description": "Measured worktable layout with one scheduled USDCraft hinge, two ABO notebooks and one GSO box.", diff --git a/src/simscene/recipes/first_delivery.py b/src/simscene/recipes/first_delivery.py new file mode 100644 index 0000000..c0447b4 --- /dev/null +++ b/src/simscene/recipes/first_delivery.py @@ -0,0 +1,144 @@ +"""Run and verify the packaged one-asset first delivery via MCP.""" +import json +from pathlib import Path +import shutil + +from .cabinet_mcp_workflow import ( + MCPJournal, WorkflowError, _next_path, _sha, _write, check_identity, + check_run_scene, prepare_fixed_asset, wait_for_export, wait_for_job, +) +from .cases import freeze_case_file +from .integration_delivery import check_edit_binding, check_visual_review +from .io import resolve_operations + +EXAMPLE = 'first_delivery' +STEPS = 240 +FPS = 30 + + +def _read(path): + return json.loads(path.read_text()) + + +async def run(session, plugin, wheel, root, scene_id, resume=False, *, collect_only=False): + if collect_only and not resume: + raise WorkflowError('collection mode requires recovery of a previous invocation') + example = plugin/'examples'/EXAMPLE + journal_dir = root/'mcp-calls' + journal_dir.mkdir(exist_ok=resume) + journal = MCPJournal(session, journal_dir) + response = await session.read_resource('simscene://runtime/identity') + identity = json.loads(response.contents[0].text) + check_identity(identity, plugin, wheel) + if resume: + if _read(root/'identity.json') != identity: + raise WorkflowError('recovery requires the original installed package and wheel') + scene = _read(root/'scene.json') + scene_id = scene['scene_id'] + else: + _write(root/'identity.json', identity) + response = await session.read_resource('simscene://recipes/examples') + examples = json.loads(response.contents[0].text) + if not any(item['id'] == EXAMPLE for item in examples['examples']): + raise WorkflowError('this installed package does not contain the first delivery example') + environment = await journal.call('environment_probe', {}) + if not environment.get('isaac', {}).get('available'): + raise WorkflowError('set SIMSCENE_ISAAC_PYTHON to an executable Isaac Sim python.sh') + if not all(shutil.which(tool) for tool in ('ffmpeg', 'ffprobe')): + raise WorkflowError('install FFmpeg and ffprobe on the simulation host before recording') + lock_path = example/'assets.lock.json' + selections = _read(lock_path)['assets'] + binding = await prepare_fixed_asset( + journal, root, scene_id, 'box', 'Ready to Use Rolled Fondant Pure White', + selections['box'], 1024**2, + ) + bindings = {'box': binding} + _write(root/'bindings.json', bindings) + operations = resolve_operations(_read(example/'recipe.json'), bindings, selections=selections) + opened = await journal.call('scene_open', {'scene_id': scene_id}) + await journal.call('scene_apply', {'scene_id': scene_id, 'base_revision': opened['revision'], + 'request_id': scene_id+'-create', 'operations': operations}) + scene = await journal.call('scene_get', {'scene_id': scene_id}) + _write(root/'scene.json', scene) + await journal.call('scene_measure', {'scene_id': scene_id, 'ids': ['table', 'box'], + 'include_overlap_candidates': True}) + if (await journal.call('scene_validate', {'scene_id': scene_id})).get('issues') != []: + raise WorkflowError('scene validation reported issues; see the saved MCP response') + freeze_case_file(example/'case.json', root/'bindings.json', lock_path, root/'case.json') + request = {'scene_id': scene_id, 'steps': STEPS, 'seed': 42, + 'case_path': str(root/'case.json'), 'request_id': scene_id+'-physics'} + request_path = root/'physics-request.json' + if resume: + if _read(request_path) != request: + raise WorkflowError('original physics request differs from the saved scene') + else: + _write(request_path, request) + receipt = root/'physics-job.json' + if resume and receipt.is_file(): + job = _read(receipt) + elif collect_only: + raise WorkflowError('no saved physics job ID; collection cannot start a new job') + else: + if await journal.call('scene_get', {'scene_id': scene_id}) != scene: + raise WorkflowError('the scene changed before physics; keep the saved scene and start a fresh example') + job = await journal.call('simulation_start', request) + _write(receipt, job) + job_id = job['job_id'] + state = await wait_for_job(journal, job_id, _next_path(root/'physics-wait.json'), 1800) + run_directory = Path(state['result_file']).resolve().parent + if run_directory.name != job['run_id']: + raise WorkflowError('physics job and completed run do not match') + check_run_scene(scene, run_directory) + check_path = _next_path(root/'physical-check.json') + checked = await journal.call('run_verify', {'job_id': job_id, 'case_type': 'rigid_asset_smoke'}) + _write(check_path, checked) + if checked.get('passed') is not True: + raise WorkflowError(f'physical verification failed; see {check_path}') + movie = root/'first-delivery.mp4' + request = {'segments': [{'run_directory': str(run_directory), 'camera': 'drop', + 'start_sim_time_s': 2/60, 'end_sim_time_s': (STEPS+2)/60}], + 'destination': str(movie), 'request_id': scene_id+'-video', 'output_resolution': [1920, 1080]} + exported = await wait_for_export(journal, root, request, resume, collect_only=collect_only) + inspection = await journal.call('video_inspect', {'path': str(movie), 'output_dir': str(_next_path(root/'frames')), + 'representative_count': 5}) + inspection_path = _next_path(root/'video-inspection.json') + _write(inspection_path, inspection) + edit = movie.with_suffix('.edit.json') + errors = check_edit_binding(_read(edit), movie, run_directory, physics_steps=STEPS) + if (errors or not (inspection.get('simulation_timeline') or {}).get('passed') + or inspection.get('decoded_frame_count') != STEPS//2): + raise WorkflowError('video inspection or source mapping failed: '+', '.join(errors)) + result = {'schema': 'simscene.first_delivery.v1', 'status': 'needs_visual_review', + 'physical_status': 'passed', 'media_status': 'passed', 'visual_review': 'pending', + 'physics_job_id': job_id, 'run_id': run_directory.name, 'export_job_id': exported['job_id'], + 'scene': str(root/'scene.json'), 'video': str(movie), 'edit_map': str(edit), + 'video_sha256': _sha(movie), 'edit_map_sha256': _sha(edit), + 'check': str(check_path), 'check_sha256': _sha(check_path), 'inspection': str(inspection_path)} + result_path = _next_path(root/'delivery.json') + _write(result_path, result) + return {**result, 'receipt': str(result_path)} + + +def record_review(directory, review_file): + """Bind an attributed review to the completed technical delivery.""" + root = Path(directory).resolve() + receipt = _read(root/'delivery.json') + movie = root/'first-delivery.mp4' + edit = movie.with_suffix('.edit.json') + checked = Path(receipt['check']).resolve() + if (receipt.get('schema') != 'simscene.first_delivery.v1' or receipt.get('status') != 'needs_visual_review' + or receipt.get('physical_status') != 'passed' or receipt.get('media_status') != 'passed' + or Path(receipt['video']).resolve() != movie or Path(receipt['edit_map']).resolve() != edit + or checked.parent != root or _sha(checked) != receipt['check_sha256'] or _read(checked).get('passed') is not True + or _sha(movie) != receipt['video_sha256'] or _sha(edit) != receipt['edit_map_sha256']): + raise WorkflowError('delivery artifacts differ from the technical receipt') + review = _read(Path(review_file)) + errors = check_visual_review(review, movie, STEPS/60, [{'start_s': 0., 'end_s': .5}, {'start_s': 2., 'end_s': STEPS/60}]) + if errors: + raise WorkflowError('review does not cover the fall and settled result: '+', '.join(errors)) + decision = review['decision'] + receipt.update(status='ready_for_submission' if decision == 'accept' else 'change_needed', + visual_review=decision, review=review) + output = _next_path(root/'reviewed-delivery.json') + _write(output, receipt) + return {'status': receipt['status'], 'video': str(movie), 'receipt': str(output)} diff --git a/src/simscene/recipes/integration_delivery.py b/src/simscene/recipes/integration_delivery.py index 154d4ac..a82d29a 100644 --- a/src/simscene/recipes/integration_delivery.py +++ b/src/simscene/recipes/integration_delivery.py @@ -23,8 +23,10 @@ def _canonical(value): allow_nan=False).encode()).hexdigest() -def check_edit_binding(edit, video, run): +def check_edit_binding(edit, video, run, *, physics_steps=600): """Check that each declared camera source belongs to this exact run.""" + frame_count = physics_steps // 2 + duration_s = physics_steps / 60 errors = [] try: video, run = Path(video).resolve(), Path(run).resolve() @@ -36,8 +38,8 @@ def check_edit_binding(edit, video, run): segments = edit.get('segments') if isinstance(edit, dict) else None if not isinstance(segments, list) or not segments: return errors + ['edited video has no source segments'] - if lock.get('requested_physics_steps') != 600 or not math.isclose(lock.get('physics_dt_s', 0), 1 / 60, abs_tol=1e-9): - errors.append('fixed example requires 600 physics steps at 60 Hz') + if lock.get('requested_physics_steps') != physics_steps or not math.isclose(lock.get('physics_dt_s', 0), 1 / 60, abs_tol=1e-9): + errors.append(f'fixed example requires {physics_steps} physics steps at 60 Hz') next_frame = 0 next_output = 0.0 frame_tables = {} @@ -56,7 +58,7 @@ def check_edit_binding(edit, video, run): errors.append(f'segment {index} does not match the run, camera or frame table') continue if segment['camera'] not in frame_tables: - if record.get('fps') != 30 or record.get('frames') != 300: + if record.get('fps') != 30 or record.get('frames') != frame_count: errors.append(f'segment {index} does not use the native 30 fps recording') continue frame_file = Path(record['frame_manifest']) @@ -64,7 +66,7 @@ def check_edit_binding(edit, video, run): errors.append(f'segment {index} frame table is too large') continue frames = [json.loads(line) for line in frame_file.read_text().splitlines()] - if (len(frames) != 300 or any( + if (len(frames) != frame_count or any( row.get('frame_id') != i or row.get('physics_step') != 2 + 2 * i or not math.isclose(row.get('sim_time_s', -1), (2 + 2 * i) / 60, abs_tol=1e-8) for i, row in enumerate(frames))): @@ -72,7 +74,7 @@ def check_edit_binding(edit, video, run): continue frame_tables[segment['camera']] = frames start, end = segment.get('source_start_frame'), segment.get('source_end_frame_exclusive') - if (type(start) is not int or type(end) is not int or not 0 <= start < end <= 300 + if (type(start) is not int or type(end) is not int or not 0 <= start < end <= frame_count or start != next_frame or segment.get('source_fps') != 30 or segment.get('speed') != 1 or segment.get('output_frames') != end - start): errors.append(f'segment {index} skips frames or changes their playback speed') @@ -88,8 +90,8 @@ def check_edit_binding(edit, video, run): continue next_frame = end next_output = expected['output_end_s'] - if next_frame != 300 or not math.isclose(next_output, 10., abs_tol=1e-6): - errors.append('technical video must cover the complete 10-second run in order') + if next_frame != frame_count or not math.isclose(next_output, duration_s, abs_tol=1e-6): + errors.append(f'technical video must cover the complete {duration_s:g}-second run in order') except (OSError, ValueError, TypeError, KeyError, AttributeError) as error: errors.append('cannot verify edited source binding: ' + str(error)) return errors diff --git a/tests/agent/test_package.py b/tests/agent/test_package.py index cc9d212..e465e4a 100644 --- a/tests/agent/test_package.py +++ b/tests/agent/test_package.py @@ -97,7 +97,12 @@ async def check_independent_metadata(root,plugin): stage=root/kind;stage.mkdir() plugin=output/kind/'simscene' self.assertTrue((plugin/'README.md').is_file()) - for sample in ('examples/automatic_cabinet_layout/assets.lock.json', + for sample in ('examples/first_delivery/README.md', + 'examples/first_delivery/assets.lock.json', + 'examples/first_delivery/recipe.json', + 'examples/first_delivery/case.json', + 'experiments/run_first_delivery.py', + 'examples/automatic_cabinet_layout/assets.lock.json', 'examples/automatic_cabinet_layout/recipe.json', 'examples/automatic_cabinet_layout/case.json', 'examples/automatic_cabinet_layout/supplemental-checks.json', diff --git a/tests/test_integration_example_registry.py b/tests/test_integration_example_registry.py index 4c1b83c..f0b26fc 100644 --- a/tests/test_integration_example_registry.py +++ b/tests/test_integration_example_registry.py @@ -12,7 +12,7 @@ def test_fixed_examples_are_separate_from_compilable_role_recipes(): listing = registry.list_examples() assert listing['schema'] == 'simscene.fixed_examples.v1' examples = {entry['id']: entry for entry in listing['examples']} - assert set(examples) == {'automatic_cabinet_layout', 'artvip_door', + assert set(examples) == {'first_delivery', 'automatic_cabinet_layout', 'artvip_door', 'usdcraft_two_drawer', 'usdcraft_sdk_guide', 'integration_workspace'} assert examples['automatic_cabinet_layout']['asset_sources'] == ['usdcraft', 'abo-glb', 'gso-glb'] assert examples['automatic_cabinet_layout']['runtime_evidence'] == 'prior_example_only' @@ -36,3 +36,25 @@ def test_fixed_example_resource_returns_registry_data(): import json assert hasattr(mcp_server, 'fixed_examples_resource') assert json.loads(mcp_server.fixed_examples_resource()) == registry.list_examples() + + +def test_first_delivery_locks_only_one_real_import_and_builtin_support(): + import json + from simscene.recipes.io import portable + from simscene.verification.rigid_asset_smoke import validate_case + + entry = next(e for e in registry.list_examples()['examples'] if e['id'] == 'first_delivery') + assert entry['asset_sources'] == ['gso-glb'] + assert entry['steps'] == 240 + example = ROOT/'examples/first_delivery' + lock = portable(json.loads((example/'assets.lock.json').read_text()))['assets'] + assert list(lock) == ['box'] + ops = portable(json.loads((example/'recipe.json').read_text()))['operations'] + assets = {op['id']: op['object'] for op in ops if op.get('object', {}).get('kind') == 'asset'} + assert set(assets) == {'box'} + assert assets['box']['dynamic'] and assets['box']['asset_role'] == 'box' + support = next(op['object'] for op in ops if op.get('id') == 'table') + assert support['kind'] == 'box' and support['collision'] is True + case = validate_case(json.loads((example/'case.json').read_text())) + assert case['objects']['box']['support_actors'] == ['/World/table'] + assert case['objects']['box']['initial_height_m'] == assets['box']['position'][2] From c90589c9d07d22c095fcac275479ffdb4341bfdf Mon Sep 17 00:00:00 2001 From: shaoxiang <519517384@qq.com> Date: Wed, 25 Nov 2026 14:33:00 +0800 Subject: [PATCH 16/20] Capture the first delivery initial state before physics --- examples/first_delivery/recipe.json | 8 ++++++++ experiments/run_first_delivery.py | 2 ++ tests/test_integration_example_registry.py | 2 ++ 3 files changed, 12 insertions(+) diff --git a/examples/first_delivery/recipe.json b/examples/first_delivery/recipe.json index 9d1aa35..d14a528 100644 --- a/examples/first_delivery/recipe.json +++ b/examples/first_delivery/recipe.json @@ -150,6 +150,14 @@ } } }, + { + "op": "set_observation", + "observation": { + "sample_interval_steps": 1, + "strict_start": true, + "record_contact_pairs": true + } + }, { "op": "set_presentation", "presentation": { diff --git a/experiments/run_first_delivery.py b/experiments/run_first_delivery.py index 12936e6..fe69691 100644 --- a/experiments/run_first_delivery.py +++ b/experiments/run_first_delivery.py @@ -30,6 +30,8 @@ def main(): result = asyncio.run(run_installed(plugin, args.wheel, args.output, scene_id, resume=args.resume, collect_only=args.collect_only, workflow=run)) except Exception as error: + while len(getattr(error, 'exceptions', ())) == 1: + error = error.exceptions[0] print(json.dumps({'status': 'incomplete', 'directory': args.output, 'error': str(error)[:900]}, ensure_ascii=False)) return 2 diff --git a/tests/test_integration_example_registry.py b/tests/test_integration_example_registry.py index f0b26fc..1768100 100644 --- a/tests/test_integration_example_registry.py +++ b/tests/test_integration_example_registry.py @@ -50,6 +50,8 @@ def test_first_delivery_locks_only_one_real_import_and_builtin_support(): lock = portable(json.loads((example/'assets.lock.json').read_text()))['assets'] assert list(lock) == ['box'] ops = portable(json.loads((example/'recipe.json').read_text()))['operations'] + observation = next(op['observation'] for op in ops if op['op'] == 'set_observation') + assert observation['strict_start'] is True and observation['sample_interval_steps'] == 1 assets = {op['id']: op['object'] for op in ops if op.get('object', {}).get('kind') == 'asset'} assert set(assets) == {'box'} assert assets['box']['dynamic'] and assets['box']['asset_role'] == 'box' From e0072008f3c98c70b257c641d0ab25ebf6fe780f Mon Sep 17 00:00:00 2001 From: shaoxiang <519517384@qq.com> Date: Wed, 25 Nov 2026 15:46:25 +0800 Subject: [PATCH 17/20] Integrate public preview documentation and the dev2 first-use path --- README.md | 345 +++++++++++------- ...53\351\200\237\345\274\200\345\247\213.md" | 122 +++++-- 2 files changed, 305 insertions(+), 162 deletions(-) diff --git a/README.md b/README.md index 1253744..f549d34 100644 --- a/README.md +++ b/README.md @@ -2,125 +2,170 @@ **Describe a scene. Find assets online. Build, simulate, and film it.** -SimScene gives AI agents tools to discover simulation assets, compose editable -USD scenes, run Isaac Sim, and improve the result from real images and physical -observations. It connects online asset selection to scene creation and video -delivery through MCP and reusable agent skills. - -[V2 preview](https://github.com/ros-claw/simscene/releases/tag/v0.2.0-dev.1) · [Asset catalog](docs/asset-catalog.md) · [中文快速开始](docs/快速开始.md) · [Plugin setup](docs/packaging.md) · [Examples](#examples) · [Apache-2.0](LICENSE) +SimScene gives AI agents an MCP server and reusable skills for discovering +assets, composing editable USD scenes, running NVIDIA Isaac Sim, and producing +videos from real simulation recordings. Agents can inspect images, measured +motion, and contacts to check and improve a scene. + +**Current public preview:** [v0.2.0-dev.1](https://github.com/ros-claw/simscene/releases/tag/v0.2.0-dev.1) +· [Supported asset sources](#supported-asset-sources) +· [Get started](#get-started) +· [Connect your agent](#connect-your-agent) +· [中文快速开始](docs/快速开始.md) +· [Examples](#examples) ![The multi-source kinetic gallery rendered in Isaac Sim](docs/media/kinetic-asset-gallery-preview.png) -[Watch the V2 kinetic gallery (66s)](docs/media/kinetic-asset-gallery-1080p30.mp4) · [Watch the chain reaction](docs/media/chain-workshop-1080p30.mp4) · [Watch the sorting workshop](docs/media/precision-workshop-1080p30.mp4) +[Kinetic gallery · 66s](docs/media/kinetic-asset-gallery-1080p30.mp4) +· [Whole-home chain reaction · 55s](docs/media/only-one-sugar-public-55s.mp4) +· [Three-arm sorting workshop](docs/media/precision-workshop-1080p30.mp4) ## What you can build -| Capability | What SimScene provides | +| Capability | What the agent can use | | --- | --- | -| Online asset discovery | Natural-language NVIDIA USD Search, asset inspection, previews, and Hugging Face repository discovery. | -| On-demand acquisition | Fetch selected assets and dependencies into a bounded cache on the simulation host. No full asset library download is required. | -| Editable composition | USD scenes, measured placement, support relationships, materials, lights, cameras, and reusable scene recipes. | -| Physical interaction | Isaac Sim execution, state and contact observations, and checks against a case defined before the run. | -| Simulation films | Native camera recording, editable camera plans, video editing, and frame-level source tracking. | -| Agent workflows | An MCP server plus skills for building scenes and delivering simulation videos. | - -The project has completed a stage covering online asset composition, physical -interaction validation, and multi-camera film delivery, with reusable production -tools. Measured comparisons have not established token savings across tasks; -see the [results and limitations](docs/validation/catalog-efficiency.md). +| Find assets online | NVIDIA USD Search, a source-aware metadata catalog, previews, and Hugging Face repository discovery. | +| Acquire selected models | Download a chosen model and its dependencies into a bounded cache on the simulation host. | +| Compose editable scenes | Measured placement, explicit support regions, materials, lights, cameras, and parameterized recipes. | +| Run physical experiments | Isaac Sim jobs, native body/joint observations, contacts, and checks against a case fixed before the run. | +| Deliver simulation videos | Native camera capture, camera plans, editing, and mappings from output frames back to recorded runs. | +| Reuse successful work | Two agent skills, editable examples, persistent preparation jobs, and optional template-based generation. | + +**You do not need to download a whole asset library to search it.** Catalog +search reads bounded metadata and keeps preview loading separate. After selection, the simulation +host downloads the required model, materials, and dependencies. A remote client +can receive images and results while those files remain on the GPU host. + +## Supported asset sources + +The public preview registers **7 sources: 5 enabled and 2 audited**. Three are +searched by default. Optional sources require explicit selection. + +| Resource | Source ID | Availability | Supported route and recorded scope | +| --- | --- | --- | --- | +| [NVIDIA USD Search](https://search.simready.omniverse.nvidia.com) | `nvidia-usd-search` | Default · enabled | Natural-language metadata search and selected native USD acquisition. The recorded workbench uses visual geometry with an explicit support proxy; its unresolved individual license blocks the newer preparation route. | +| [ABO GLB](https://huggingface.co/datasets/codepawl/abo-glb) | `abo-glb` | Default · enabled | Community-converted Amazon Berkeley Objects: metadata search and selected standard GLB preparation. A notebook has recorded rigid-body fall, contact, and settling checks. | +| [GSO GLB](https://huggingface.co/datasets/codepawl/scanned-objects-glb) | `gso-glb` | Default · enabled | Community-converted Google Scanned Objects: metadata search and selected standard GLB preparation. A scanned box has a real drop test and missing-support control. | +| [NVIDIA USDCraft-10K](https://huggingface.co/datasets/nvidia/USDCraft-10K) | `usdcraft` | Optional · enabled | Manifest search and selected native USD dependencies. The recorded `ds_R021_02` cabinet preserves a two-link, single-hinge articulation; arbitrary multi-DOF imports are outside this public profile. | +| [Poly Haven](https://polyhaven.com) | `polyhaven` | Optional · enabled | Configured HDRI/material IDs and selected resolutions. A 1k HDRI has light-only USD preparation and rendering evidence; material-map acquisition does not imply geometry preparation. | +| [NVIDIA SimReady Central](https://huggingface.co/spaces/nvidia/simready-central) | `simready-central` | Optional · audited | Literal filename filtering through its HTTP service. Returns metadata locators; this adapter does not directly acquire or prepare the returned assets. | +| [ProjectSim SimReady packages](https://huggingface.co/datasets/projectsim/simready-assets) | `projectsim-public` | Optional · audited | The selected `industrial_pipe_valve` BOM package has acquisition, visual-only preparation, texture rendering, and cache-restore evidence. Its original dynamics and joints are not qualified. | + +**Enabled** means an adapter has a finite integration example. **Audited** is a +limited admission state, not full-source support. Search availability, preparation, +and physical success are separate results; each recorded check applies to its +listed asset, parameters, and runtime. + +For the current development checkout, the +[packaged registry](src/simscene/catalog/data/sources.yaml) is authoritative. +Its generated [full source list](docs/assets/SOURCES.md) records revisions, +license scope, examples, and limitations. See also +[measured capabilities](docs/validation/catalog-capabilities.md) and +[adding a source](docs/assets/ADDING_A_SOURCE.md). + +```bash +simscene catalog sources +simscene catalog search 'notebook' --source abo-glb --limit 4 +simscene catalog search 'cabinet' --source usdcraft --limit 4 +``` + +Hugging Face discovery finds **candidate repositories**; it does not automatically +register them or certify their models. NVIDIA USD Search and SimReady Central +are distinct services, not interchangeable names for an asset dataset. Neither +implies that every Hugging Face model is indexed or ready for physics. + +### Optional generation + +[Sand3D integration](docs/asset-generation.md) runs the shipped +`guide_plate_v1` and `open_receiver_v1` templates in a separately configured +environment. Generated assets enter the same preparation and physical-check +workflow. This is a generation backend, not another downloadable asset library; +it does not execute arbitrary code returned by search. ## Get started -**Development package (dev2):** try the [one-object first delivery](examples/first_delivery/README.md) -for a checked drop onto a SimScene worktop and a four-second native video. +### Development branch -**Recommended first run:** pin [v0.2.0-dev.1](docs/releases/v0.2.0-dev.1.md#安装与第一次尝试) -→ configure the tested runtime → select a small ABO/GSO object → check a single -object's fall, contact and settling → expand to multiple instances → record video. -Follow the [preparation setup](docs/asset-catalog.md#configure-the-preparation-runtime-explicitly) -before attempting GLB physics. The [gravity-cell example](examples/catalog_gravity_cell/README.md) -documents the single-object and four-instance checks; its NVIDIA table follows -the separate legacy acquisition route described below. +Build and install the current dev2 portable package using +[the package guide](docs/packaging.md). Then run the +[one-object first delivery](examples/first_delivery/README.md) to search for a +pinned GSO scan, drop it onto an editable worktop, verify the run and export a +four-second native video. See the [integration results](docs/validation/integration-release-matrix.md) +for tested cases and client qualification scope. -| Your setup | What to try next | -| --- | --- | -| Base SimScene installation and network access | Search metadata and inspect candidates; this does not require the GLB decoder or start Isaac Sim. | -| Compatible Isaac Sim and USD bindings, pinned Node.js decoder, successful `asset probe` | Prepare a selected ABO/GSO GLB, then run fall/contact/settling checks. | -| Verified physical scene and configured FFmpeg | Plan cameras, capture native frames, inspect and export video. | -Python **3.10+** is required. Running simulations also requires a compatible -**NVIDIA Isaac Sim** installation on a GPU host. Install FFmpeg for video capture -and editing; see [video setup](docs/视频交付.md) for encoding requirements. +### 1. Search metadata first + +Use **Python 3.10+** and pin the public preview. These catalog commands do not +start Isaac Sim or require the optional GLB decoder: ```bash -git clone https://github.com/ros-claw/simscene.git +git clone --branch v0.2.0-dev.1 https://github.com/ros-claw/simscene.git cd simscene -git checkout v0.2.0-dev.1 python3 -m venv .venv . .venv/bin/activate -python -m pip install -e . usd-core +python -m pip install -e . -simscene configure --isaac-python /absolute/path/to/isaac-sim/python.sh -simscene doctor -simscene search 'industrial conveyor' +simscene catalog sources +simscene catalog search 'notebook' --source abo-glb --limit 4 +simscene recipe list ``` -Search returns candidates and metadata. After choosing a result, inspect it and -acquire only the selected files: +The first query may fetch a bounded metadata index. It does not download the +model library. For a prebuilt installation, the +[preview release](https://github.com/ros-claw/simscene/releases/tag/v0.2.0-dev.1) +includes a Python wheel and a **Linux x86_64 / Python 3.10** client bundle; +see [installation and relocation](docs/packaging.md). + +### 2. Prepare one object and run a small physical test + +| Operation | Additional requirements | +| --- | --- | +| Local USD inspection and scene export | Compatible host USD Python bindings. | +| Physical simulation and native rendering | A compatible NVIDIA Isaac Sim installation and GPU host. | +| Selected ABO/GSO GLB preparation | Configured Isaac asset converter, pinned Node.js decoder, and a successful `simscene asset probe`. | +| Native recording and video editing | Configured capture settings and FFmpeg/ffprobe with H.264 encoding and `zscale` support. | +| Sand3D generation | Its separate reviewed runtime; optional for all other workflows. | + +The recorded catalog/preparation runtime is **Isaac Sim 6.2.0-rc.14**, OpenUSD +**0.25.11**, on Linux/RTX A6000. Other versions need their own compatibility +check; configuring a launcher path alone does not establish compatibility. ```bash -simscene inspect 'ASSET_URL_FROM_SEARCH' -simscene acquire 'ASSET_URL_FROM_SEARCH' +python -m pip install usd-core +simscene configure --isaac-python /absolute/path/to/isaac-sim/python.sh +simscene doctor ``` -The default service is [NVIDIA USD Search](https://search.simready.omniverse.nvidia.com). -Set `USD_SEARCH_API_URL` to use another endpoint. Check each asset's dependency -status and license before use. Downloaded models and textures are not bundled -with this repository. +Install host USD bindings in the SimScene environment and verify compatibility +with your target runtime. Follow +[preparation setup](docs/asset-catalog.md#configure-the-preparation-runtime-explicitly) +to configure the decoder and probe the runtime before GLB physics. +`doctor` checks configuration; `asset probe` starts the preparation runtime and +records its capabilities. -## V2 catalog and preparation +**Recommended first experiment:** the +[cross-catalog gravity cell](examples/catalog_gravity_cell/README.md). +Its reproduction starts with a pinned ABO notebook and an NVIDIA table, then +checks fall, contact, and settling before expanding to several notebook +instances. The table uses a separate legacy acquisition route with an unresolved +individual license and explicit proxy limits; review the example before +acquiring its assets. Other selected-object evidence, including GSO, is listed +in the [capability matrix](docs/validation/catalog-capabilities.md). -This unreleased development branch is **0.2.0.dev2** (plugin **0.2.0-dev.2**). -The published V2 preview is **0.2.0.dev1** (plugin **0.2.0-dev.1**). It adds -unified metadata search, immutable preparation plans, persistent preparation jobs, -role-based scene recipes and optional isolated Sand3D generation. See the -[source registry](docs/assets/SOURCES.md) and [measured validation scope](docs/validation/catalog-capabilities.md). +For the existing native USD route: ```bash -simscene catalog sources -simscene catalog search 'notebook' --source abo-glb --limit 4 -simscene recipe list +simscene search 'industrial conveyor' +simscene inspect 'ASSET_URL_FROM_SEARCH' +simscene acquire 'ASSET_URL_FROM_SEARCH' ``` -Search retrieves metadata; selecting and preparing a model is a separate step. -Default sources are NVIDIA USD Search, ABO and GSO. Explicit optional providers -cover a reviewed native USD manifest, one curated ArtVIP door, a selected BOM -package, configured HDRI IDs and Central metadata locators. Asset licenses, dependency completeness and -physical suitability are checked individually. Source admission does not -certify every model. - -The example NVIDIA PackingTable's individual license remains unknown, so the -new `asset_plan` route blocks its preparation. Enabling NVIDIA search by default -does not authorize preparing every result. The gravity-cell example documents -its separate legacy acquisition route and makes no redistribution claim. - -For imported dynamic objects, use the prepared package's actual body mapping -and verify contacts, movement and settling. The [gravity-cell example](examples/catalog_gravity_cell/README.md) -provides a complete selected-asset route. [Preparation](docs/asset-catalog.md), -[scene recipes](docs/scene-recipes.md), and [optional generation](docs/asset-generation.md) -describe setup and reuse. Existing asset and simulation tools remain compatible. - -This development branch also offers [optional automatic measured layout](docs/scene-layout.md) -for existing props on an explicitly measured support. It proposes editable -placements; the original USD and separate physical verification remain intact. -The branch additionally supports an isolated [USDCraft SDK guide-plate generator](docs/usdcraft-sdk.md) -and a narrowly admitted two-joint native asset profile. The pinned v0.2.0-dev.1 -release above predates these capabilities. - -An independent [MobilityGen Jetbot experiment](experiments/mobilitygen_jetbot/README.md) -provides one fixed-route physical test and a zero-command control. It is not yet -connected to SimScene scene or simulation jobs, and does not establish general -robot planning or obstacle avoidance. +The default endpoint is NVIDIA USD Search; `USD_SEARCH_API_URL` selects another +compatible endpoint. Review the chosen asset's license and dependencies. +This legacy `search` command requests inline previews by default; use catalog +search for the metadata-only route. Downloaded models and textures are not +bundled with SimScene. ## Connect your agent @@ -130,7 +175,7 @@ Run the MCP server from the installed environment: simscene mcp ``` -For an MCP client that accepts a JSON server configuration: +For a client that accepts an `mcpServers` configuration: ```json { @@ -143,61 +188,97 @@ For an MCP client that accepts a JSON server configuration: } ``` -Use the [build-scene](skills/build-scene/SKILL.md) skill to discover assets, -compose a scene, run it, and inspect the result. Use -[deliver-scene-video](skills/deliver-scene-video/SKILL.md) to plan cameras and -produce traceable films. [Packaging and installation](docs/packaging.md) covers -portable, Claude Code, and DeepSeek Harness integration. +| Client | Integration | Recorded public-preview evidence | +| --- | --- | --- | +| Codex | Portable package, matching skills, optional explicit MCP registration | Two authenticated tasks covering native video/physics and imported GLB preparation/physics. | +| Claude Code | Claude plugin layout and matching skills | Packaged stdio and host skill/MCP loading; no authenticated Claude model task claimed. | +| DeepSeek Harness | MCP overlay plus skill-directory configuration | Packaged stdio, overlay loading, and tool listing; no authenticated DeepSeek model task claimed. | +| Other MCP clients | Stdio configuration | Compatibility depends on the client; complete tasks need their own validation. | -Try a prompt such as: +See [packaging and client setup](docs/packaging.md) for the exact installation, +registration, environment-forwarding, and DeepSeek relocation steps, and +[release qualification](examples/catalog_benchmark/results/release-qualification.json) +for the scoped Codex results. Package loading is distinct from completing a +new scene-building task. -> Build a small workshop with a conveyor, collection bins, and a camera that -> clearly shows the handoff. Find suitable assets online, inspect their scale -> and dependencies, run the scene, and improve it from the observations. +MCP registration and skill installation are separate steps. Install the matching +skills with the portable installer's project option, or use your client's skill +mechanism. Set runtime paths and decoder configuration in the environment that +actually launches the MCP server; an export in another terminal may not reach it. -## Examples +The two skills divide the work: -| Example | Explore | -| --- | --- | -| Only one sugar cube | [Editable whole-home experiment](examples/whole_home_sugar/README.md) · [55-second film](docs/media/only-one-sugar-public-55s.mp4) · [Red-rope control](docs/media/red-rope-causal-comparison-20s.mp4) | -| Multi-source kinetic gallery | [Editable recipe](examples/kinetic_asset_gallery/README.md) · [66-second film](docs/media/kinetic-asset-gallery-1080p30.mp4) | -| Cross-catalog gravity cell | [Locked assets, physical case and reproduction](examples/catalog_gravity_cell/README.md) | -| Automatic cabinet layout (development branch) | [Editable recipe, source lock and physical checks](examples/automatic_cabinet_layout/README.md) | -| ArtVIP door (development branch) | [Selected asset, explicit physics assumptions and drive checks](examples/artvip_door/README.md) | -| USDCraft two-drawer cabinet (development branch) | [Two native joints, editable recipe and drive control](examples/usdcraft_two_drawer/README.md) | -| Generated USDCraft guide (development branch) | [Two sizes, editable recipe and physical support comparison](examples/usdcraft_sdk_guide/README.md) | -| Three-level chain reaction | [Editable recipe and reproduction steps](examples/three_level_chain/README.md) · [Film](docs/media/chain-workshop-1080p30.mp4) | -| Precision sorting workshop | [Scene recipe](examples/precision_sorting_corner/README.md) · [Film](docs/media/precision-workshop-1080p30.mp4) | -| Maintenance workbench | [Scene recipe](examples/maintenance_workbench/README.md) · [Film](docs/media/maintenance-workbench-1080p30.mp4) | - -Recipes preserve the selected asset references and scene operations. Acquire the -referenced assets on your own simulation host and use the example's case to -check a new run. +- [build-scene](skills/build-scene/SKILL.md): select assets, prepare roles, + compose a scene, run it, and inspect physical observations. +- [deliver-scene-video](skills/deliver-scene-video/SKILL.md): plan cameras, + inspect native footage, and export a traceable film. -## Remote simulation +Start with a small request: + +> Reproduce the gravity-cell example with its pinned ABO notebook and documented +> table acquisition route. Prepare the notebook as a rigid body and run the +> fall/contact/settling check. +> Enable native capture, inspect the actual result, and deliver the editable scene, a short native +> video, and the verification result. Download only the selected dependencies. + +Then try a composition task: + +> Build a small workshop with a conveyor and collection bins. Find suitable +> assets online, check their scale and dependencies, leave the working areas +> clear, and choose a camera that shows the handoff. Run the scene and improve +> it from the physical observations and images. -The MCP service can run on a GPU workstation while assets, USD files, and caches -stay on that host. Clients receive images, state, and video data. For the -experimental HTTP transport, bind through an SSH tunnel as described in the -[remote setup guide](docs/快速开始.md#远程仿真). A local SSH tunnel has been tested; -cross-machine deployment still needs validation in the target environment. +## Examples + +| Example | What it explores | Recipe and video | +| --- | --- | --- | +| Only one sugar cube | An editable whole-home chain reaction with a separate red-rope control | [Recipe](examples/whole_home_sugar/README.md) · [55s film](docs/media/only-one-sugar-public-55s.mp4) · [20s control](docs/media/red-rope-causal-comparison-20s.mp4) | +| Multi-source kinetic gallery | Several asset roles in one scene; scheduled cabinet motion is identified separately from the passive chain | [Recipe](examples/kinetic_asset_gallery/README.md) · [66s film](docs/media/kinetic-asset-gallery-1080p30.mp4) | +| Cross-catalog gravity cell | Selected asset preparation, physical checks, and reproducible inputs | [Recipe and checks](examples/catalog_gravity_cell/README.md) | +| Three-level chain reaction | A multi-level physical scene | [Recipe](examples/three_level_chain/README.md) · [Film](docs/media/chain-workshop-1080p30.mp4) | +| Precision sorting workshop | Incremental asset and camera layout for an existing compatible three-arm scene | [Incremental recipe](examples/precision_sorting_corner/README.md) · [Film](docs/media/precision-workshop-1080p30.mp4) | +| Maintenance workbench | Industrial asset composition | [Recipe](examples/maintenance_workbench/README.md) · [Film](docs/media/maintenance-workbench-1080p30.mp4) | -## Documentation +Examples retain selected asset references and editable operations. Acquire the +referenced files on your simulation host and check each new run against its +case. A previous example's pass is not reused as a new scene's physical verdict. -- [Quick start / 快速开始](docs/快速开始.md) +## Remote simulation + +Run MCP on a GPU workstation and keep assets, USD files, and caches there. +Clients receive images, state, and video data. The experimental HTTP transport +can use an SSH tunnel; see the [remote guide](docs/快速开始.md#远程仿真). +A local tunnel has been tested; deployment between separate machines still +needs validation in the target environment. + +## Validation and current limits + +- Validation is tied to selected assets, preparation profiles, physical cases, + and recorded environments. Source admission does not certify a whole dataset. +- The public imported-articulation profile admits a canonical two-link, + single-DOF hinge/slider. Robot following and collision checks remain experimental. +- A successful worker exit, a prepared asset, and a verified physical result + are separate outcomes. Native recording checks are also separate from visual review. +- No cross-task token or time advantage has been established. See the + [measured evaluation and limitations](docs/validation/catalog-efficiency.md). + +The [validation guide](docs/validation.md) and +[catalog capability matrix](docs/validation/catalog-capabilities.md) describe +the actual checks and their scope. + +## Documentation and contributing + +- [中文快速开始](docs/快速开始.md) +- [Catalog and asset preparation](docs/asset-catalog.md) +- [Full source registry](docs/assets/SOURCES.md) · [Add a source](docs/assets/ADDING_A_SOURCE.md) +- [Scene recipes](docs/scene-recipes.md) · [Optional generation](docs/asset-generation.md) +- [Cameras and video delivery](docs/视频交付.md) - [Plugin packaging and installation](docs/packaging.md) -- [Cameras, video, and layout](docs/视频交付.md) -- [Optional automatic measured layout](docs/scene-layout.md) -- [Validation scope](docs/validation.md) - [Repository contents and asset distribution](docs/开源发布说明.md) - [Contributing](CONTRIBUTING.md) -SimScene is a development project. Scene plans and successful worker exits need -physical verification against the intended task. Robot following and collision -checks are experimental; their measured scope is described in the validation -documentation. - ## License SimScene code is licensed under [Apache-2.0](LICENSE). Third-party assets retain -their own terms; see [NOTICE](NOTICE). +their own terms and attribution requirements; see [NOTICE](NOTICE), +[source notices](OPEN_SOURCE_NOTICES.md), and the per-source records. diff --git "a/docs/\345\277\253\351\200\237\345\274\200\345\247\213.md" "b/docs/\345\277\253\351\200\237\345\274\200\345\247\213.md" index a611ded..99a7d99 100644 --- "a/docs/\345\277\253\351\200\237\345\274\200\345\247\213.md" +++ "b/docs/\345\277\253\351\200\237\345\274\200\345\247\213.md" @@ -1,55 +1,116 @@ # SimScene 快速开始 -本地开发候选(dev2)提供[单物体首次交付](../examples/first_delivery/README.md),从已安装插件完成选定模型获取、落体检查和原生视频导出。 +SimScene 为智能体提供在线资产检索、可编辑 USD 场景、Isaac Sim 运行和原生视频交付工具。 +可以先查看资源与搜索元数据,再配置仿真主机;不需要预下载完整资产库。 -SimScene 将在线资产发现、可编辑 USD 场景、Isaac Sim 运行和影片制作接入智能体。 -先在仿真主机上完成安装,再按需选择资产;不需要预下载完整资产库。 +开发分支可运行[单物体首次交付](../examples/first_delivery/README.md),使用自建台面,完成 +选定模型获取、物理检查和 4 秒原生录像。安装方式见[插件打包与安装](packaging.md)。 -## 安装 +下文的公开版命令固定使用预览版 **v0.2.0-dev.1**。支持来源见 +[README 资源表](../README.md#supported-asset-sources)和 +[完整来源清单](assets/SOURCES.md)。来源可检索、模型能准备、物理实验通过是不同结果。 -需要 Python 3.10 或以上版本。真实仿真需要兼容的 NVIDIA Isaac Sim 和 GPU; -录像与剪辑需要 FFmpeg,具体要求见[视频接口](视频交付.md)。 +## 1. 安装基础包,先搜索元数据 + +需要 Python 3.10 或以上版本及网络。下面的目录查询不会启动 Isaac Sim,也不要求先安装 GLB 解码器。 ```bash -git clone https://github.com/ros-claw/simscene.git +git clone --branch v0.2.0-dev.1 https://github.com/ros-claw/simscene.git cd simscene python3 -m venv .venv . .venv/bin/activate -python -m pip install -e . usd-core -simscene configure --isaac-python /absolute/path/to/isaac-sim/python.sh -simscene doctor +python -m pip install -e . + +simscene catalog sources +simscene catalog search 'notebook' --source abo-glb --limit 4 +simscene recipe list +``` + +首次查询可能读取有限大小的固定版本元数据索引;选中并准备对象后才获取模型与依赖。 +预览图是独立操作。默认来源为 NVIDIA USD Search、ABO GLB 和 GSO GLB; +USDCraft、Poly Haven 等来源需要显式选择,例如: + +```bash +simscene catalog search 'cabinet' --source usdcraft --limit 4 ``` -机器人 IK 的附加依赖可通过 `python -m pip install -e '.[ik]'` 安装。 -路径应填写当前仿真主机的实际位置。 +Hugging Face 仓库发现返回候选资源,不会自动把新仓库加入受支持来源,也不代表其中所有模型可直接仿真。 -## 在线选材 +## 2. 配置仿真和准备环境 + +| 操作 | 额外环境要求 | +|---|---| +| 本地 USD 检查与场景导出 | SimScene Python 环境中的兼容 USD bindings | +| 真实物理与原生渲染 | 兼容的 NVIDIA Isaac Sim 和 GPU 主机 | +| 已验证的 ABO/GSO GLB 准备 | Isaac 资产转换器、规定版本的 Node.js/npm 与解码器、成功的 preparation probe | +| 录像与剪辑 | 带 H.264 编码及 `zscale` 支持的 FFmpeg/ffprobe,见[视频接口](视频交付.md) | ```bash -simscene search 'industrial conveyor' -simscene inspect 'ASSET_URL_FROM_SEARCH' -simscene acquire 'ASSET_URL_FROM_SEARCH' +python -m pip install usd-core +simscene configure --isaac-python /absolute/path/to/isaac-sim/python.sh +simscene doctor ``` -默认连接 NVIDIA 公共 USD Search。搜索阶段获取候选、元数据和预览,选中后 -才获取所用资产及依赖。检查获取结果的依赖状态与上游许可;`root` 是仿真端 -资产路径。`USD_SEARCH_API_URL` 可替换服务地址,`SIMSCENE_CACHE` 可设置缓存目录。 +路径填写当前仿真主机的实际位置。`doctor` 检查配置,不启动仿真,也不能代替转换环境验证。 +公开记录的 catalog/preparation 环境是 Isaac Sim **6.2.0-rc.14**、OpenUSD **0.25.11**; +其他版本需要单独核对兼容性。 + +准备 GLB 之前,按照[资产准备说明](asset-catalog.md#configure-the-preparation-runtime-explicitly) +配置 Node.js **22.23.2**、npm 和锁定解码器,再运行 `simscene asset probe`。 +该 probe 会启动 SDK 应用、记录转换器能力,但不推进物理步。 +`asset setup-decoder` 不负责安装 Node 本身。 + +机器人 IK 的附加依赖可通过 `python -m pip install -e '.[ik]'` 安装;普通元数据搜索不需要它。 +预构建客户端包为 Linux x86_64/Python 3.10,对应 wheel 和迁移方法见[插件安装说明](packaging.md)。 -## 接入智能体 +## 3. 先复现一个小实验 -在安装好的虚拟环境中运行 `simscene mcp`,或按 -[插件安装说明](packaging.md)配置客户端的 stdio MCP 服务。 -[build-scene](../skills/build-scene/SKILL.md) 引导选材、测量、组合、运行和观察; -[deliver-scene-video](../skills/deliver-scene-video/SKILL.md) 引导镜头与视频交付。 +[跨目录重力单元](../examples/catalog_gravity_cell/README.md)包含固定 ABO 笔记本道具的 +单物体检查和四实例场景。它保存资产身份、准备参数和物理 case,适合先检查跌落、接触与稳定。 -可以直接提出开放场景目标,例如:“搭建一个带传送带和收集箱的小工坊, -在线寻找合适资产,运行后检查交接,再调整镜头使动作清楚可见。” +这个示例同时使用 NVIDIA 工作台,工作台走原有获取路径,其个体许可仍未明确,碰撞支撑使用显式代理。 +请先阅读示例说明;不要把它当成任意 ABO/GSO 模型的一键仿真入口。默认检查也不等于已经录制正式影片。 -复现现有作品时使用示例配方,避免从文字重新搭建: +需要复现其他作品时,使用已有配方: [连锁工坊](../examples/three_level_chain/README.md)、 -[精密分拣](../examples/precision_sorting_corner/README.md)、 +[多来源动态展厅](../examples/kinetic_asset_gallery/README.md)、 [维修工作台](../examples/maintenance_workbench/README.md)。 -先获取资源锁中的所选资产,再导入普通场景操作,并使用示例的 case 验证新运行。 +[精密分拣配方](../examples/precision_sorting_corner/README.md)是已有兼容三臂场景的增量布景, +需要原机器人、控制器、工件和 case,不能从空场景独立重建完整三臂系统。 + +先获取资源锁中的所选资产,再应用场景操作,并使用对应 case 验证新运行;不沿用旧运行的物理通过结论。 + +## 4. 接入智能体 + +在安装好的虚拟环境中运行 `simscene mcp`,或按[插件安装说明](packaging.md) +配置客户端的 stdio MCP 服务。注册 MCP 和安装技能是两个步骤;使用匹配版本的: + +- [build-scene](../skills/build-scene/SKILL.md):选材、准备、测量、组合、运行和观察。 +- [deliver-scene-video](../skills/deliver-scene-video/SKILL.md):相机、原生画面审阅与视频交付。 + +Isaac 路径、GLB 解码器和缓存配置应在实际启动 MCP 的环境中可见,另一个终端里的环境变量不一定会被客户端继承。 +安装包和客户端的验证范围见[客户端表](../README.md#connect-your-agent); +Claude/DeepSeek 的加载检查不等于真实模型已经完成端到端场景任务。 + +第一条提示可以使用: + +> 复现 gravity-cell 示例,使用锁定的 ABO 笔记本道具和文档说明的 NVIDIA 工作台获取路径, +> 检查真实跌落、接触和稳定结果。明确启用原生录像,查看实际画面,交付可编辑场景、短视频和验证结果。 + +## 原有 NVIDIA USD 选材入口 + +已有原生 USD 工作流可以继续使用: + +```bash +simscene search 'industrial conveyor' +simscene inspect 'ASSET_URL_FROM_SEARCH' +simscene acquire 'ASSET_URL_FROM_SEARCH' +``` + +默认连接 NVIDIA 公共 USD Search。这个旧 `search` 入口默认请求内联预览; +需要只查元数据时使用前面的 `catalog search`。选中后获取所用资产及依赖, +并检查依赖状态与上游许可。`root` 是仿真端资产路径。 +`USD_SEARCH_API_URL` 可替换兼容服务地址,`SIMSCENE_CACHE` 可设置缓存目录。 ## 远程仿真 @@ -70,5 +131,6 @@ ssh -L 8765:127.0.0.1:8765 USER@SIMULATION_HOST ## 验证与使用范围 场景规划、worker 正常退出和物理任务成功需要分别判断。检查实际观测、接触、 -目标状态和必要的负对照,完整测试范围见 [validation.md](validation.md)。 +目标状态和必要的负对照,完整范围见 [validation.md](validation.md)和 +[资产能力记录](validation/catalog-capabilities.md)。 自有代码及第三方资源分发范围见[开源发布说明](开源发布说明.md)。 From 82e01fb1e5d3ef569779e9bcd916afa80a1aad29 Mon Sep 17 00:00:00 2001 From: shaoxiang <519517384@qq.com> Date: Wed, 25 Nov 2026 15:50:04 +0800 Subject: [PATCH 18/20] Qualify first delivery with bounded client turns and bound artifacts --- examples/first_delivery/README.md | 23 ++ experiments/qualify_first_delivery.py | 240 ++++++++++++++++++ skills/build-scene/SKILL.md | 2 +- .../references/integration-workspace.md | 9 + src/simscene/recipes/cabinet_mcp_workflow.py | 22 +- src/simscene/recipes/first_delivery.py | 16 +- tests/test_cabinet_mcp_workflow.py | 30 ++- tests/test_first_delivery_qualification.py | 62 +++++ 8 files changed, 391 insertions(+), 13 deletions(-) create mode 100644 experiments/qualify_first_delivery.py create mode 100644 tests/test_first_delivery_qualification.py diff --git a/examples/first_delivery/README.md b/examples/first_delivery/README.md index e4da532..370e77c 100644 --- a/examples/first_delivery/README.md +++ b/examples/first_delivery/README.md @@ -60,3 +60,26 @@ python3 "$PLUGIN/experiments/run_first_delivery.py" --output "$WORK/output" --re The reviewed receipt binds the declaration to the checked movie and can reach `ready_for_submission`. The eventual submission belongs to the client or host that requested the work. This example verifies a fixed asset and configuration. + +## Qualified host-assisted Codex route + +From the source checkout, a host with a configured Codex CLI login can use +the first-delivery qualification driver. Use a fresh attempt directory and +the same runtime setup as above. + +~~~sh +python3 experiments/qualify_first_delivery.py --plugin "$PLUGIN" --wheel "$WHEEL" \ + --output "$WORK/qualification" --model YOUR_CODEX_MODEL +~~~ + +The host admits one discovery turn, runs the installed MCP workflow outside +model turns, and admits a separate visual review only after physical and media +checks pass. It preserves observed token usage and writes a submission only +within the wall and token limits. The allowance governs client turn admission +and observed use. Reports cannot enforce unreported in-flight provider usage. +Visual qualification uses two ordered frame strips tied to the checked video. + +The export destination should be on a local filesystem that supports hard +links. After worker or host failure, use the job record as the completion +authority. An uncertain status leaves any remaining files available for +diagnosis. diff --git a/experiments/qualify_first_delivery.py b/experiments/qualify_first_delivery.py new file mode 100644 index 0000000..9317ee8 --- /dev/null +++ b/experiments/qualify_first_delivery.py @@ -0,0 +1,240 @@ +"""Run a bounded real-Codex first delivery with host-owned job waiting.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import time + +from pilot_usage import collect, normalize, rows + + +class Budget: + """Reserve observable client turns before launching them.""" + + def __init__(self, total, per_turn): + if not 0 < per_turn <= total: + raise ValueError('positive turn allowance within the total is required') + self.total = total + self.per_turn = per_turn + self.spent = 0 + self.in_flight = None + self.ledger = [] + + def admit(self, phase, *, later_turns): + if self.in_flight is not None or self.spent + self.per_turn*(1+later_turns) > self.total: + raise ValueError('model turn would exceed the remaining allowance') + self.in_flight = phase + self.ledger.append({'event': 'admitted', 'phase': phase, 'unix_ns': time.time_ns(), + 'spent_tokens': self.spent, 'reserved_tokens': self.per_turn, + 'later_turns_reserved': later_turns*self.per_turn}) + + def settle(self, phase, usage): + if self.in_flight != phase or usage is None: + raise ValueError('the admitted turn must provide actual usage') + usage = normalize(usage) + self.in_flight = None + self.spent += usage['total_tokens'] + self.ledger.append({'event': 'settled', 'phase': phase, 'unix_ns': time.time_ns(), + 'usage': usage, 'spent_tokens': self.spent}) + if usage['total_tokens'] > self.per_turn or self.spent > self.total: + raise ValueError('a completed turn exceeded its token allowance') + + +def read(path): + return json.loads(path.read_text()) + + +def sha(path): + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def write(path, value): + with path.open('x', encoding='utf-8') as stream: + json.dump(value, stream, ensure_ascii=False, indent=2) + stream.write('\n') + + +def remaining(deadline): + seconds = deadline - time.monotonic() + if seconds <= 0: + raise TimeoutError('delivery deadline reached') + return seconds + + +def object_schema(**fields): + return {'type': 'object', 'properties': fields, 'required': list(fields), 'additionalProperties': False} + + +def model_turn(root, phase, prompt, schema, model, budget, deadline, *, later_turns, images=()): + budget.admit(phase, later_turns=later_turns) + schema_path = root/f'{phase}.schema.json' + final = root/f'{phase}.json' + write(schema_path, schema) + (root/f'{phase}.txt').write_text(prompt) + command = [ + 'codex', 'exec', '--ignore-user-config', '--ephemeral', '--skip-git-repo-check', + '--disable', 'shell_tool', '--disable', 'apps', '--disable', 'multi_agent', + '--disable', 'multi_agent_v2', '-c', 'web_search="disabled"', '--sandbox', 'read-only', + '--model', model, '--json', '--output-schema', str(schema_path), '-o', str(final), + ] + for image in images: + command.extend(('--image', str(image))) + events = root/f'{phase}.jsonl' + with events.open('xb') as out, (root/f'{phase}.stderr').open('xb') as err: + process = subprocess.run(command+['-'], input=prompt.encode(), cwd=root, stdout=out, stderr=err, + timeout=min(120, remaining(deadline))) + report = collect(events) + write(root/f'{phase}-usage.json', report) + parsed, _ = rows(events) + completed = [event for _, event in parsed if event.get('type') == 'turn.completed'] + if len(completed) != 1: + raise ValueError(f'{phase} did not produce one complete model turn') + budget.settle(phase, report['aggregate_reported_usage']) + if process.returncode or not final.is_file(): + raise ValueError(f'{phase} failed; see its retained CLI output') + for _, event in parsed: + if event.get('type') == 'item.completed' and event.get('item', {}).get('type') not in ( + 'reasoning', 'agent_message'): + raise ValueError(f'{phase} used a tool outside the fixed model turn') + remaining(deadline) + return read(final) + + +def media_strips(video, root, deadline): + """Attach ordered thumbnails of the actual action and settled result.""" + from PIL import Image, ImageDraw + + w, h = 384, 216 + raw = subprocess.check_output([ + 'ffmpeg', '-hide_banner', '-loglevel', 'error', '-threads', '2', '-i', str(video), + '-vf', f'scale={w}:{h},format=rgb24', '-f', 'rawvideo', '-', + ], timeout=remaining(deadline)) + frame_bytes = w*h*3 + if len(raw) != 120*frame_bytes: + raise ValueError('expected the complete 120-frame delivery') + strips = [] + for name, indices in (('fall', [0, 2, 4, 5, 6, 7, 8, 10, 14]), ('settled', [60, 74, 89, 104, 119])): + sheet = Image.new('RGB', (3*w, ((len(indices)+2)//3)*(h+20)), '#151d24') + ink = ImageDraw.Draw(sheet) + for slot, index in enumerate(indices): + body = raw[index*frame_bytes:(index+1)*frame_bytes] + x, y = (slot%3)*w, (slot//3)*(h+20) + sheet.paste(Image.frombytes('RGB', (w, h), body), (x, y+20)) + ink.text((x+9, y+3), f'frame {index:03d} {index/30:.2f}s', fill='white') + path = root/f'{name}.jpg' + sheet.save(path, quality=90) + strips.append(path) + return strips + + +def engine(plugin, root, arguments, deadline, log): + env = dict(os.environ, PYTHONPATH=str(plugin/'server/vendor')) + with (root/log).open('xb') as stream: + subprocess.run([sys.executable, str(plugin/'experiments/run_first_delivery.py'), *arguments], + stdout=stream, stderr=subprocess.STDOUT, check=True, env=env, + timeout=remaining(deadline)) + + +def qualify(args, root, budget, deadline): + plugin, wheel = Path(args.plugin).resolve(), Path(args.wheel).resolve() + package = read(plugin/'server/build-info.json') + if package['source_clean'] is not True or package['wheel_sha256'] != sha(wheel): + raise ValueError('qualification requires an installed package matching a clean-source wheel') + recipes = read(plugin/'server/vendor/simscene/recipes/data/fixed-examples.json')['examples'] + candidates = {item['id']: item['description'] for item in recipes} + chosen = read(plugin/'examples/first_delivery/assets.lock.json')['assets']['box']['source_ref'] + text = {'type': 'string'} + plan = model_turn( + root, 'discover', + 'Select the fixed installed SimScene example that uses one scanned external object, ' + 'an editable worktop and a short verified gravity-drop video. Choose from this actual installed recipe list. ' + 'Return the recipe ID and a short reason. Recipes: '+json.dumps(candidates), + object_schema(recipe_id={'type': 'string', 'enum': list(candidates)}, reason=text), + args.model, budget, deadline, later_turns=1, + ) + if plan.get('recipe_id') != 'first_delivery': + raise ValueError('the client did not select the fixed novice recipe') + delivery = root/'delivery' + engine(plugin, root, ['--wheel', str(wheel), '--output', str(delivery)], deadline, 'engine.log') + receipt = read(delivery/'delivery.json') + if receipt['status'] != 'needs_visual_review' or receipt['physical_status'] != 'passed' or receipt['media_status'] != 'passed': + raise ValueError('verified physical and media delivery is required before the review turn') + video = Path(receipt['video']) + if sha(video) != receipt['video_sha256']: + raise ValueError('the video differs from the checked delivery') + images = media_strips(video, root, deadline) + review_answer = model_turn( + root, 'review', + 'Independently inspect the two attached images from one actual 4-second SimScene video. Read the nine ordered early frames ' + '(0 to 0.47 s) and the five ordered late frames (2 to 3.97 s). ' + 'Describe the visible object and support, how their relative positions change, and whether the final placement is stable. ' + 'If you cannot read either image or the claimed action is obscured, return change_needed. ' + 'Use specific visible cues in each observation; do not infer physics sensor results from pixels.', + object_schema(decision={'type': 'string', 'enum': ['accept', 'change_needed']}, + fall_observation=text, settled_observation=text), + args.model, budget, deadline, later_turns=0, images=images, + ) + review = { + 'reviewer': f'Independent Codex {args.model}', 'decision': review_answer['decision'], + 'video_sha256': receipt['video_sha256'], 'mode': 'ordered attached source-frame strips', + 'reviewed_windows': [ + {'start_s': 0, 'end_s': .5, 'observation': review_answer['fall_observation']}, + {'start_s': 2, 'end_s': 4, 'observation': review_answer['settled_observation']}, + ], + 'attachments': [{'path': str(image), 'sha256': sha(image)} for image in images], + } + review_path = root/'attributed-review.json' + write(review_path, review) + engine(plugin, root, ['--output', str(delivery), '--review', str(review_path)], deadline, 'review-record.log') + verified = read(delivery/'reviewed-delivery.json') + if verified['status'] != 'ready_for_submission': + raise ValueError('the independent client did not accept the visible result') + remaining(deadline) + result = {'schema': 'simscene.first_delivery_qualification.v1', 'status': 'submitted', + 'source_commit': package['source_commit'], 'wheel_sha256': package['wheel_sha256'], + 'selection': chosen, 'model': args.model, 'model_observed_tokens': budget.spent, + 'reviewed_receipt': str(delivery/'reviewed-delivery.json'), + 'reviewed_receipt_sha256': sha(delivery/'reviewed-delivery.json'), + 'video_sha256': receipt['video_sha256'], 'submitted_unix_ns': time.time_ns(), + 'scope': 'Two fresh Codex turns with host-run installed MCP engineering between them. Independent attached-frame review.'} + write(root/'submission.json', result) + return result + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--plugin', required=True) + parser.add_argument('--wheel', required=True) + parser.add_argument('--output', required=True, help='new directory for exactly one attempt') + parser.add_argument('--model', required=True) + parser.add_argument('--wall-seconds', type=float, default=900) + parser.add_argument('--total-tokens', type=int, default=150000) + parser.add_argument('--turn-allowance', type=int, default=60000) + args = parser.parse_args() + if not 0 < args.wall_seconds <= 3600: + parser.error('wall-seconds must be positive and at most 3600') + budget = Budget(args.total_tokens, args.turn_allowance) + root = Path(args.output).resolve() + root.mkdir(parents=True, exist_ok=False) + start = time.monotonic() + write(root/'contract.json', {'model': args.model, 'wall_seconds': args.wall_seconds, + 'token_limit': args.total_tokens, 'turn_allowance': args.turn_allowance, + 'start_unix_ns': time.time_ns(), + 'usage_scope': 'Admission applies before each host-controlled Codex turn. Internal provider requests and unreported in-flight usage are outside this gate.'}) + try: + result = qualify(args, root, budget, start+args.wall_seconds) + except (OSError, ValueError, KeyError, TypeError, subprocess.SubprocessError) as error: + result = {'status': 'incomplete', 'error': str(error), 'directory': str(root)} + result['wall_s'] = time.monotonic()-start + result['model_observed_tokens'] = budget.spent + write(root/'summary.json', result) + write(root/'budget-ledger.json', budget.ledger) + print(json.dumps(result, indent=2, ensure_ascii=False)) + return 0 if result['status'] == 'submitted' else 2 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/skills/build-scene/SKILL.md b/skills/build-scene/SKILL.md index 0972835..6706c94 100644 --- a/skills/build-scene/SKILL.md +++ b/skills/build-scene/SKILL.md @@ -3,7 +3,7 @@ name: build-scene description: Discover online simulation assets, compose editable scenes with measured support relationships, run Isaac Sim and improve the result from camera and physical observations. --- -For a first verified delivery, use the installed [one-object example](../../examples/first_delivery/README.md). +For a first verified delivery, follow [the one-object setup](references/integration-workspace.md#first-delivery). Choose reproduction, modification or original construction first. Reproduce a locked recipe directly; test changed interfaces locally; build new mechanisms diff --git a/skills/build-scene/references/integration-workspace.md b/skills/build-scene/references/integration-workspace.md index a9439ad..96fac01 100644 --- a/skills/build-scene/references/integration-workspace.md +++ b/skills/build-scene/references/integration-workspace.md @@ -1,5 +1,14 @@ # Fixed integration examples +## First delivery + +Read the installed package path from the skill's .simscene-plugin-root +marker, then open examples/first_delivery/README.md in that package. A skill +loaded in place is already within the package's skills directory. The example +runs one locked GSO box on a primitive worktop and retains its physical check +and native video. Use the installed helper for long-running work. + + Read `simscene://recipes/examples` or `simscene recipe list` to discover model-free examples. These are fixed scene inputs, separate from the role recipes accepted by `scene_compile_recipe`. The registry describes earlier diff --git a/src/simscene/recipes/cabinet_mcp_workflow.py b/src/simscene/recipes/cabinet_mcp_workflow.py index 9a68a52..bf5e9e5 100644 --- a/src/simscene/recipes/cabinet_mcp_workflow.py +++ b/src/simscene/recipes/cabinet_mcp_workflow.py @@ -203,23 +203,31 @@ async def wait_for_export(journal, root, request, resume, *, collect_only=False) request_path = root/'video-request.json' job_id = export_job_id(request['request_id']) - if not request_path.exists(): + if request_path.exists(): + if not resume or json.loads(request_path.read_text()) != request: + raise WorkflowError('existing video request differs or recovery was not requested') + else: if collect_only: raise WorkflowError('no saved video export request; collection cannot start a new job') _write(request_path, request) + if not collect_only: + # The exact request is safe if its original reply or dispatch was lost. handle = await journal.call('video_export_start', request) if handle.get('job_id') != job_id: raise WorkflowError('export job ID differs from the saved request') - _write(root/'video-job.json', handle) - elif not resume or json.loads(request_path.read_text()) != request: - raise WorkflowError('existing video request differs or recovery was not requested') + receipt = root/'video-job.json' + if not receipt.exists(): + _write(receipt, handle) # A lost start response still identifies the same durable reservation. actual = await wait_for_job(journal, job_id, _next_path(root/'video-wait.json'), 1800) movie = Path(request['destination']) result = actual.get('result') or {} - if (actual.get('job_id') != job_id or result.get('video') != str(movie) - or result.get('edit_map') != str(movie.with_suffix('.edit.json'))): - raise WorkflowError('export job does not match the requested movie and edit map') + edit = movie.with_suffix('.edit.json') + if (actual.get('job_id') != job_id or actual.get('completion_confirmed') is not True + or result.get('video') != str(movie) or result.get('edit_map') != str(edit) + or not movie.is_file() or not edit.is_file() + or result.get('video_sha256') != _sha(movie) or result.get('edit_map_sha256') != _sha(edit)): + raise WorkflowError('export files do not match the completed durable export') return actual diff --git a/src/simscene/recipes/first_delivery.py b/src/simscene/recipes/first_delivery.py index c0447b4..3907dc0 100644 --- a/src/simscene/recipes/first_delivery.py +++ b/src/simscene/recipes/first_delivery.py @@ -64,7 +64,13 @@ async def run(session, plugin, wheel, root, scene_id, resume=False, *, collect_o 'include_overlap_candidates': True}) if (await journal.call('scene_validate', {'scene_id': scene_id})).get('issues') != []: raise WorkflowError('scene validation reported issues; see the saved MCP response') - freeze_case_file(example/'case.json', root/'bindings.json', lock_path, root/'case.json') + frozen = freeze_case_file(example/'case.json', root/'bindings.json', lock_path, root/'case.json') + _write(root/'case-freeze.json', frozen) + case_path = root/'case.json' + frozen = _read(root/'case-freeze.json') + case_digest = _sha(case_path) + if frozen.get('case_sha256') != case_digest or frozen.get('template_sha256') != _sha(example/'case.json'): + raise WorkflowError('the case or packaged template differs from the saved freeze') request = {'scene_id': scene_id, 'steps': STEPS, 'seed': 42, 'case_path': str(root/'case.json'), 'request_id': scene_id+'-physics'} request_path = root/'physics-request.json' @@ -89,6 +95,8 @@ async def run(session, plugin, wheel, root, scene_id, resume=False, *, collect_o if run_directory.name != job['run_id']: raise WorkflowError('physics job and completed run do not match') check_run_scene(scene, run_directory) + if _read(run_directory/'run-lock.json').get('acceptance_case_sha256') != case_digest: + raise WorkflowError('the verified run does not contain the saved frozen case') check_path = _next_path(root/'physical-check.json') checked = await journal.call('run_verify', {'job_id': job_id, 'case_type': 'rigid_asset_smoke'}) _write(check_path, checked) @@ -111,7 +119,9 @@ async def run(session, plugin, wheel, root, scene_id, resume=False, *, collect_o result = {'schema': 'simscene.first_delivery.v1', 'status': 'needs_visual_review', 'physical_status': 'passed', 'media_status': 'passed', 'visual_review': 'pending', 'physics_job_id': job_id, 'run_id': run_directory.name, 'export_job_id': exported['job_id'], - 'scene': str(root/'scene.json'), 'video': str(movie), 'edit_map': str(edit), + 'scene': str(root/'scene.json'), 'scene_sha256': _sha(root/'scene.json'), + 'case': str(case_path), 'case_sha256': case_digest, + 'video': str(movie), 'edit_map': str(edit), 'video_sha256': _sha(movie), 'edit_map_sha256': _sha(edit), 'check': str(check_path), 'check_sha256': _sha(check_path), 'inspection': str(inspection_path)} result_path = _next_path(root/'delivery.json') @@ -129,6 +139,8 @@ def record_review(directory, review_file): if (receipt.get('schema') != 'simscene.first_delivery.v1' or receipt.get('status') != 'needs_visual_review' or receipt.get('physical_status') != 'passed' or receipt.get('media_status') != 'passed' or Path(receipt['video']).resolve() != movie or Path(receipt['edit_map']).resolve() != edit + or Path(receipt['scene']).resolve() != root/'scene.json' or _sha(root/'scene.json') != receipt['scene_sha256'] + or Path(receipt['case']).resolve() != root/'case.json' or _sha(root/'case.json') != receipt['case_sha256'] or checked.parent != root or _sha(checked) != receipt['check_sha256'] or _read(checked).get('passed') is not True or _sha(movie) != receipt['video_sha256'] or _sha(edit) != receipt['edit_map_sha256']): raise WorkflowError('delivery artifacts differ from the technical receipt') diff --git a/tests/test_cabinet_mcp_workflow.py b/tests/test_cabinet_mcp_workflow.py index 9a9ed44..6557cf1 100644 --- a/tests/test_cabinet_mcp_workflow.py +++ b/tests/test_cabinet_mcp_workflow.py @@ -144,15 +144,18 @@ def test_video_recovery_reuses_job_status_after_losing_the_start_response(tmp_pa movie = tmp_path/'technical.mp4' edit = movie.with_suffix('.edit.json') + movie.write_bytes(b'checked native output') + edit.write_text('{}') request = {'destination': str(movie), 'request_id': 'cabinet-video', 'segments': [{'camera': 'overview'}], 'output_resolution': [1920, 1080]} mod._write(tmp_path/'video-request.json', request) expected_job = export_job_id(request['request_id']) lost = Session([Result({'state': 'completed'}), - Result({'job_id': expected_job, 'state': 'completed', - 'result': {'video': str(movie), 'edit_map': str(edit)}})]) + Result({'job_id': expected_job, 'state': 'completed', 'completion_confirmed': True, + 'result': {'video': str(movie), 'edit_map': str(edit), + 'video_sha256': mod._sha(movie), 'edit_map_sha256': mod._sha(edit)}})]) journal = mod.MCPJournal(lost, tmp_path) - assert asyncio.run(mod.wait_for_export(journal, tmp_path, request, resume=True))['job_id'] == expected_job + assert asyncio.run(mod.wait_for_export(journal, tmp_path, request, resume=True, collect_only=True))['job_id'] == expected_job assert [name for name, _ in lost.calls] == ['job_status', 'job_status'] assert {args['job_id'] for _, args in lost.calls} == {expected_job} @@ -166,3 +169,24 @@ def test_collection_does_not_start_an_export_without_a_saved_request(tmp_path): asyncio.run(mod.wait_for_export(journal, tmp_path, request, resume=True, collect_only=True)) assert session.calls == [] assert not (tmp_path/'video-request.json').exists() + + +def test_resume_replays_a_reserved_request_that_never_reached_the_server(tmp_path): + mod = module() + from simscene.video_export_jobs import export_job_id + + movie = tmp_path/'technical.mp4' + request = {'destination': str(movie), 'request_id': 'cabinet-video', + 'segments': [{'camera': 'overview'}], 'output_resolution': [1920, 1080]} + mod._write(tmp_path/'video-request.json', request) + job_id = export_job_id(request['request_id']) + edit = movie.with_suffix('.edit.json') + movie.write_bytes(b'checked native output') + edit.write_text('{}') + session = Session([Result({'job_id': job_id}), Result({'state': 'completed'}), + Result({'job_id': job_id, 'state': 'completed', 'completion_confirmed': True, 'result': { + 'video': str(movie), 'edit_map': str(edit), + 'video_sha256': mod._sha(movie), 'edit_map_sha256': mod._sha(edit)}})]) + journal = mod.MCPJournal(session, tmp_path) + assert asyncio.run(mod.wait_for_export(journal, tmp_path, request, resume=True))['job_id'] == job_id + assert session.calls[0] == ('video_export_start', request) diff --git a/tests/test_first_delivery_qualification.py b/tests/test_first_delivery_qualification.py new file mode 100644 index 0000000..a3ca5ad --- /dev/null +++ b/tests/test_first_delivery_qualification.py @@ -0,0 +1,62 @@ +"""Regression checks for admission and terminal accounting of hosted turns.""" +import importlib.util +from pathlib import Path + +import pytest + + +def host(monkeypatch): + file = Path(__file__).resolve().parents[1]/'experiments/qualify_first_delivery.py' + monkeypatch.syspath_prepend(str(file.parent)) + spec = importlib.util.spec_from_file_location('first_delivery_qualification', file) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def test_discovery_cannot_consume_the_allowance_reserved_for_review(monkeypatch): + h = host(monkeypatch) + limit = h.Budget(total=150, per_turn=60) + with pytest.raises(ValueError, match='allowance'): + limit.admit('discover', later_turns=2) + limit.admit('discover', later_turns=1) + limit.settle('discover', {'input_tokens': 37, 'cached_input_tokens': 30, 'output_tokens': 3}) + limit.admit('review', later_turns=0) + limit.settle('review', {'input_tokens': 41, 'cached_input_tokens': 0, 'output_tokens': 2}) + assert limit.spent == 83 + + +def test_missing_or_excess_usage_cannot_borrow_the_next_turn_allowance(monkeypatch): + h = host(monkeypatch) + limit = h.Budget(total=100, per_turn=50) + limit.admit('discover', later_turns=1) + with pytest.raises(ValueError, match='usage'): + limit.settle('discover', None) + with pytest.raises(ValueError, match='allowance'): + limit.settle('discover', {'input_tokens': 51, 'output_tokens': 1}) + assert limit.spent == 52 + + +def test_review_rejects_a_changed_case_even_when_video_hashes_match(tmp_path): + from simscene.recipes.first_delivery import record_review, WorkflowError + from simscene.recipes.cabinet_mcp_workflow import _sha, _write + + files = {'scene': tmp_path/'scene.json', 'case': tmp_path/'case.json', + 'video': tmp_path/'first-delivery.mp4', 'edit_map': tmp_path/'first-delivery.edit.json', + 'check': tmp_path/'physical-check.json'} + for path in files.values(): + path.write_text('{"passed":true}') + _write(tmp_path/'delivery.json', { + 'schema': 'simscene.first_delivery.v1', 'status': 'needs_visual_review', + 'physical_status': 'passed', 'media_status': 'passed', + **{k: str(p) for k, p in files.items()}, **{k+'_sha256': _sha(p) for k, p in files.items()}, + }) + review = tmp_path/'review.json' + _write(review, {'decision': 'accept', 'reviewer': 'Test reviewer', 'video_sha256': _sha(files['video']), + 'reviewed_windows': [{'start_s': 0, 'end_s': 4, 'observation': 'Clear fall and settled box.'}]}) + files['case'].write_text('{"passed":false}') + with pytest.raises(WorkflowError, match='artifacts differ'): + record_review(tmp_path, review) + assert not (tmp_path/'reviewed-delivery.json').exists() + files['case'].write_text('{"passed":true}') + assert record_review(tmp_path, review)['status'] == 'ready_for_submission' From 778871f9b0f93e4035675714ddba09e3a68466c7 Mon Sep 17 00:00:00 2001 From: shaoxiang <519517384@qq.com> Date: Wed, 25 Nov 2026 15:52:29 +0800 Subject: [PATCH 19/20] Reject incomplete turn logs and late submission writes --- experiments/qualify_first_delivery.py | 41 +++++++++++++++++----- tests/test_first_delivery_qualification.py | 29 +++++++++++++++ 2 files changed, 61 insertions(+), 9 deletions(-) diff --git a/experiments/qualify_first_delivery.py b/experiments/qualify_first_delivery.py index 9317ee8..4983f00 100644 --- a/experiments/qualify_first_delivery.py +++ b/experiments/qualify_first_delivery.py @@ -68,6 +68,35 @@ def object_schema(**fields): return {'type': 'object', 'properties': fields, 'required': list(fields), 'additionalProperties': False} +def require_fixed_turn(events, invalid_lines, phase): + if invalid_lines or any(not isinstance(event, dict) for _, event in events): + raise ValueError(f'{phase} contains an invalid CLI event') + if sum(event.get('type') == 'turn.completed' for _, event in events) != 1: + raise ValueError(f'{phase} did not produce one complete model turn') + for _, event in events: + if event.get('type') in ('item.started', 'item.updated', 'item.completed'): + item = event.get('item') + if not isinstance(item, dict) or item.get('type') not in ('reasoning', 'agent_message'): + raise ValueError(f'{phase} used a tool outside the fixed model turn') + + +def publish_submission(root, result, deadline): + staged = root/'submission.pending.json' + final = root/'submission.json' + write(staged, result) + with staged.open('rb') as stream: + os.fsync(stream.fileno()) + try: + remaining(deadline) + os.replace(staged, final) + remaining(deadline) + except TimeoutError: + final.unlink(missing_ok=True) + staged.unlink(missing_ok=True) + write(root/'submission-late.json', {**result, 'status': 'late'}) + raise + + def model_turn(root, phase, prompt, schema, model, budget, deadline, *, later_turns, images=()): budget.admit(phase, later_turns=later_turns) schema_path = root/f'{phase}.schema.json' @@ -86,19 +115,13 @@ def model_turn(root, phase, prompt, schema, model, budget, deadline, *, later_tu with events.open('xb') as out, (root/f'{phase}.stderr').open('xb') as err: process = subprocess.run(command+['-'], input=prompt.encode(), cwd=root, stdout=out, stderr=err, timeout=min(120, remaining(deadline))) + parsed, invalid = rows(events) + require_fixed_turn(parsed, invalid, phase) report = collect(events) write(root/f'{phase}-usage.json', report) - parsed, _ = rows(events) - completed = [event for _, event in parsed if event.get('type') == 'turn.completed'] - if len(completed) != 1: - raise ValueError(f'{phase} did not produce one complete model turn') budget.settle(phase, report['aggregate_reported_usage']) if process.returncode or not final.is_file(): raise ValueError(f'{phase} failed; see its retained CLI output') - for _, event in parsed: - if event.get('type') == 'item.completed' and event.get('item', {}).get('type') not in ( - 'reasoning', 'agent_message'): - raise ValueError(f'{phase} used a tool outside the fixed model turn') remaining(deadline) return read(final) @@ -200,7 +223,7 @@ def qualify(args, root, budget, deadline): 'reviewed_receipt_sha256': sha(delivery/'reviewed-delivery.json'), 'video_sha256': receipt['video_sha256'], 'submitted_unix_ns': time.time_ns(), 'scope': 'Two fresh Codex turns with host-run installed MCP engineering between them. Independent attached-frame review.'} - write(root/'submission.json', result) + publish_submission(root, result, deadline) return result diff --git a/tests/test_first_delivery_qualification.py b/tests/test_first_delivery_qualification.py index a3ca5ad..9fca57c 100644 --- a/tests/test_first_delivery_qualification.py +++ b/tests/test_first_delivery_qualification.py @@ -60,3 +60,32 @@ def test_review_rejects_a_changed_case_even_when_video_hashes_match(tmp_path): assert not (tmp_path/'reviewed-delivery.json').exists() files['case'].write_text('{"passed":true}') assert record_review(tmp_path, review)['status'] == 'ready_for_submission' + + +def test_submission_write_that_crosses_deadline_is_retained_as_late(tmp_path, monkeypatch): + h = host(monkeypatch) + clock = [3.] + original_replace = h.os.replace + + def delayed_replace(src, dst): + original_replace(src, dst) + if dst.name == 'submission.json': + clock[0] = 6. + + monkeypatch.setattr(h.time, 'monotonic', lambda: clock[0]) + monkeypatch.setattr(h.os, 'replace', delayed_replace) + with pytest.raises(TimeoutError, match='deadline'): + h.publish_submission(tmp_path, {'status': 'submitted'}, deadline=5.) + assert not (tmp_path/'submission.json').exists() + assert h.read(tmp_path/'submission-late.json')['status'] == 'late' + + +def test_fixed_turn_rejects_started_tool_without_completion(monkeypatch): + h = host(monkeypatch) + complete = [(1, {'type': 'turn.completed', 'usage': {'input_tokens': 1000, 'output_tokens': 50}})] + h.require_fixed_turn(complete, [], 'review') + with pytest.raises(ValueError, match='invalid CLI event'): + h.require_fixed_turn(complete, [2], 'review') + started = (1, {'type': 'item.started', 'item': {'type': 'command_execution'}}) + with pytest.raises(ValueError, match='outside the fixed model turn'): + h.require_fixed_turn([started, *complete], [], 'review') From 07294b7fc72c3260e84ac0185e93f23aa21f5f36 Mon Sep 17 00:00:00 2001 From: shaoxiang <519517384@qq.com> Date: Wed, 25 Nov 2026 15:53:55 +0800 Subject: [PATCH 20/20] Record the independent first-delivery qualification --- docs/validation/integration-release-matrix.md | 16 +++++++ .../first_delivery/qualification-result.json | 47 +++++++++++++++++++ experiments/qualify_first_delivery.py | 1 + 3 files changed, 64 insertions(+) create mode 100644 examples/first_delivery/qualification-result.json diff --git a/docs/validation/integration-release-matrix.md b/docs/validation/integration-release-matrix.md index 471a690..c71ba7a 100644 --- a/docs/validation/integration-release-matrix.md +++ b/docs/validation/integration-release-matrix.md @@ -45,3 +45,19 @@ The recorded physical examples use Isaac Sim 6.2.0-rc.14 on the documented Linux host. Prepared assets, callbacks and frame records must be checked for each new run. Hashes support integrity comparisons; they are not signatures. See [catalog capabilities](catalog-capabilities.md) for per-source conditions. + + +## Independent first delivery + +On 2026-11-25, the new host-assisted first-delivery qualification submitted +the verified GSO tabletop drop at commit 82e01fb. Real Codex selected the +recipe in one turn and accepted the fall and settled result from attached +ordered frames in a separate turn. The host ran the installed MCP workflow +between those turns. The submission took 111.777 seconds and reported 30,540 +tokens within the 900-second and 150,000-token allowances. See the +[qualification result](../../examples/first_delivery/qualification-result.json) +for the tested wheel and usage scope. + +The earlier cabinet QI1 outcomes remain unchanged. The paired drawer showcase +revision retains source mapping, Chinese captions and synchronized displacement +traces. Its final continuous-playback visual review remains pending. diff --git a/examples/first_delivery/qualification-result.json b/examples/first_delivery/qualification-result.json new file mode 100644 index 0000000..26edb83 --- /dev/null +++ b/examples/first_delivery/qualification-result.json @@ -0,0 +1,47 @@ +{ + "schema": "simscene.first_delivery_qualification_public.v1", + "date": "2026-11-25", + "code_commit": "82e01fb1e5d3ef569779e9bcd916afa80a1aad29", + "wheel_sha256": "a8fdeb7a45c6af7fd3327042f7602d1936da17bf124dc3648022c40d9d001b4b", + "model": "gpt-6.1-terra", + "codex_cli": "0.172.0", + "model_turns": { + "discover": { + "input_tokens": 10968, + "cached_input_tokens": 0, + "output_tokens": 43, + "total_tokens": 11011 + }, + "review": { + "input_tokens": 19394, + "cached_input_tokens": 0, + "output_tokens": 135, + "total_tokens": 19529 + } + }, + "wall_seconds": 111.777, + "wall_limit_seconds": 900, + "observed_token_limit": 150000, + "observed_turn_allowance": 60000, + "result": "submitted", + "physical_status": "passed", + "media_status": "passed", + "visual_review": "accept", + "video_sha256": "f063281a2f6f95e28f01ccf1ab6afb9a4ad49b63308554f3512e36c7f152da0c", + "source": { + "source_id": "gso-glb", + "asset_id": "ReadytoUse_Rolled_Fondant_Pure_White_24_oz_box", + "revision": "75e8895e4f4e854cddd7009a7e60f86812041012", + "variant_id": null + }, + "native_video": { + "fps": 30, + "resolution": [ + 1920, + 1080 + ], + "decoded_frames": 120 + }, + "scope": "Two isolated Codex turns: installed recipe selection and visual review from attached ordered frames. Host executes the installed MCP workflow between turns. Scope is limited to this fixed GSO case.", + "usage_scope": "Reported CLI aggregate only. No request-level accounting or claims about hidden in-flight use, whole-library compatibility, or throughput." +} diff --git a/experiments/qualify_first_delivery.py b/experiments/qualify_first_delivery.py index 4983f00..5824e5b 100644 --- a/experiments/qualify_first_delivery.py +++ b/experiments/qualify_first_delivery.py @@ -253,6 +253,7 @@ def main(): result = {'status': 'incomplete', 'error': str(error), 'directory': str(root)} result['wall_s'] = time.monotonic()-start result['model_observed_tokens'] = budget.spent + result['pending_usage_turn'] = budget.in_flight write(root/'summary.json', result) write(root/'budget-ledger.json', budget.ledger) print(json.dumps(result, indent=2, ensure_ascii=False))