RoboParty Release
Unify robohome source, assets and scenes delivery
3f15e9f
Raw History Blame Contribute Delete
27.3 kB
from __future__ import annotations
import hashlib
import json
import os
import re
import subprocess
from datetime import UTC, datetime
from pathlib import Path
from typing import Any
from packages.core.files import atomic_write_text
REFERENCE_PATTERN = re.compile(r"@([^@]+)@")
ISAAC_RUNTIME_ASSETS = {"OmniPBR.mdl"}
RUNTIME_SCENE_FILES = (
"scene.usdc",
"preview.mp4",
"iteration_history.mp4",
"iterations_manifest.json",
"stage_manifest.json",
"scene_request.json",
"scene_context.json",
"selected_assets.json",
"effective_selected_assets.json",
"compiled_prompt.txt",
"timing.json",
"cleanup_report.json",
"cleanup_config.json",
"context_assets_config.json",
"agent_skill_policy.json",
"scene_dependency_graph.json",
"dependency_execution_plan.json",
"agent_orchestration_effective.json",
"planning_agent_output.json",
"agent_execution_plan.json",
"agent_execution_ledger.json",
"global_critic.json",
"agent_merge_result.json",
)
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def refresh_checksums(root: Path) -> int:
lines = []
for path in sorted(root.rglob("*")):
if path.is_file() and not path.is_symlink() and path.name != "checksums.sha256":
lines.append(f"{sha256(path)} {path.relative_to(root).as_posix()}")
atomic_write_text(root / "checksums.sha256", "\n".join(lines) + "\n")
return len(lines)
def _hardlink(source: Path, destination: Path) -> None:
destination.parent.mkdir(parents=True, exist_ok=True)
os.link(source, destination)
def _runtime_files(source: Path) -> list[tuple[Path, Path]]:
files: list[tuple[Path, Path]] = []
for relative_root in (Path("layers"), Path("manifests")):
for path in sorted((source / relative_root).rglob("*")):
if (
path.is_file()
and not path.is_symlink()
and path.relative_to(source) != Path("manifests/portable_validation.json")
):
files.append((path, path.relative_to(source)))
files.append((source / "root.usda", Path("root.usda")))
snapshot = source / "snapshot.jpg"
if snapshot.is_file():
files.append((snapshot, Path("snapshot.jpg")))
# Stable public media entry. Keep the SceneSmith-native location as
# provenance/backward compatibility, while portable consumers can always
# open ``preview.mp4`` without knowing which scene backend produced it.
root_preview = source / "preview.mp4"
scenesmith_preview = source / "scenesmith" / "preview.mp4"
preview = root_preview if root_preview.is_file() else scenesmith_preview
if preview.is_file():
files.append((preview, Path("preview.mp4")))
root_history = source / "iteration_history.mp4"
scenesmith_history = source / "scenesmith" / "iteration_history.mp4"
history = root_history if root_history.is_file() else scenesmith_history
if history.is_file():
files.append((history, Path("iteration_history.mp4")))
for name in RUNTIME_SCENE_FILES:
path = source / "scenesmith" / name
if path.is_file():
files.append((path, Path("scenesmith") / name))
texture_root = source / "scenesmith" / "textures"
if texture_root.is_dir():
for path in sorted(texture_root.rglob("*")):
if path.is_file() and not path.is_symlink():
files.append((path, path.relative_to(source)))
robot_assets_root = source / "assets" / "robots"
if robot_assets_root.is_dir():
for path in sorted(robot_assets_root.rglob("*")):
if path.is_file() and not path.is_symlink():
files.append((path, path.relative_to(source)))
postprocess_root = source / "scenesmith" / "postprocess_iterations"
if postprocess_root.is_dir():
for path in sorted(postprocess_root.rglob("*")):
if path.is_file() and not path.is_symlink():
files.append((path, path.relative_to(source)))
subtree_root = source / "scenesmith" / "subtrees"
if subtree_root.is_dir():
for path in sorted(subtree_root.rglob("*")):
if path.is_file() and not path.is_symlink():
files.append((path, path.relative_to(source)))
house_state = source / "scenesmith/upstream/scene_000/combined_house/house_state.json"
stage_manifest = source / "scenesmith/stage_manifest.json"
if stage_manifest.is_file():
manifest = json.loads(stage_manifest.read_text(encoding="utf-8"))
relative_state = manifest.get("house_state")
if isinstance(relative_state, str) and relative_state:
candidate = source / "scenesmith" / relative_state
if candidate.is_file():
house_state = candidate
if house_state.is_file():
files.append((house_state, Path("provenance/house_state.json")))
return files
def portable_source_fingerprint(source: Path) -> str:
"""Hash every source artifact that is materialized into a portable bundle."""
digest = hashlib.sha256()
for path, relative in _runtime_files(source.resolve()):
digest.update(relative.as_posix().encode("utf-8"))
digest.update(b"\0")
digest.update(sha256(path).encode("ascii"))
digest.update(b"\n")
return digest.hexdigest()
def _native_asset_bindings(source: Path) -> dict[str, Any]:
manifest_path = source / "scenesmith/stage_manifest.json"
if not manifest_path.is_file():
return {}
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
bindings = manifest.get("native_asset_bindings") or {}
if not isinstance(bindings, dict):
raise ValueError(f"native_asset_bindings must be an object: {manifest_path}")
return bindings
def _dependency_destination(root: Path, source: Path, kind: str) -> Path:
path_digest = hashlib.sha256(str(source).encode("utf-8")).hexdigest()[:16]
return root / "scenesmith" / "assets" / kind / f"{path_digest}-{source.name}"
def _is_isaac_runtime_asset(value: object) -> bool:
"""Recognize only named modules guaranteed by the declared Isaac runtime."""
normalized = str(value).replace("\\", "/").rsplit("/", 1)[-1]
return normalized in ISAAC_RUNTIME_ASSETS
def _stage_usd_dependencies(
source_scene: Path,
destination_scene: Path,
destination_root: Path,
) -> dict[str, Any]:
try:
from pxr import Sdf, Usd, UsdUtils # type: ignore[import-not-found]
except ImportError as error:
raise RuntimeError(
"pxr is required to stage native USD dependencies for a portable bundle"
) from error
layers, asset_paths, unresolved = UsdUtils.ComputeAllDependencies(str(source_scene))
external_runtime_assets = sorted(
{str(path).replace("\\", "/").rsplit("/", 1)[-1] for path in unresolved}
& ISAAC_RUNTIME_ASSETS
)
unresolved_files = sorted(
str(path) for path in unresolved if not _is_isaac_runtime_asset(path)
)
if unresolved_files:
raise RuntimeError(
"USD dependencies could not be resolved: " + ", ".join(unresolved_files)
)
source_scene = source_scene.resolve()
layer_sources = {
Path(layer.realPath).resolve(): layer
for layer in layers
if layer.realPath and Path(layer.realPath).is_file()
}
if source_scene not in layer_sources:
raise RuntimeError(f"USD dependency traversal omitted root layer: {source_scene}")
destination_by_source: dict[Path, Path] = {source_scene: destination_scene}
for source in sorted(layer_sources, key=str):
if source != source_scene:
destination_by_source[source] = _dependency_destination(destination_root, source, "usd")
non_layer_sources = {
Path(path).resolve()
for path in asset_paths
if Path(path).is_file() and Path(path).resolve() not in layer_sources
}
missing_assets = sorted(
str(path)
for path in asset_paths
if not Path(path).is_file() and not _is_isaac_runtime_asset(path)
)
if missing_assets:
raise RuntimeError("USD asset files are missing: " + ", ".join(missing_assets))
for source in sorted(non_layer_sources, key=str):
destination_by_source[source] = _dependency_destination(destination_root, source, "files")
hardlinked_assets = 0
for source in sorted(non_layer_sources, key=str):
target = destination_by_source[source]
_hardlink(source, target)
hardlinked_assets += 1
rewritten_layers = 0
for source, source_layer in sorted(layer_sources.items(), key=lambda item: str(item[0])):
target = destination_by_source[source]
target.parent.mkdir(parents=True, exist_ok=True)
temporary = target.with_name(f".{target.name}.rewrite{target.suffix}")
if not source_layer.Export(str(temporary)):
raise RuntimeError(f"could not export USD dependency: {source}")
output_layer = Sdf.Layer.FindOrOpen(str(temporary))
if output_layer is None:
raise RuntimeError(f"could not reopen staged USD layer: {temporary}")
unstaged: list[str] = []
def rebase(
asset_path: str,
*,
source_layer: Any = source_layer,
source: Path = source,
target: Path = target,
unstaged: list[str] = unstaged,
) -> str:
if not asset_path:
return asset_path
resolved_text = Sdf.ComputeAssetPathRelativeToLayer(source_layer, asset_path)
resolved = Path(resolved_text).resolve()
dependency_target = destination_by_source.get(resolved)
if dependency_target is None:
if resolved.is_file():
unstaged.append(f"{source}: {asset_path} -> {resolved}")
return asset_path
return os.path.relpath(dependency_target, target.parent).replace(os.sep, "/")
UsdUtils.ModifyAssetPaths(output_layer, rebase)
if unstaged:
raise RuntimeError("USD dependencies were not staged: " + ", ".join(unstaged))
output_layer.Save()
temporary.replace(target)
rewritten_layers += 1
stage = Usd.Stage.Open(str(destination_scene))
if stage is None:
raise RuntimeError(f"staged USD scene does not open: {destination_scene}")
return {
"rewritten_layers": rewritten_layers,
"hardlinked_assets": hardlinked_assets,
"dependency_count": len(destination_by_source) - 1,
"external_runtime_assets": external_runtime_assets,
}
def create_portable_bundle(
source: Path,
destination: Path,
*,
policy_path: Path | None = None,
) -> dict[str, Any]:
source = source.resolve()
destination = destination.resolve()
if destination.exists():
raise FileExistsError(destination)
if not (source / "root.usda").is_file():
raise FileNotFoundError(source / "root.usda")
if source.stat().st_dev != destination.parent.stat().st_dev:
raise RuntimeError("hard-link staging requires source and destination on one filesystem")
destination.mkdir()
linked = 0
for path, relative in _runtime_files(source):
if not path.is_file():
raise FileNotFoundError(path)
_hardlink(path, destination / relative)
linked += 1
if policy_path is not None:
policy_path = policy_path.resolve()
_hardlink(policy_path, destination / "runtime/policies" / policy_path.name)
linked += 1
usd_dependencies = {
"rewritten_layers": 0,
"hardlinked_assets": 0,
"dependency_count": 0,
"external_runtime_assets": [],
}
if _native_asset_bindings(source):
usd_dependencies = _stage_usd_dependencies(
source / "scenesmith/scene.usdc",
destination / "scenesmith/scene.usdc",
destination,
)
linked += usd_dependencies["hardlinked_assets"]
furniture = destination / "layers/furniture.usda"
text = furniture.read_text(encoding="utf-8")
corrected = text.replace("@scenesmith/scene.usdc@", "@../scenesmith/scene.usdc@")
if corrected != text:
# Break the hard link before writing metadata that is specific to the portable layout.
temporary = furniture.with_suffix(".tmp")
temporary.write_text(corrected, encoding="utf-8")
temporary.replace(furniture)
manifest = {
"schema_version": "1.0",
"format": "robothousegen-portable-benchmark",
"created_at": datetime.now(UTC).isoformat(),
"source_run_name": source.name,
"source_fingerprint": portable_source_fingerprint(source),
"entrypoint": "root.usda",
"episode": "manifests/episode.json",
"evaluator": "manifests/evaluator.json",
"hardlink_staging": True,
"hardlinked_files": linked,
"usd_dependencies": usd_dependencies,
"runtime_requirements": {
"simulator": "Isaac Sim 6.0.1",
"benchmark_runtime": "Isaac Lab-Arena release/0.2.1",
"robot_profile": "unitree_g1_43dof",
},
}
atomic_write_text(
destination / "portable_manifest.json",
json.dumps(manifest, indent=2, sort_keys=True) + "\n",
)
manifest["checksummed_files"] = refresh_checksums(destination)
return manifest
def _verify_checksums(root: Path) -> list[str]:
failures = []
checksum_path = root / "checksums.sha256"
if not checksum_path.is_file():
return ["checksums.sha256 is missing"]
for line in checksum_path.read_text(encoding="utf-8").splitlines():
expected, separator, relative = line.partition(" ")
path = root / relative
if not separator or not path.is_file() or sha256(path) != expected:
failures.append(relative or line)
return failures
def _verify_text_references(root: Path, *, allowed_root: Path | None = None) -> list[str]:
allowed_root = (allowed_root or root).resolve()
failures = []
for layer in [root / "root.usda", *(root / "layers").glob("*.usda")]:
for reference in REFERENCE_PATTERN.findall(layer.read_text(encoding="utf-8")):
if reference.startswith(("http://", "https://", "omniverse://")):
failures.append(f"external URI in {layer.relative_to(root)}: {reference}")
continue
target = (layer.parent / reference).resolve()
if not target.is_relative_to(allowed_root) or not target.is_file():
failures.append(f"broken reference in {layer.relative_to(root)}: {reference}")
return failures
def _verify_usd(
root: Path, *, allowed_root: Path | None = None
) -> tuple[dict[str, Any], list[str]]:
allowed_root = (allowed_root or root).resolve()
try:
from pxr import Sdf, Usd, UsdPhysics
except ImportError:
return {"pxr_available": False}, []
stage = Usd.Stage.Open(str(root / "root.usda"))
if stage is None:
return {"pxr_available": True, "stage_open": False}, ["USD stage did not open"]
failures: list[str] = []
external_paths: list[str] = []
for layer in stage.GetLayerStack():
if not layer.realPath:
continue
for reference in layer.GetExternalReferences():
target = Path(layer.ComputeAbsolutePath(reference)).resolve()
external_paths.append(str(target))
if not target.is_relative_to(allowed_root) or not target.is_file():
failures.append(f"USD dependency escapes bundle: {target}")
asset_paths = 0
for prim in stage.Traverse():
for attribute in prim.GetAttributes():
value = attribute.Get()
values = value if isinstance(value, (list, tuple)) else [value]
for item in values:
if isinstance(item, Sdf.AssetPath) and item.path:
asset_paths += 1
if item.path in ISAAC_RUNTIME_ASSETS:
continue
asset_target = Path(item.resolvedPath).resolve() if item.resolvedPath else None
if (
asset_target is None
or not asset_target.is_relative_to(allowed_root)
or not asset_target.is_file()
):
failures.append(f"USD asset dependency is missing or external: {item.path}")
evaluator = json.loads((root / "manifests/evaluator.json").read_text(encoding="utf-8"))
missing_prims = [
path
for path in [
*evaluator.get("entity_prim_paths", {}).values(),
evaluator.get("robot_prim_path"),
]
if path and not stage.GetPrimAtPath(path)
]
failures.extend(f"evaluator prim is missing: {path}" for path in missing_prims)
task = json.loads((root / "manifests/task.json").read_text(encoding="utf-8"))
entity_paths = evaluator.get("entity_prim_paths", {})
manipulation_physics: dict[str, Any] = {}
for entity in task.get("entities", []):
if not isinstance(entity, dict) or entity.get("role") != "MANIPULATED":
continue
entity_id = str(entity.get("entity_id", ""))
prim_path = entity_paths.get(entity_id)
prim = stage.GetPrimAtPath(prim_path) if isinstance(prim_path, str) else None
rigid = bool(prim and prim.HasAPI(UsdPhysics.RigidBodyAPI))
collisions = (
[
str(descendant.GetPath())
for descendant in Usd.PrimRange(prim)
if descendant.HasAPI(UsdPhysics.CollisionAPI)
]
if prim
else []
)
manipulation_physics[entity_id] = {
"prim_path": prim_path,
"rigid_body_api": rigid,
"collision_prim_paths": collisions,
}
if not rigid:
failures.append(f"manipulated entity lacks RigidBodyAPI: {entity_id}")
if not collisions:
failures.append(f"manipulated entity lacks CollisionAPI geometry: {entity_id}")
return {
"pxr_available": True,
"stage_open": True,
"traversed_prims": sum(1 for _ in stage.Traverse()),
"external_layers": len(external_paths),
"asset_paths": asset_paths,
"missing_evaluator_prims": missing_prims,
"manipulation_physics": manipulation_physics,
}, failures
def verify_portable_bundle(root: Path, *, require_pxr: bool = False) -> dict[str, Any]:
root = root.resolve()
failures: list[str] = []
required = [
"root.usda",
"portable_manifest.json",
"manifests/task.json",
"manifests/scene.json",
"manifests/evaluator.json",
"manifests/episode.json",
]
if (root / "scenesmith/stage_manifest.json").is_file() or (
root / "scenesmith/scene.usdc"
).is_file():
required.append("scenesmith/scene.usdc")
failures.extend(relative for relative in required if not (root / relative).is_file())
symlinks = [str(path.relative_to(root)) for path in root.rglob("*") if path.is_symlink()]
failures.extend(f"symlink is not portable: {path}" for path in symlinks)
failures.extend(f"checksum mismatch: {path}" for path in _verify_checksums(root))
failures.extend(_verify_text_references(root))
usd_report, usd_failures = _verify_usd(root)
failures.extend(usd_failures)
if require_pxr and not usd_report.get("pxr_available"):
failures.append("pxr is required for full USD validation")
return {
"schema_version": "1.0",
"root": str(root),
"passed": not failures,
"failures": failures,
"file_count": sum(1 for path in root.rglob("*") if path.is_file()),
"size_bytes": sum(path.stat().st_size for path in root.rglob("*") if path.is_file()),
"symlink_count": len(symlinks),
"usd": usd_report,
}
def _link_tree(source: Path, destination: Path) -> int:
linked = 0
for path in sorted(source.rglob("*")):
if path.is_symlink():
raise RuntimeError(f"portable source contains a symlink: {path}")
if path.is_file():
_hardlink(path, destination / path.relative_to(source))
linked += 1
return linked
def create_portable_suite_bundle(source: Path, destination: Path) -> dict[str, Any]:
"""Stage a shared-scene benchmark suite with every dependency inside one directory."""
source = source.resolve()
destination = destination.resolve()
if destination.exists():
raise FileExistsError(destination)
suite_manifest_path = source / "manifests/suite.json"
if not suite_manifest_path.is_file():
raise FileNotFoundError(suite_manifest_path)
if source.stat().st_dev != destination.parent.stat().st_dev:
raise RuntimeError("hard-link staging requires source and destination on one filesystem")
suite_manifest = json.loads(suite_manifest_path.read_text(encoding="utf-8"))
episodes = suite_manifest.get("episodes")
if not isinstance(episodes, list) or not episodes:
raise ValueError("suite manifest must contain episodes")
destination.mkdir()
linked = 0
for relative in (Path("inputs"), Path("manifests")):
root = source / relative
if root.is_dir():
linked += _link_tree(root, destination / relative)
for episode in episodes:
if not isinstance(episode, dict) or not isinstance(episode.get("episode_id"), str):
raise ValueError("suite episode entries require episode_id")
episode_id = episode["episode_id"]
episode_root = source / "episodes" / episode_id
if not episode_root.is_dir():
raise FileNotFoundError(episode_root)
linked += _link_tree(episode_root, destination / "episodes" / episode_id)
shared_source = source / "shared_scene"
shared_destination = destination / "shared_scene"
for path, relative in _runtime_files(shared_source):
if not path.is_file():
raise FileNotFoundError(path)
_hardlink(path, shared_destination / relative)
linked += 1
usd_dependencies = {
"rewritten_layers": 0,
"hardlinked_assets": 0,
"dependency_count": 0,
}
if _native_asset_bindings(shared_source):
usd_dependencies = _stage_usd_dependencies(
shared_source / "scenesmith/scene.usdc",
shared_destination / "scenesmith/scene.usdc",
shared_destination,
)
linked += usd_dependencies["hardlinked_assets"]
manifest = {
"schema_version": "1.0",
"format": "robothousegen-portable-suite",
"created_at": datetime.now(UTC).isoformat(),
"source_run_name": source.name,
"suite": "manifests/suite.json",
"shared_scene_entrypoint": "shared_scene/root.usda",
"shared_scene_usd": (
"shared_scene/scenesmith/scene.usdc"
if (shared_destination / "scenesmith/scene.usdc").is_file()
else None
),
"episode_count": len(episodes),
"hardlink_staging": True,
"hardlinked_files": linked,
"usd_dependencies": usd_dependencies,
"runtime_requirements": {
"simulator": "Isaac Sim 6.0.1",
"benchmark_runtime": "Isaac Lab-Arena release/0.2.1",
},
}
atomic_write_text(
destination / "portable_manifest.json",
json.dumps(manifest, indent=2, sort_keys=True) + "\n",
)
manifest["checksummed_files"] = refresh_checksums(destination)
return manifest
def verify_portable_suite_bundle(root: Path, *, require_pxr: bool = False) -> dict[str, Any]:
root = root.resolve()
failures: list[str] = []
required = [
"portable_manifest.json",
"manifests/suite.json",
"manifests/build_timing.json",
"shared_scene/root.usda",
"shared_scene/manifests/scene.json",
]
portable_path = root / "portable_manifest.json"
if portable_path.is_file():
portable = json.loads(portable_path.read_text(encoding="utf-8"))
shared_scene_usd = portable.get("shared_scene_usd")
if isinstance(shared_scene_usd, str):
required.append(shared_scene_usd)
failures.extend(relative for relative in required if not (root / relative).is_file())
symlinks = [str(path.relative_to(root)) for path in root.rglob("*") if path.is_symlink()]
failures.extend(f"symlink is not portable: {path}" for path in symlinks)
failures.extend(f"checksum mismatch: {path}" for path in _verify_checksums(root))
suite_path = root / "manifests/suite.json"
episodes: list[dict[str, Any]] = []
if suite_path.is_file():
payload = json.loads(suite_path.read_text(encoding="utf-8"))
raw_episodes = payload.get("episodes", [])
if isinstance(raw_episodes, list):
episodes = [item for item in raw_episodes if isinstance(item, dict)]
else:
failures.append("suite manifest episodes must be a list")
usd_reports: dict[str, Any] = {}
for episode in episodes:
episode_id = episode.get("episode_id")
if not isinstance(episode_id, str):
failures.append("suite episode is missing episode_id")
continue
episode_root = root / "episodes" / episode_id
for relative in (
"root.usda",
"manifests/task.json",
"manifests/episode.json",
"manifests/evaluator.json",
"manifests/scene_overrides.json",
):
if not (episode_root / relative).is_file():
failures.append(f"episodes/{episode_id}/{relative} is missing")
if not (episode_root / "root.usda").is_file():
continue
failures.extend(_verify_text_references(episode_root, allowed_root=root))
if (episode_root / "manifests/evaluator.json").is_file():
usd_report, usd_failures = _verify_usd(episode_root, allowed_root=root)
usd_reports[episode_id] = usd_report
failures.extend(f"{episode_id}: {failure}" for failure in usd_failures)
if require_pxr and not usd_report.get("pxr_available"):
failures.append(f"{episode_id}: pxr is required for full USD validation")
return {
"schema_version": "1.0",
"root": str(root),
"passed": not failures,
"failures": failures,
"episode_count": len(episodes),
"file_count": sum(1 for path in root.rglob("*") if path.is_file()),
"size_bytes": sum(path.stat().st_size for path in root.rglob("*") if path.is_file()),
"symlink_count": len(symlinks),
"usd": usd_reports,
}
def create_zstd_archive(bundle: Path, archive: Path) -> None:
archive.parent.mkdir(parents=True, exist_ok=True)
subprocess.run(
["tar", "--zstd", "-cf", str(archive), "-C", str(bundle.parent), bundle.name],
check=True,
)