From ec496c0a7389f301ec898021dce20b22420de710 Mon Sep 17 00:00:00 2001 From: Piotr Barejko Date: Wed, 2 Dec 2026 14:53:50 -0700 Subject: [PATCH] Manage localized asset lifetimes with OVStorage leases --- .../ovstorage-asset-reads.added.rst | 2 + .../ovstorage-asset-reads.changed.rst | 5 + .../changelog.d/ovstorage-asset-reads.minor | 0 .../sim/spawners/from_files/from_files.py | 36 +- .../sim/usd_export/base_usd_exporter.py | 29 +- source/isaaclab/isaaclab/sim/utils/prims.py | 27 +- .../isaaclab/isaaclab/utils/_asset_cache.py | 216 ++++++++ source/isaaclab/isaaclab/utils/assets.py | 508 ++++++------------ source/isaaclab/test/sim/test_usd_export.py | 11 +- source/isaaclab/test/utils/test_assets.py | 449 ++++++---------- .../ovstorage-asset-reads.changed.rst | 2 + .../tacsl_sensor/visuotactile_render.py | 49 +- .../ovstorage-asset-reads.changed.rst | 3 + .../entrypoints/backends/export_rl_games.py | 4 +- .../entrypoints/backends/export_rsl_rl.py | 4 +- .../entrypoints/backends/export_sb3.py | 3 +- .../entrypoints/backends/export_skrl.py | 4 +- .../entrypoints/backends/play_model_based.py | 3 +- .../entrypoints/backends/play_rl_games.py | 3 +- .../entrypoints/backends/play_rsl_rl.py | 3 +- .../entrypoints/backends/play_sb3.py | 3 +- .../entrypoints/backends/play_skrl.py | 3 +- .../entrypoints/backends/play_torchrl.py | 3 +- .../isaaclab_rl/entrypoints/common.py | 14 +- .../utils/pretrained_checkpoint.py | 15 +- .../test/test_pretrained_checkpoint.py | 43 +- .../ovstorage-asset-reads.changed.rst | 2 + .../contrib/automate/assembly_env.py | 14 +- .../contrib/automate/automate_algo_utils.py | 6 +- .../contrib/automate/disassembly_env.py | 10 +- .../contrib/automate/industreal_algo_utils.py | 10 +- .../contrib/drone_arl/mdp/observations.py | 7 +- 32 files changed, 713 insertions(+), 778 deletions(-) create mode 100644 source/isaaclab/changelog.d/ovstorage-asset-reads.added.rst create mode 100644 source/isaaclab/changelog.d/ovstorage-asset-reads.changed.rst create mode 100644 source/isaaclab/changelog.d/ovstorage-asset-reads.minor create mode 100644 source/isaaclab/isaaclab/utils/_asset_cache.py create mode 100644 source/isaaclab_contrib/changelog.d/ovstorage-asset-reads.changed.rst create mode 100644 source/isaaclab_rl/changelog.d/ovstorage-asset-reads.changed.rst create mode 100644 source/isaaclab_tasks/changelog.d/ovstorage-asset-reads.changed.rst diff --git a/source/isaaclab/changelog.d/ovstorage-asset-reads.added.rst b/source/isaaclab/changelog.d/ovstorage-asset-reads.added.rst new file mode 100644 index 000000000000..d893ba62818b --- /dev/null +++ b/source/isaaclab/changelog.d/ovstorage-asset-reads.added.rst @@ -0,0 +1,2 @@ +* Added :func:`isaaclab.utils.assets.lease_file_path` to keep a read-only local asset and its USD + dependencies available to a consumer, including a subprocess, for the duration of a context manager. diff --git a/source/isaaclab/changelog.d/ovstorage-asset-reads.changed.rst b/source/isaaclab/changelog.d/ovstorage-asset-reads.changed.rst new file mode 100644 index 000000000000..0563aed21828 --- /dev/null +++ b/source/isaaclab/changelog.d/ovstorage-asset-reads.changed.rst @@ -0,0 +1,5 @@ +* Replaced the temporary asset mirror and its revision sidecars with a shared OVStorage byte + cache with a 10 GiB eviction budget. USD stages hold leases on downloaded and rewritten + layers so deferred payloads remain available. Existing mirror files are outside this budget. +* Kept process-lifetime paths for callers of :func:`isaaclab.utils.assets.retrieve_file_path`. + Passing an explicit download directory saves a caller-owned copy that persists after exit. diff --git a/source/isaaclab/changelog.d/ovstorage-asset-reads.minor b/source/isaaclab/changelog.d/ovstorage-asset-reads.minor new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab/isaaclab/sim/spawners/from_files/from_files.py b/source/isaaclab/isaaclab/sim/spawners/from_files/from_files.py index 3a91fc4c23ff..2cdd62752866 100644 --- a/source/isaaclab/isaaclab/sim/spawners/from_files/from_files.py +++ b/source/isaaclab/isaaclab/sim/spawners/from_files/from_files.py @@ -6,13 +6,9 @@ from __future__ import annotations import logging -import os -import tempfile -from contextlib import nullcontext from typing import TYPE_CHECKING import numpy as np -from filelock import FileLock from ... import converters, schemas from ...utils import ( @@ -676,28 +672,18 @@ def spawn_from_usd_file( deformable_values = (cfg.deformable_props, cfg.volume_deformable_props, cfg.surface_deformable_props) if cfg.mesh_collision_props is not None and any(value is not None for value in deformable_values): raise ValueError("Deformable bodies collide through their simulation mesh and take no 'mesh_collision_props'.") - # In distributed training, serialize asset download and USD stage composition - # across ranks to prevent file I/O races. Concurrent mmap reads/writes on - # the same cached USD files cause segfaults in Sdf_CrateFile::_MmapStream::Read. - _world_size = int(os.environ.get("LOCAL_WORLD_SIZE", "1")) - - if _world_size > 1: - lock = FileLock(os.path.join(tempfile.gettempdir(), "isaaclab_usd_spawn.lock")) + stage = get_current_stage() + if not stage.GetPrimAtPath(prim_path).IsValid(): + create_prim( + prim_path, + usd_path=usd_path, + translation=translation, + orientation=orientation, + scale=cfg.scale, + stage=stage, + ) else: - lock = nullcontext() - with lock: - stage = get_current_stage() - if not stage.GetPrimAtPath(prim_path).IsValid(): - create_prim( - prim_path, - usd_path=usd_path, - translation=translation, - orientation=orientation, - scale=cfg.scale, - stage=stage, - ) - else: - logger.warning(f"A prim already exists at prim path: '{prim_path}'.") + logger.warning(f"A prim already exists at prim path: '{prim_path}'.") from . import from_files_cfg # noqa: PLC0415 diff --git a/source/isaaclab/isaaclab/sim/usd_export/base_usd_exporter.py b/source/isaaclab/isaaclab/sim/usd_export/base_usd_exporter.py index 07c686dbd46a..ee673cd94cdd 100644 --- a/source/isaaclab/isaaclab/sim/usd_export/base_usd_exporter.py +++ b/source/isaaclab/isaaclab/sim/usd_export/base_usd_exporter.py @@ -13,8 +13,10 @@ import os import shutil import tempfile +import weakref from abc import ABC, abstractmethod from collections.abc import Collection +from contextlib import ExitStack from typing import TYPE_CHECKING, Any, ClassVar, NamedTuple import numpy as np @@ -22,7 +24,7 @@ from pxr import Gf, Plug, Sdf, Usd, UsdGeom, UsdPhysics, UsdShade, UsdUtils from ... import cloner -from ...utils.assets import check_file_path, retrieve_file_path, unmirror_file_path +from ...utils.assets import get_asset_source, lease_file_path if TYPE_CHECKING: from ...scene import InteractiveScene @@ -359,18 +361,17 @@ def open_stage(path: str) -> Usd.Stage: Returns: A stage whose layer references local copies of the remote assets. """ - source = Sdf.Layer.FindOrOpen(path) - if source is None: - raise FileNotFoundError(f"Could not open '{path}'.") - layer = Sdf.Layer.CreateAnonymous(".usda") - layer.TransferContent(source) - UsdUtils.ModifyAssetPaths( - layer, - lambda asset: ( - retrieve_file_path(asset) if check_file_path(asset) == 2 else source.ComputeAbsolutePath(asset) - ), - ) - return Usd.Stage.Open(layer) + with ExitStack() as leases: + local_path = leases.enter_context(lease_file_path(path)) + source = Sdf.Layer.FindOrOpen(local_path) + if source is None: + raise FileNotFoundError(f"Could not open '{path}'.") + layer = Sdf.Layer.CreateAnonymous(".usda") + layer.TransferContent(source) + UsdUtils.ModifyAssetPaths(layer, source.ComputeAbsolutePath) + stage = Usd.Stage.Open(layer) + weakref.finalize(stage, leases.pop_all().close) + return stage def _get_engine_base(self) -> Any: """The base :meth:`read_engine_base` returned when the scene's physics became ready.""" @@ -481,7 +482,7 @@ def _compute_pd_drive_edits(self, stage: Usd.Stage) -> list[UsdEdit]: def _make_asset_paths_portable(self, layer: Sdf.Layer, export_path: str): """Reference the source of cached remote assets, and keep files the run wrote to the temporary directory.""" # Cached copies of remote assets exist only on this machine; reference their source instead. - UsdUtils.ModifyAssetPaths(layer, lambda asset: unmirror_file_path(asset) or asset) + UsdUtils.ModifyAssetPaths(layer, lambda asset: get_asset_source(asset) or asset) UsdUtils.ModifyAssetPaths(layer, functools.partial(self._copy_temporary_file, export_path=export_path)) remote = sorted({asset for asset in layer.GetCompositionAssetDependencies() if "://" in asset}) if remote: diff --git a/source/isaaclab/isaaclab/sim/utils/prims.py b/source/isaaclab/isaaclab/sim/utils/prims.py index 5f702c3a5e67..d188010ae245 100644 --- a/source/isaaclab/isaaclab/sim/utils/prims.py +++ b/source/isaaclab/isaaclab/sim/utils/prims.py @@ -12,13 +12,15 @@ import logging import math import re +import weakref from collections.abc import Callable, Sequence +from contextlib import ExitStack from typing import TYPE_CHECKING, Any, ParamSpec, overload import torch from ...utils import to_dict -from ...utils.assets import retrieve_file_path +from ...utils.assets import lease_file_path from ...utils.string import to_camel_case from .queries import ( find_matching_prim_paths, @@ -976,16 +978,19 @@ def add_usd_reference( from pxr import Ar # noqa: PLC0415 stage = get_current_stage() if stage is None else stage - with Ar.ResolverContextBinder(stage.GetPathResolverContext()): - usd_path = retrieve_file_path(usd_path) - prim = stage.GetPrimAtPath(prim_path) - if not prim.IsValid(): - prim = stage.DefinePrim(prim_path, prim_type) - - if not prim.GetReferences().AddReference(usd_path): - raise RuntimeError( - f"Unable to add USD reference to the prim at path: {prim_path} from the USD file at path: {usd_path}" - ) + with ExitStack() as leases: + with Ar.ResolverContextBinder(stage.GetPathResolverContext()): + usd_path = leases.enter_context(lease_file_path(usd_path)) + prim = stage.GetPrimAtPath(prim_path) + if not prim.IsValid(): + prim = stage.DefinePrim(prim_path, prim_type) + + if not prim.GetReferences().AddReference(usd_path): + raise RuntimeError( + f"Unable to add USD reference to the prim at path: {prim_path} from the USD file at path: {usd_path}" + ) + # References and unloaded payloads may be opened long after prim creation. + weakref.finalize(stage, leases.pop_all().close) return prim diff --git a/source/isaaclab/isaaclab/utils/_asset_cache.py b/source/isaaclab/isaaclab/utils/_asset_cache.py new file mode 100644 index 000000000000..46ef19b22d6e --- /dev/null +++ b/source/isaaclab/isaaclab/utils/_asset_cache.py @@ -0,0 +1,216 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""OVStorage byte caching and lifetime of local names presented to asset consumers.""" + +import asyncio +import contextlib +import errno +import functools +import hashlib +import os +import re +import shutil +import threading +import uuid +from collections.abc import Coroutine +from pathlib import Path +from types import SimpleNamespace +from typing import Any, BinaryIO + +import ovstorage +from filelock import FileLock +from ovstorage.byte_cache import ByteCache + + +_MAX_CACHE_BYTES = 10 * 1024**3 + + +@functools.cache +def _ovstorage_loop() -> ovstorage.OwnedLoop: + """Event loop thread driving every OVStorage stack, started on first use.""" + return ovstorage.OwnedLoop() + + +def run(coroutine: Coroutine[Any, Any, Any]) -> Any: + """Run an OVStorage coroutine on its event loop thread and return the result.""" + return asyncio.run_coroutine_threadsafe(coroutine, _ovstorage_loop().loop).result() + + +def cache_directory() -> Path: + """Directory shared by the local byte caches and their named files.""" + parent = os.getenv("XDG_CACHE_HOME") or os.getenv("LOCALAPPDATA") or Path.home() / ".cache" + return Path(parent).absolute() / "isaaclab" / "ovstorage" + + +def _byte_cache(inner: str, directory: Path) -> ByteCache: + directory.mkdir(mode=0o700, parents=True, exist_ok=True) + return ByteCache( + "cache", + inner, + { + "cache_root": ovstorage.ConfigValue.string(str(directory / "blobs")), + "state_root": ovstorage.ConfigValue.string(str(directory / "state")), + "max_bytes": ovstorage.ConfigValue.int_(_MAX_CACHE_BYTES), + }, + ) + + +class _CacheReads(ovstorage.LayerBase): + """Let materialize return a cache hit or signal a miss, without spooling an unowned temp file.""" + + async def materialize(self, address: str, **kwargs) -> ovstorage.LocalDelegate: + raise ovstorage.UnsupportedError("cache miss") + + +def wrap_reads(stack: ovstorage.Stack, directory: Path) -> None: + """Cache validated remote reads and return pinned entries on a materialize hit.""" + stack.wrapper(_CacheReads(name="reads", layer_type="wrapper", inner="redirects")) + stack.wrapper(_byte_cache("reads", directory)) + + +def cached_delegate(cache: ovstorage.LayerBase, address: str) -> ovstorage.LocalDelegate | None: + """Pin an existing entry. Both cache origins decline materialization on a miss.""" + try: + return run(cache.materialize(address)) + except ovstorage.UnsupportedError: + return None + + +class _PublishedContent(ovstorage.LayerBase): + """Read-only origin for immutable bytes while they are being inserted into OVStorage.""" + + payload: bytes + + async def stat(self, address: str, **kwargs): + return SimpleNamespace( + address=address, + kind="file", + size=len(self.payload), + etag=address.rsplit("/", 1)[1], + etag_strength="strong", + mtime_unix_nanos=None, + version=None, + system_metadata={}, + user_metadata={}, + ) + + async def read(self, address: str, **kwargs): + return self.payload, await self.stat(address) + + +@functools.cache +def _published_stack(directory: Path) -> tuple[_PublishedContent, ovstorage.LayerBase]: + origin = _PublishedContent(name="content", layer_type="backend", roots=["isaaclab-content:///"]) + stack = ( + ovstorage.Stack(root="cache") + .with_registry(ovstorage.PluginRegistry([ovstorage.bundled_plugins_dir()])) + .backend(origin) + .wrapper(_byte_cache("content", directory)) + ) + return origin, run(stack.build()) + + +_PUBLISH_LOCK = threading.Lock() + + +def _lock_view(marker: Path) -> BinaryIO: + """Hold the namespace lock until the descriptor closes (including on process death).""" + stream = marker.open("a+b") + try: + if os.name == "nt": + import msvcrt # noqa: PLC0415 + + stream.seek(0) + msvcrt.locking(stream.fileno(), msvcrt.LK_NBLCK, 1) + else: + import fcntl # noqa: PLC0415 + + fcntl.flock(stream, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BaseException: + stream.close() + raise + return stream + + +@functools.cache +def _recover_views(views: Path, pid: int): + """Remove abandoned filename trees once per process, under the directory lock.""" + for old in views.iterdir(): + if not re.fullmatch("[0-9a-f]{32}", old.name) or old.is_symlink() or not old.is_dir(): + continue + try: + with _lock_view(old / "owner"): + pass + except OSError: + continue + shutil.rmtree(old, ignore_errors=True) + + +class AssetLease(contextlib.ExitStack): + """Owns OVStorage delegates and the filesystem names that a USD consumer can open.""" + + def __init__(self, sources: dict[str, str]): + super().__init__() + self.sources = sources + self.directory = cache_directory() / "views" / uuid.uuid4().hex + self.active = False + self.pid = os.getpid() + + def prepare(self, path: Path) -> None: + if not self.active: + views = self.directory.parent + views.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + views.mkdir(mode=0o700, exist_ok=True) + # No other process can observe a new directory before its owner holds the lock. + with FileLock(views / "sessions.lock"): + _recover_views(views, self.pid) + self.directory.mkdir(mode=0o700) + marker = _lock_view(self.directory / "owner") + self.callback(self._remove_view, marker) + self.active = True + path.parent.mkdir(exist_ok=True, parents=True) + + def _remove_view(self, marker: BinaryIO) -> None: + with FileLock(self.directory.parent / "sessions.lock"): + marker.close() + shutil.rmtree(self.directory, ignore_errors=True) + + def publish(self, content: bytes | ovstorage.LocalDelegate, path: Path, source: str) -> None: + if isinstance(content, ovstorage.LocalDelegate): + delegate = self.enter_context(content) + else: + address = "isaaclab-content:///" + hashlib.sha256(content).hexdigest() + with _PUBLISH_LOCK: + origin, cache = _published_stack(cache_directory()) + origin.payload = content + try: + delegate = cached_delegate(cache, address) + if delegate is None: + run(cache.read(address)) + delegate = cached_delegate(cache, address) + if delegate is not None: + self.enter_context(delegate) + finally: + origin.payload = b"" + self.prepare(path) + if delegate is None: + # An object larger than the cache budget still has the lifetime of its tree. + path.write_bytes(content) + else: + # Both names are on the cache filesystem. Hard links preserve USD's + # filename-based format selection and work on Windows without symlink privileges. + try: + os.link(delegate.path, path) + except OSError as exc: + if exc.errno not in (errno.EXDEV, errno.EPERM, errno.ENOTSUP) and getattr(exc, "winerror", None) != 1: + raise + shutil.copyfile(delegate.path, path) + self.sources[str(path)] = source + self.callback(self.sources.pop, str(path), None) + + def close(self) -> None: + if self.pid == os.getpid(): + super().close() diff --git a/source/isaaclab/isaaclab/utils/assets.py b/source/isaaclab/isaaclab/utils/assets.py index 4609dbfb31cd..1d7567769fe0 100644 --- a/source/isaaclab/isaaclab/utils/assets.py +++ b/source/isaaclab/isaaclab/utils/assets.py @@ -13,11 +13,10 @@ .. _Omniverse Nucleus: https://docs.omniverse.nvidia.com/nucleus/latest/overview/overview.html """ -import asyncio +import atexit import contextlib -import functools +import hashlib import io -import json import logging import ntpath import os @@ -26,18 +25,18 @@ import shutil import tempfile import threading -import uuid import warnings -from collections.abc import Coroutine, Iterator, Sequence +from collections.abc import Iterator, Sequence +from pathlib import Path from typing import Any, Literal, NotRequired, TypedDict from urllib.parse import urlparse import ovstorage -from filelock import FileLock from ovstorage.plugin import PluginBackend from ovstorage.redirect_follower import RedirectFollower from ..paths import ISAACLAB_ROOT +from . import _asset_cache logger = logging.getLogger(__name__) @@ -136,27 +135,18 @@ def configure_storage_profile() -> None: _OVSTORAGE_LOCK = threading.Lock() """Guards the lazily built OVStorage stacks.""" -_OVSTORAGE_STACKS: dict[str, ovstorage.LayerBase] = {} +_OVSTORAGE_STACKS: dict[tuple[str, Path | None], ovstorage.LayerBase] = {} """Built OVStorage stack per URL origin, since each OVStorage connection serves one origin.""" -@functools.cache -def _ovstorage_loop() -> ovstorage.OwnedLoop: - """Event loop thread driving every OVStorage stack, started on first use.""" - return ovstorage.OwnedLoop() - - -def _ovstorage_run(coroutine: Coroutine[Any, Any, Any]) -> Any: - """Run an OVStorage coroutine on its event loop thread and return the result.""" - return asyncio.run_coroutine_threadsafe(coroutine, _ovstorage_loop().loop).result() - - -def _ovstorage_stack(url: str) -> ovstorage.LayerBase: +def _ovstorage_stack(url: str, *, cache_bytes: bool = False) -> ovstorage.LayerBase: """Return the OVStorage stack serving ``url``'s origin, building it on first use.""" parsed = urlparse(url) origin = f"{parsed.scheme}://{parsed.netloc}" + directory = _asset_cache.cache_directory() if cache_bytes else None + key = (origin, directory) with _OVSTORAGE_LOCK: - if origin not in _OVSTORAGE_STACKS: + if key not in _OVSTORAGE_STACKS: if parsed.scheme == "omniverse": kind, config = "nucleus", {"server": parsed.netloc} else: @@ -168,69 +158,38 @@ def _ovstorage_stack(url: str) -> ovstorage.LayerBase: ) kind, config = "http", {"prefix": f"{origin}/", "root_url": cdn_url} request = ovstorage.ConnectionRequest(kind) - for key, value in config.items(): - request.add_config(key, ovstorage.ConfigValue.string(value)) + for name, value in config.items(): + request.add_config(name, ovstorage.ConfigValue.string(value)) stack = ( - ovstorage.Stack(root="redirects") + ovstorage.Stack(root="cache" if cache_bytes else "redirects") .with_registry(ovstorage.PluginRegistry([str(ovstorage.bundled_plugins_dir())])) .wrapper(RedirectFollower("redirects", "origin")) .backend(PluginBackend(kind, "origin")) .connection("origin", request) ) - _OVSTORAGE_STACKS[origin] = _ovstorage_run(stack.build()) - return _OVSTORAGE_STACKS[origin] - - -def _remote_stat(url: str) -> dict | None: - """Revision metadata of ``url``, or ``None`` when the server does not report the file.""" - url = url.replace(os.sep, "/") - try: - info = _ovstorage_run(_ovstorage_stack(url).stat(url)) - except ovstorage.Error: - # an unreachable server reads as unreported too, so offline runs keep using their local copies - return None - return { - "hash": info.etag or "", - "version": info.version or "", - "size": info.size or 0, - "modified_time": str(info.mtime_unix_nanos or ""), - } - + if directory is not None: + _asset_cache.wrap_reads(stack, directory) + _OVSTORAGE_STACKS[key] = _asset_cache.run(stack.build()) + return _OVSTORAGE_STACKS[key] -async def _materialize(stack: ovstorage.LayerBase, url: str, target: str) -> None: - """Copy ``url`` to the local file ``target``, releasing OVStorage's lease on its local copy.""" - async with await stack.materialize(url) as delegate: - shutil.copyfile(delegate.path, target) - -def _remote_copy(url: str, target: str) -> None: - """Download ``url`` to the local file ``target``. - - Raises: - FileNotFoundError: When the server does not have the file. - RuntimeError: When the download fails. - """ +def _remote_read(url: str, *, force_download: bool = False, lease: bool = False) -> bytes | ovstorage.LocalDelegate: + """Read a remote file, optionally returning a lease on its cached bytes.""" url = url.replace(os.sep, "/") try: - _ovstorage_run(_materialize(_ovstorage_stack(url), url, target)) + stack = _ovstorage_stack(url, cache_bytes=not force_download) + if lease and not force_download: + delegate = _asset_cache.cached_delegate(stack, url) + if delegate is not None: + return delegate + data, info = _asset_cache.run(stack.read_bytes(url)) + if lease and not force_download and info.etag_strength == "strong": + delegate = _asset_cache.cached_delegate(stack, url) + if delegate is not None: + return delegate + return data except ovstorage.NotFoundError as exc: raise FileNotFoundError(f"Unable to find the file: {url}") from exc - except ovstorage.Error as exc: - raise RuntimeError(f"Unable to copy file: '{url}' ({exc})") from exc - - -def _remote_read(url: str) -> bytes: - """Read the contents of ``url``. - - Raises: - FileNotFoundError: When the server does not have the file. - """ - url = url.replace(os.sep, "/") - try: - data, _ = _ovstorage_run(_ovstorage_stack(url).read_bytes(url)) - except ovstorage.NotFoundError as exc: - raise FileNotFoundError(f"Unable to find the file: {url}") from exc - return data def _resolve_asset_root() -> str: @@ -280,225 +239,129 @@ def _resolve_asset_root() -> str: SIMREADY_SEARCH_SERVICE_ENDPOINT: str = "https://search.simready.omniverse.nvidia.com/" """Default SimReady USD-Search service endpoint.""" -_MIRROR_FINGERPRINT_SUFFIX = ".isaaclab-cache.json" -"""Suffix of the sidecar file recording the remote revision a locally cached asset came from.""" - -_REMOTE_FINGERPRINTS: dict[str, dict] = {} -"""Successful remote metadata queries, refreshed by forced retrieval.""" - -_ANNOUNCED_MIRROR_DIRS: set[str] = set() -"""Cache directories already announced, so the banner is logged once per directory.""" - -_ANNOUNCED_MIRRORS: set[str] = set() -"""URLs already announced, so an asset consulted repeatedly is logged once.""" +_LEASED_SOURCES: dict[str, str] = {} +_SAVED_SOURCES: dict[str, str] = {} -_ASSET_SOURCES: dict[str, tuple[str, str]] = {} -"""Original source and download directory of each managed copy.""" +def get_asset_source(path: str, *, leased_only: bool = False) -> str: + """Return the source of a localized path, or an empty string if its source is unknown. -def _mirror_path(url: str, download_dir: str) -> str: - """Local path a remote ``url`` mirrors to under ``download_dir``, or ``""`` if not a URL. - - The scheme and host are part of the mirror layout so that two servers exposing the same - path (for instance a cloud and an on-prem Nucleus) do not share a cache entry. + Pass leased_only=True to exclude permanent copies saved to an explicit download directory. """ - parsed = urlparse(url.replace(os.sep, "/")) - if not parsed.scheme or not parsed.path: - return "" - # ':' (port separator) is not a valid path character on Windows - netloc = parsed.netloc.replace(":", "_") - mirrored = os.path.join(download_dir, parsed.scheme, netloc, *parsed.path.lstrip("/").split("/")) - # a host is what distinguishes a remote URL from a Windows drive letter, which ``urlparse`` - # also reports as a scheme - if parsed.netloc: - _ASSET_SOURCES[os.path.abspath(mirrored)] = (url, download_dir) - return mirrored + local = os.path.abspath(path) + source = _LEASED_SOURCES.get(local, "") + return source if source or leased_only else _SAVED_SOURCES.get(local, "") def unmirror_file_path(path: str) -> str: - """Maps a locally cached asset copy back to the URL it was downloaded from. - - :func:`retrieve_file_path` hands callers a local copy of a remote asset, so a stage built - from one records a path that only resolves on the machine holding the cache. An export of - that stage can use this to name the source asset instead. - - Only copies this process located are known, so a locally authored path is never mistaken - for a cached copy. A copy mirrored by an earlier run is still recognised, because retrieval - walks the whole dependency tree even when every file is already cached. - - Args: - path: Local filesystem path, typically an asset path read from a USD layer. - - Returns: - The URL the copy was cached from, or ``""`` when this process did not cache it. - """ - source, _ = _ASSET_SOURCES.get(os.path.abspath(path), ("", "")) + """Return the URL a local copy was downloaded from, or an empty string.""" + source = get_asset_source(path) return source if _is_remote_path(source) else "" -def _remote_fingerprint(url: str) -> dict | None: - """Provider metadata identifying the revision of ``url`` the server currently holds. - - Every reported field is kept, because which ones a provider fills in varies: a Nucleus - server reporting a content hash and an HTTP host reporting only a size and a modification - time both yield a usable revision marker. - - Successful queries are reused until forced retrieval. Failed queries are not cached, - so a missing file or an unreachable server can be retried. - - Args: - url: Remote asset URL. - - Returns: - The reported metadata, or ``None`` when the server does not report the file. That - covers both a missing file and an unreachable server, which are not distinguished here. - """ - if url not in _REMOTE_FINGERPRINTS: - fingerprint = _remote_stat(url) - if fingerprint is None: - return None - _REMOTE_FINGERPRINTS[url] = fingerprint - return _REMOTE_FINGERPRINTS[url] - - -def _write_mirror_fingerprint(url: str, mirrored: str) -> None: - """Record the remote revision a freshly cached copy was taken from.""" - fingerprint = _remote_fingerprint(url) - if fingerprint is None: - return - try: - with open(mirrored + _MIRROR_FINGERPRINT_SUFFIX, "w", encoding="utf-8") as f: - json.dump(fingerprint, f) - except OSError as exc: - # a copy we cannot annotate is simply re-fetched on the next run - logger.debug("Unable to record the asset cache fingerprint for '%s': %s", url, exc) - - -def _mirror_is_current(url: str, mirrored: str) -> bool: - """Whether the locally cached copy of ``url`` still matches what the server holds. - - A copy with no recorded fingerprint counts as outdated, so copies left by earlier Isaac Lab - versions are re-fetched once and annotated. When the answer cannot be obtained at all -- - an unreachable server, or a provider that reports no metadata -- the copy is used anyway - and the missing guarantee is logged, so offline runs keep working. - """ - remote = _remote_fingerprint(url) - if remote is None: - logger.warning( - "Asset server did not respond for '%s'. Using the local copy at '%s', which may be out of date.", - url, - mirrored, - ) - return True - if not any(remote.values()): - logger.warning( - "Asset server reports no revision metadata for '%s'. Using the local copy at '%s' without a" - " freshness check.", - url, - mirrored, - ) - return True - try: - with open(mirrored + _MIRROR_FINGERPRINT_SUFFIX, encoding="utf-8") as f: - return json.load(f) == remote - except (OSError, ValueError): - return False - - -def _announce_local_asset(url: str, mirrored: str, download_dir: str) -> None: - """Announce, once per cache directory and once per asset, that a local copy is being used.""" - if download_dir not in _ANNOUNCED_MIRROR_DIRS: - _ANNOUNCED_MIRROR_DIRS.add(download_dir) - logger.warning( - "Serving remote assets from the local cache under '%s'. Each copy is checked against the server" - " before use; delete the directory to force a full re-download.", - download_dir, - ) - if url not in _ANNOUNCED_MIRRORS: - _ANNOUNCED_MIRRORS.add(url) - logger.info("Loading local copy of remote asset '%s' from '%s'.", url, mirrored) - - -def _usable_mirror(url: str, download_dir: str | None = None) -> str: - """Local copy to serve ``url`` from, or ``""`` when it has to come from the server.""" - download_dir = download_dir or tempfile.gettempdir() - mirrored = _mirror_path(url, download_dir) - if not mirrored or not os.path.isfile(mirrored) or not _mirror_is_current(url, mirrored): - return "" - _announce_local_asset(url, mirrored, download_dir) - return mirrored - - -def _store_mirror(url: str, data: bytes) -> None: - """Cache a payload that was just read from the server, so later runs can reuse it.""" - mirrored = _mirror_path(url, tempfile.gettempdir()) - if not mirrored: - return - try: - os.makedirs(os.path.dirname(mirrored), exist_ok=True) - with FileLock(mirrored + ".lock"): - temporary_path = f"{mirrored}.{uuid.uuid4().hex}.partial" - try: - with open(temporary_path, "wb") as f: - f.write(data) - os.replace(temporary_path, mirrored) - finally: - with contextlib.suppress(OSError): - os.remove(temporary_path) - _write_mirror_fingerprint(url, mirrored) - except OSError as exc: - logger.debug("Unable to cache the asset '%s' locally: %s", url, exc) - - def check_file_path(path: str) -> Literal[0, 1, 2]: - """Checks if a file exists on the Nucleus Server or locally. - - Args: - path: The path to the file. - - Returns: - The status of the file. Possible values are listed below. - - * :obj:`0` if the file does not exist - * :obj:`1` if the file exists locally - * :obj:`2` if the file exists on the Nucleus Server - """ + """Return 1 for local files, 2 for available remote files, or 0 for missing files.""" if os.path.isfile(path): return 1 - - # a locally cached copy that still matches the server answers this without a download - if _usable_mirror(path): + if not _is_remote_path(path): + return 0 + url = path.replace(os.sep, "/") + try: + _asset_cache.run(_ovstorage_stack(url).stat(url)) return 2 - - return 2 if _remote_fingerprint(path) is not None else 0 + except ovstorage.NotFoundError: + return 0 + except ovstorage.Error: + if _asset_cache.cache_directory().is_dir(): + try: + delegate = _asset_cache.cached_delegate(_ovstorage_stack(url, cache_bytes=True), url) + except ovstorage.Error: + return 0 + if delegate is not None: + with delegate: + return 2 + return 0 -def retrieve_file_path(path: str, download_dir: str | None = None, force_download: bool = False) -> str: - """Retrieves the path to a file on the Nucleus Server or locally. +@contextlib.contextmanager +def lease_file_path(path: str, force_download: bool = False) -> Iterator[str]: + """Yield a read-only local asset path and retain its USD dependencies until context exit. - USD layers are localized in the bound resolver context without modifying authored files or - raw downloads. Each retrieval resolves dependencies afresh while reusing downloaded files. - Unresolved references retain their anchors; USD decides which the selected composition requires. - MDL modules, UDIM textures, and USDZ contents keep their native loader's dependency handling. - Localization does not validate composition or rendering readiness. + Keep the context open through deferred payload loads or until a subprocess using the path exits. + Pass force_download=True to fetch fresh bytes from the provider. + """ + lease = _asset_cache.AssetLease(_LEASED_SOURCES) + try: + yield _localize(path, force_download, lease) + finally: + lease.close() - Args: - path: The path to the file. - download_dir: Download directory. Defaults to the system's temporary directory, or the original - cache directory when reusing a managed copy. - force_download: Whether to force download the file from the Nucleus Server. This will overwrite - the local file if it exists. Defaults to False. - Returns: - The path to the file on the local machine. +def retrieve_file_path(path: str, download_dir: str | None = None, force_download: bool = False) -> str: + """Retrieve a local path with USD dependencies resolved in the bound resolver context. - Raises: - FileNotFoundError: When the requested file cannot be resolved or found. - RuntimeError: When a download fails or a resolved USD copy cannot be saved. + With an explicit download directory the caller owns the saved files. Otherwise the returned + path is read-only and available until process exit. Use lease_file_path to release it earlier. + Pass force_download=True to fetch fresh bytes from the provider. """ - root, cached_dir = _ASSET_SOURCES.get(os.path.abspath(path), (path, "")) - download_dir = os.path.abspath(download_dir or cached_dir or tempfile.gettempdir()) - if os.path.splitext(root)[1].lower() in _USD_EXTENSIONS: + with contextlib.ExitStack() as lifetime: + lease = _asset_cache.AssetLease(_LEASED_SOURCES) + lifetime.callback(lease.close) + result = _localize(path, force_download, lease, download_dir) + if lease.active and download_dir is None: + # A string can be handed to consumers that outlive the call. + atexit.register(lifetime.pop_all().close) + return result + + +def _save_download(root: Path, view: Path, directory: Path, localized: dict[str, str]) -> str: + """Publish a caller-owned copy while the complete source tree is leased.""" + source = get_asset_source(str(root)) + if root.is_relative_to(view / "raw"): + url = urlparse(source) + parts = [url.scheme, url.netloc.replace(":", "_"), *url.path.strip("/").split("/")] + if url.query or url.fragment or any(part in {"", ".", ".."} or ntpath.basename(part) != part for part in parts): + parts = [hashlib.sha256(source.encode()).hexdigest(), root.name] + target = directory.joinpath(*parts) + target.parent.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(dir=target.parent) as temporary: + copied = shutil.copyfile(root, Path(temporary) / root.name) + os.replace(copied, target) + _SAVED_SOURCES[str(target)] = source + return str(target) + + # Relative references make the numbered tree portable. Publish a complete revision atomically + # so readers can still load deferred dependencies when a newer revision is downloaded. + files = sorted(path for path in map(Path, localized.values()) if path.is_relative_to(view)) + revision = hashlib.sha256() + for path in files: + revision.update(os.fsencode(path.relative_to(view).as_posix()) + b"\0") + revision.update(os.fsencode(get_asset_source(str(path))) + b"\0") + with path.open("rb") as stream: + revision.update(hashlib.file_digest(stream, "sha256").digest()) + directory.mkdir(parents=True, exist_ok=True) + target = directory / revision.hexdigest() + if not target.exists(): + with tempfile.TemporaryDirectory(dir=directory) as temporary: + tree = Path(temporary) / "layers" + for path in files: + copy = tree / path.relative_to(view) + copy.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(path, copy) + try: + tree.rename(target) + except OSError: + if not target.is_dir(): + raise + for path in files: + _SAVED_SOURCES[str(target / path.relative_to(view))] = get_asset_source(str(path)) + return str(target / root.relative_to(view)) + + +def _localize(path: str, force_download: bool, lease: _asset_cache.AssetLease, download_dir: str | None = None) -> str: + root = get_asset_source(path, leased_only=not force_download) or path + root_name = urlparse(root).path if _is_remote_path(root) else root + if os.path.splitext(root_name)[1].lower() in _USD_EXTENSIONS: from pxr import Ar, Sdf, UsdShade, UsdUtils # noqa: PLC0415 resolver = Ar.GetResolver() @@ -508,21 +371,26 @@ def retrieve_file_path(path: str, download_dir: str | None = None, force_downloa raise FileNotFoundError(f"Unable to resolve the file: {root}") root = str(resolved) root = root.replace(os.sep, "/") if _is_remote_path(root) else os.path.abspath(root) - if force_download: - _REMOTE_FINGERPRINTS.pop(root, None) localized = {} - copy_dir = os.path.join(download_dir, f"isaaclab_usd_{uuid.uuid4().hex}") + copy_dir = str(lease.directory) def localize(source: str) -> str: if source in localized: return localized[source] remote = _is_remote_path(source) - # Read detached contents while the download lock protects the raw mirror. - with _download_file(source, download_dir, force_download) as local_path: - suffix = os.path.splitext(local_path)[1].lower() - if suffix in _USD_EXTENSIONS: - layer = Sdf.Layer.OpenAsAnonymous(local_path) + name = ntpath.basename(urlparse(source).path) if remote else os.path.basename(source) + if remote: + if name in {"", ".", ".."} or ":" in name: + raise ValueError(f"Invalid asset filename in {source!r}") + raw = lease.directory / "raw" / str(len(localized)) / name + lease.publish(_remote_read(source, force_download=force_download, lease=True), raw, source) + local_path = str(raw) + else: + if not os.path.isfile(source): + raise FileNotFoundError(f"Unable to find the file: {source}") + local_path = source + suffix = os.path.splitext(name)[1].lower() localized[source] = local_path if suffix not in _USD_EXTENSIONS: return local_path @@ -530,6 +398,7 @@ def localize(source: str) -> str: # Reserve before descending so shared children and cycles have one destination. output = os.path.join(copy_dir, str(len(localized)), os.path.basename(local_path)) localized[source] = output + layer = Sdf.Layer.OpenAsAnonymous(local_path) anchor = Ar.ResolvedPath(local_path) changed = False @@ -540,32 +409,43 @@ def rewrite(ref: str) -> str: dependency = _resolve_reference_url(source, ref) identifier = ref if _is_remote_path(ref) else resolver.CreateIdentifier(ref, anchor) if UsdShade.UdimUtils.IsUdimIdentifier(ref): - # Keep the pattern on its source, not on a partially populated mirror. + # The native texture loader needs the original tile pattern. resolved = dependency if not _is_remote_path(dependency): resolved = UsdShade.UdimUtils.ResolveUdimPath(ref, Sdf.Layer.FindOrOpen(local_path)) or dependency else: if not _is_remote_path(dependency): dependency = str(resolver.Resolve(identifier)) or identifier - if force_download and dependency not in localized: - _REMOTE_FINGERPRINTS.pop(dependency, None) - exists = check_file_path(dependency) if ref.endswith(".mdl"): - # Keep native module names; anchor explicit paths to the source, not the download mirror. - resolved = dependency if exists or identifier != ref else identifier - elif exists: + # The MDL loader resolves module names. Explicit paths retain their source anchor. + resolved = dependency if identifier != ref or check_file_path(dependency) else identifier + elif _is_remote_path(dependency): + # An offline byte-cache hit can compose even when the provider cannot stat it. + try: + resolved = localize(dependency) + except FileNotFoundError: + resolved = dependency + except ovstorage.TransientBucketError: + if check_file_path(dependency): + raise + resolved = dependency + elif check_file_path(dependency): resolved = localize(dependency) else: resolved = dependency changed |= resolved != (_resolve_reference_url(local_path, ref) if remote else dependency) + if resolved.startswith(copy_dir + os.sep): + return os.path.relpath(resolved, os.path.dirname(output)).replace(os.sep, "/") return resolved UsdUtils.ModifyAssetPaths(layer, rewrite) if changed: - os.makedirs(os.path.dirname(output)) - if not layer.Export(output): + staging = Path(output).with_name(".staging-" + name) + lease.prepare(staging) + if not layer.Export(str(staging)): raise RuntimeError(f"Unable to save resolved USD layer: {output}") - _ASSET_SOURCES[output] = (source, download_dir) + lease.publish(staging.read_bytes(), Path(output), source) + staging.unlink() else: localized[source] = local_path return localized[source] @@ -574,34 +454,16 @@ def rewrite(ref: str) -> str: report_activity("Loading assets") try: - return localize(root) + result = localize(root) + if download_dir is not None and Path(result).is_relative_to(lease.directory): + return _save_download(Path(result), lease.directory, Path(download_dir).absolute(), localized) + return result + except ovstorage.Error as exc: + raise RuntimeError(f"Unable to localize asset '{root}': {exc}") from exc finally: report_activity(None) -@contextlib.contextmanager -def _download_file(source: str, download_dir: str, force_download: bool) -> Iterator[str]: - """Yield a local file while holding its remote mirror's download lock.""" - if not _is_remote_path(source): - if not os.path.isfile(source): - raise FileNotFoundError(f"Unable to find the file: {source}") - yield source - return - target = _mirror_path(source, download_dir) - os.makedirs(os.path.dirname(target), exist_ok=True) - with FileLock(target + ".lock"): - if force_download or not _usable_mirror(source, download_dir): - temporary_path = f"{target}.{uuid.uuid4().hex}.partial" - try: - _remote_copy(source, temporary_path) - os.replace(temporary_path, target) - _write_mirror_fingerprint(source, target) - finally: - with contextlib.suppress(OSError): - os.remove(temporary_path) - yield target - - def read_file(path: str) -> io.BytesIO: """Reads a file from the Nucleus Server or locally. @@ -614,26 +476,10 @@ def read_file(path: str) -> io.BytesIO: Returns: The content of the file. """ - # check file status - file_status = check_file_path(path) - if file_status == 1: - with open(path, "rb") as f: - return io.BytesIO(f.read()) - elif file_status == 2: - # Read the local copy when an earlier run already fetched this revision. Actuator - # networks and similar payloads are read at every startup, so a remote read re-downloads - # megabytes that :func:`retrieve_file_path` already cached. - mirrored = _usable_mirror(path) - if mirrored: - with open(mirrored, "rb") as f: - return io.BytesIO(f.read()) - - data = _remote_read(path) - # cache what was just downloaded, so the next run reads it from disk - _store_mirror(path, data) - return io.BytesIO(data) - else: - raise FileNotFoundError(f"Unable to find the file: {path}") + if _is_remote_path(path): + return io.BytesIO(_remote_read(path)) + with open(path, "rb") as f: + return io.BytesIO(f.read()) def search_simready_usd_paths( diff --git a/source/isaaclab/test/sim/test_usd_export.py b/source/isaaclab/test/sim/test_usd_export.py index 031b3ce8fff6..8201772a7ddd 100644 --- a/source/isaaclab/test/sim/test_usd_export.py +++ b/source/isaaclab/test/sim/test_usd_export.py @@ -472,17 +472,16 @@ def test_relative_references_of_a_scene_opened_from_a_file_resolve_in_another_di assert exported.GetPrimAtPath("/World/Robot").GetTypeName() == "Xform" -def test_a_cached_remote_asset_is_referenced_by_its_url_without_opening_it(tmp_path, capfd, caplog): +def test_a_cached_remote_asset_is_referenced_by_its_url_without_opening_it(tmp_path, capfd, caplog, monkeypatch): """The export names a cached remote asset by its URL in a copy no stage composes, so nothing opens the URL. An import resolves the URL only with a resolver that fetches it, so the export warns about it. """ url = "https://example.com/Robots/robot.usda" - cached = Path(assets_utils._mirror_path(url, str(tmp_path / "cache"))) - cached.parent.mkdir(parents=True) - robot = Usd.Stage.CreateNew(str(cached)) - robot.SetDefaultPrim(robot.DefinePrim("/Robot", "Xform")) - robot.Save() + monkeypatch.setenv("XDG_CACHE_HOME", str(tmp_path / "cache")) + data = b'#usda 1.0\n(defaultPrim = "Robot")\ndef Xform "Robot" {}\n' + monkeypatch.setattr(assets_utils, "_remote_read", lambda url, **kwargs: data) + cached = assets_utils.retrieve_file_path(url) stage = Usd.Stage.CreateInMemory() stage.DefinePrim("/World/Robot").GetReferences().AddReference(str(cached)) exporter = _Exporter(_scene(stage=stage, cable_objects={})) diff --git a/source/isaaclab/test/utils/test_assets.py b/source/isaaclab/test/utils/test_assets.py index c73f597b7d11..30934fd3cec3 100644 --- a/source/isaaclab/test/utils/test_assets.py +++ b/source/isaaclab/test/utils/test_assets.py @@ -6,13 +6,14 @@ from __future__ import annotations import functools +import gc +import hashlib import http.server import importlib -import json import logging -import os +import subprocess +import sys import threading -import time import types from concurrent.futures import ThreadPoolExecutor from pathlib import Path @@ -173,13 +174,7 @@ def test_localized_usd_preserves_material_resource_anchors(asset_cache, monkeypa payloads = {f"https://example.com/{name}": data for name, data in payloads.items()} payloads[_REMOTE_URL] = '#usda 1.0\ndef Xform "Remote" {}\n' - revision = {"hash": "abc123", "version": "", "size": 32, "modified_time": "2026-07-01 10:00:00"} - _serve(monkeypatch, dict.fromkeys(payloads, revision)) - - def copy(url, target_path): - Path(target_path).write_text(payloads[url]) - - monkeypatch.setattr(assets_utils, "_remote_copy", copy) + _serve(monkeypatch, {url: data.encode() for url, data in payloads.items()}) source = "https://example.com/scene.usda" if remote else str(asset_cache / "scene.usda") result = assets_utils.retrieve_file_path(source) assert result != source @@ -206,44 +201,28 @@ def test_resolve_reference_url_treats_windows_drive_as_local_path(): @pytest.fixture def asset_cache(tmp_path, monkeypatch): """Isolate the local asset cache: an empty cache directory and no state from other tests.""" - monkeypatch.setattr(assets_utils.tempfile, "gettempdir", lambda: str(tmp_path)) - monkeypatch.setattr(assets_utils, "_REMOTE_FINGERPRINTS", {}) - monkeypatch.setattr(assets_utils, "_ANNOUNCED_MIRROR_DIRS", set()) - monkeypatch.setattr(assets_utils, "_ANNOUNCED_MIRRORS", set()) - monkeypatch.setattr(assets_utils, "_ASSET_SOURCES", {}) + monkeypatch.setenv("XDG_CACHE_HOME", str(tmp_path / "cache")) return tmp_path -def _serve(monkeypatch, entries: dict[str, dict | None], payloads: dict[str, bytes] | None = None) -> None: - """Fake the asset server: ``entries`` maps a URL to its reported metadata (``None`` = absent).""" - - def fake_stat(url): - reported = entries.get(url) - return None if reported is None else dict(reported) - - def fake_read(url): - if payloads is None or url not in payloads: - raise AssertionError(f"the server should not have been read for: {url}") - return payloads[url] - - monkeypatch.setattr(assets_utils, "_remote_stat", fake_stat) - monkeypatch.setattr(assets_utils, "_remote_read", fake_read) +def _serve(monkeypatch, payloads: dict[str, bytes]) -> None: + def read(url, **kwargs): + try: + return payloads[url] + except KeyError as exc: + raise FileNotFoundError(url) from exc - -def _cache_asset(cache_dir, url: str, payload: bytes, fingerprint: dict | None) -> Path: - """Write a locally cached copy of ``url``, with its recorded remote revision.""" - mirrored = Path(assets_utils._mirror_path(url, str(cache_dir))) - mirrored.parent.mkdir(parents=True, exist_ok=True) - mirrored.write_bytes(payload) - if fingerprint is not None: - (mirrored.parent / (mirrored.name + assets_utils._MIRROR_FINGERPRINT_SUFFIX)).write_text( - json.dumps(fingerprint), encoding="utf-8" - ) - return mirrored + local_check = assets_utils.check_file_path + monkeypatch.setattr(assets_utils, "_remote_read", read) + monkeypatch.setattr( + assets_utils, + "check_file_path", + lambda path: (2 if path in payloads else 0) if "://" in path else local_check(path), + ) @pytest.mark.parametrize("layout", ["direct", "nested", "remote", "package"]) -def test_local_usd_mirrors_remote_sublayer_without_editing_source(asset_cache, monkeypatch, layout): +def test_local_usd_localizes_remote_sublayer_without_editing_source(asset_cache, monkeypatch, layout): """Compose local and remote dependency chains without editing the authored layers.""" from pxr import Sdf, Usd @@ -260,15 +239,7 @@ def test_local_usd_mirrors_remote_sublayer_without_editing_source(asset_cache, m root_url: layers["robot.usda"], "https://example.com/local.usda": layers["local.usda"], } - revision = {"hash": "abc123", "version": "", "size": 32, "modified_time": "2026-07-01 10:00:00"} - - def fake_copy(url, target_path): - if url not in payloads: - raise FileNotFoundError(url) - data = payloads[url] - Path(target_path).write_bytes(data.encode() if isinstance(data, str) else data) - monkeypatch.setattr(assets_utils, "_remote_copy", fake_copy) source = {"direct": str(asset_cache / "robot.usda"), "nested": str(asset_cache / "scene.usda"), "remote": root_url} if layout == "package": source[layout] = _REMOTE_URL + "z" @@ -279,7 +250,10 @@ def fake_copy(url, target_path): package.AddFile(str(package_root), "package.usda") package.AddFile(str(asset_cache / "local.usda"), "local.usda") payloads[source[layout]] = package_path.read_bytes() - _serve(monkeypatch, dict.fromkeys(payloads, revision)) + _serve( + monkeypatch, + {url: data.encode() if isinstance(data, str) else data for url, data in payloads.items()}, + ) resolved_path = assets_utils.retrieve_file_path(source[layout]) stage = Usd.Stage.Open(resolved_path) assert stage.GetPrimAtPath("/cartpole").IsValid() @@ -314,14 +288,7 @@ def test_local_usd_preserves_search_paths_and_relative_sublayers(asset_cache, mo prim.variantSetNameList.prependedItems = ["model"] prim.variantSelections["model"] = "available" layer.Save() - revision = {"hash": "abc123", "version": "", "size": 32, "modified_time": "2026-07-01 10:00:00"} - _serve(monkeypatch, {_REMOTE_URL: revision}) - - def fake_copy(url, target_path): - assert url == _REMOTE_URL - Path(target_path).write_text('#usda 1.0\ndef Xform "remote" {}\n', encoding="utf-8") - - monkeypatch.setattr(assets_utils, "_remote_copy", fake_copy) + _serve(monkeypatch, {_REMOTE_URL: b'#usda 1.0\ndef Xform "remote" {}\n'}) for name in ("first", "second"): directory = search_dir / name directory.mkdir() @@ -345,45 +312,28 @@ def fake_copy(url, target_path): assert not resolved_stage.GetCompositionErrors() -@pytest.mark.parametrize("failure", ["transfer", "missing"]) -@pytest.mark.parametrize("force_download", [False, True]) -def test_retrieve_file_path_retries_incomplete_tree(asset_cache, monkeypatch, failure, force_download): - """Retry failed or unavailable dependencies; forced downloads also refresh revision metadata.""" - from pxr import Usd +def test_retrieve_file_path_retries_incomplete_tree(asset_cache, monkeypatch): + """A missing dependency can become available on a later retrieval.""" + from pxr import Sdf, Usd - child_url = _REMOTE_URL.replace("example.usd", "child.usda") - revision = {"hash": "abc123", "version": "", "size": 32, "modified_time": "2026-07-01 10:00:00"} - root = b"#usda 1.0\n(subLayers = [@child.usda@])\n" - mirrored = _cache_asset(asset_cache, _REMOTE_URL, root, revision) - entries = {_REMOTE_URL: revision, child_url: revision if failure == "transfer" else None} - _serve(monkeypatch, entries) - fail_child = True - - def fake_copy(url, target_path): - if url == _REMOTE_URL: - Path(target_path).write_bytes(root) - return - if fail_child: - raise RuntimeError("transfer failed") - Path(target_path).write_text('#usda 1.0\ndef Xform "child" {}\n', encoding="utf-8") - - monkeypatch.setattr(assets_utils, "_remote_copy", fake_copy) - if failure == "transfer": - with pytest.raises(RuntimeError): - assets_utils.retrieve_file_path(_REMOTE_URL) - else: - assets_utils.retrieve_file_path(_REMOTE_URL) - fail_child = False - entries[child_url] = revision - if force_download: - entries[_REMOTE_URL] = {**revision, "hash": "new-revision"} - resolved = assets_utils.retrieve_file_path(str(mirrored), force_download=force_download) - stage = Usd.Stage.Open(resolved) - assert stage.GetPrimAtPath("/child").IsValid() - assert json.loads(Path(str(mirrored) + assets_utils._MIRROR_FINGERPRINT_SUFFIX).read_text()) == entries[_REMOTE_URL] + payloads = {_REMOTE_URL: b"#usda 1.0\n(subLayers = [@child.usda@])\n"} + _serve(monkeypatch, payloads) + with assets_utils.lease_file_path(_REMOTE_URL) as first: + child_url = _REMOTE_URL.replace("example.usd", "child.usda") + assert child_url in Sdf.Layer.FindOrOpen(first).subLayerPaths + payloads[child_url] = b'#usda 1.0\ndef Xform "Child" {}\n' + with assets_utils.lease_file_path(first) as second: + stage = Usd.Stage.Open(second) + assert stage.GetPrimAtPath("/Child").IsValid() class _QuietHandler(http.server.SimpleHTTPRequestHandler): + def end_headers(self): + path = Path(self.translate_path(self.path)) + if path.is_file(): + self.send_header("ETag", f'"{hashlib.sha256(path.read_bytes()).hexdigest()}"') + super().end_headers() + def log_message(self, format, *args): pass @@ -410,16 +360,61 @@ def test_http_assets_are_retrieved(asset_cache, http_assets): (served / "actuator.pt").write_bytes(b"network weights") assert assets_utils.check_file_path(f"{root}/robot.usda") == 2 - stage = Usd.Stage.Open(assets_utils.retrieve_file_path(f"{root}/robot.usda")) - assert stage.GetPrimAtPath("/Robot").IsValid() - assert stage.GetPrimAtPath("/Base").IsValid() + with assets_utils.lease_file_path(f"{root}/robot.usda") as path: + stage = Usd.Stage.Open(path) + assert stage.GetPrimAtPath("/Robot").IsValid() + assert stage.GetPrimAtPath("/Base").IsValid() + del stage + assert not Path(path).exists() assert assets_utils.read_file(f"{root}/actuator.pt").read() == b"network weights" + assert not list(asset_cache.glob("http/**/actuator.pt")) # a missing asset is reported as absent rather than as a download failure assert assets_utils.check_file_path(f"{root}/missing.usda") == 0 with pytest.raises(FileNotFoundError): assets_utils.retrieve_file_path(f"{root}/missing.usda") +@pytest.mark.kitless +def test_stage_retains_leased_payload_across_crash_recovery(asset_cache, http_assets): + """A subsequent process recovers abandoned paths without invalidating a live stage.""" + from pxr import Usd + + from isaaclab.sim.utils.prims import add_usd_reference + + served, root = http_assets + (served / "scene.usda").write_text( + f'#usda 1.0\n(defaultPrim="Robot")\ndef Xform "Robot" {{\n def "Link" (payload=@{root}/body.usda@) {{}}\n}}\n' + ) + (served / "body.usda").write_text('#usda 1.0\n(defaultPrim="Body")\ndef Cube "Body" {}\n') + url = f"{root}/scene.usda" + stage = Usd.Stage.CreateInMemory(load=Usd.Stage.LoadNone) + robot = add_usd_reference("/Robot", url, stage=stage) + live = Path(robot.GetMetadata("references").GetAppliedItems()[0].assetPath) + child = """ +import os, sys +from isaaclab.utils.assets import retrieve_file_path +print(retrieve_file_path(sys.argv[1]), flush=True) +if sys.argv[2] == "crash": + os._exit(0) +""" + + def run_child(mode): + result = subprocess.run( + [sys.executable, "-c", child, url, mode], check=True, capture_output=True, text=True, timeout=60 + ) + return Path(result.stdout.strip().splitlines()[-1]) + + abandoned = run_child("crash") + assert abandoned.is_file() + assert not run_child("normal").exists() + assert not abandoned.exists() + stage.Load("/Robot/Link") + assert stage.GetPrimAtPath("/Robot/Link").GetTypeName() == "Cube" + del robot, stage + gc.collect() + assert not live.exists() + + def test_region_profile_reads_through_its_cdn(asset_cache, http_assets, monkeypatch): """Test an asset region profile's object-storage endpoint is read through its CDN, selected or not.""" served, root = http_assets @@ -431,164 +426,90 @@ def test_region_profile_reads_through_its_cdn(asset_cache, http_assets, monkeypa assert assets_utils.read_file("https://bucket.invalid/Assets/robot.usda").read().startswith(b"#usda 1.0") -def test_read_file_uses_the_local_copy_when_it_matches_the_server(asset_cache, monkeypatch): - """Test an unchanged remote asset is read from disk instead of downloaded again.""" - revision = {"hash": "abc123", "version": "", "size": 12, "modified_time": "2026-07-01 10:00:00"} - _cache_asset(asset_cache, _REMOTE_URL, b"cached bytes", revision) - # no payload is served, so any read from the server fails the test - _serve(monkeypatch, {_REMOTE_URL: revision}) - - assert assets_utils.read_file(_REMOTE_URL).read() == b"cached bytes" - - -def test_read_file_refetches_when_the_server_copy_changed(asset_cache, monkeypatch): - """Test a changed remote asset is downloaded again rather than served stale.""" - stale = {"hash": "abc123", "version": "", "size": 12, "modified_time": "2026-07-01 10:00:00"} - current = {"hash": "def456", "version": "", "size": 11, "modified_time": "2026-07-29 10:00:00"} - mirrored = _cache_asset(asset_cache, _REMOTE_URL, b"cached bytes", stale) - _serve(monkeypatch, {_REMOTE_URL: current}, payloads={_REMOTE_URL: b"fresh bytes"}) - - assert assets_utils.read_file(_REMOTE_URL).read() == b"fresh bytes" - # the refreshed copy is cached under the new revision, so the next run reads it from disk - assert mirrored.read_bytes() == b"fresh bytes" - fingerprint = mirrored.parent / (mirrored.name + assets_utils._MIRROR_FINGERPRINT_SUFFIX) - assert json.loads(fingerprint.read_text(encoding="utf-8")) == current - - -def test_local_copy_without_a_recorded_revision_is_refetched(asset_cache, monkeypatch): - """Test copies left by earlier versions are re-fetched once instead of trusted blindly.""" - _cache_asset(asset_cache, _REMOTE_URL, b"cached bytes", fingerprint=None) - current = {"hash": "def456", "version": "", "size": 11, "modified_time": "2026-07-29 10:00:00"} - _serve(monkeypatch, {_REMOTE_URL: current}, payloads={_REMOTE_URL: b"fresh bytes"}) - - assert assets_utils.read_file(_REMOTE_URL).read() == b"fresh bytes" - - -def test_retrieve_file_path_serializes_cold_cache_population(asset_cache, monkeypatch): - """Test concurrent ranks reuse the mirror populated by the first rank.""" - revision = {"hash": "abc123", "version": "", "size": 12, "modified_time": "2026-07-01 10:00:00"} - _serve(monkeypatch, {_REMOTE_URL: revision}) - copy_count = 0 - active_copies = 0 - max_active_copies = 0 - counter_lock = threading.Lock() - mirrored = Path(assets_utils._mirror_path(_REMOTE_URL, str(asset_cache))) - - def fake_copy(url, target_path): - nonlocal copy_count, active_copies, max_active_copies - assert url == _REMOTE_URL - assert Path(target_path) != mirrored - with counter_lock: - copy_count += 1 - active_copies += 1 - max_active_copies = max(max_active_copies, active_copies) - time.sleep(0.05) - Path(target_path).write_bytes(b"#usda 1.0\n") - with counter_lock: - active_copies -= 1 - - monkeypatch.setattr(assets_utils, "_remote_copy", fake_copy) - start = threading.Barrier(2) - - def retrieve() -> str: - start.wait() - return assets_utils.retrieve_file_path(_REMOTE_URL, str(asset_cache)) - - with ThreadPoolExecutor(max_workers=2) as executor: - retrieved = list(executor.map(lambda _: retrieve(), range(2))) - - assert retrieved == [str(mirrored)] * 2 - assert mirrored.read_bytes() == b"#usda 1.0\n" - assert copy_count == 1 - assert max_active_copies == 1 - - -def test_size_and_modification_time_identify_a_revision(asset_cache, monkeypatch): - """Test providers that report no hash still get a freshness check. - - The local file provider reports only a size and a modification time, and HTTP hosts - behave the same way, so the check cannot rely on a content hash being available. - """ - revision = {"hash": "", "version": "", "size": 12, "modified_time": "2026-07-01 10:00:00"} - _cache_asset(asset_cache, _REMOTE_URL, b"cached bytes", revision) - _serve(monkeypatch, {_REMOTE_URL: revision}) - assert assets_utils._usable_mirror(_REMOTE_URL) - - assets_utils._REMOTE_FINGERPRINTS.clear() - _serve(monkeypatch, {_REMOTE_URL: {**revision, "modified_time": "2026-07-29 10:00:00"}}) - assert not assets_utils._usable_mirror(_REMOTE_URL) - - -def test_unreachable_server_falls_back_to_the_local_copy(asset_cache, monkeypatch, caplog): - """Test offline runs keep working, with the missing freshness guarantee announced.""" - revision = {"hash": "abc123", "version": "", "size": 12, "modified_time": "2026-07-01 10:00:00"} - _cache_asset(asset_cache, _REMOTE_URL, b"cached bytes", revision) - _serve(monkeypatch, {_REMOTE_URL: None}) - - with caplog.at_level(logging.WARNING, logger=assets_utils.logger.name): - assert assets_utils.read_file(_REMOTE_URL).read() == b"cached bytes" - - assert "did not respond" in caplog.text - assert "may be out of date" in caplog.text - - -def test_server_without_revision_metadata_is_announced(asset_cache, monkeypatch, caplog): - """Test a provider reporting nothing to compare cannot silently serve a stale copy.""" - _cache_asset(asset_cache, _REMOTE_URL, b"cached bytes", {"hash": "", "version": "", "size": 0, "modified_time": ""}) - _serve(monkeypatch, {_REMOTE_URL: {"hash": "", "version": "", "size": 0, "modified_time": ""}}) - - with caplog.at_level(logging.WARNING, logger=assets_utils.logger.name): - assert assets_utils.read_file(_REMOTE_URL).read() == b"cached bytes" - - assert "no revision metadata" in caplog.text - - -def test_two_hosts_serving_the_same_path_do_not_share_a_local_copy(asset_cache, monkeypatch): - """Test a cloud and an on-prem server exposing the same layout get separate cache entries. - - The on-prem server is unreachable, the case where an unrelated copy would otherwise be - accepted without a freshness check. - """ - revision = {"hash": "abc123", "version": "", "size": 12, "modified_time": "2026-07-01 10:00:00"} - on_prem_url = _REMOTE_URL.replace("example.com", "nucleus.example-lab.com") - _cache_asset(asset_cache, _REMOTE_URL, b"cached bytes", revision) - _serve(monkeypatch, {_REMOTE_URL: revision, on_prem_url: None}) - - assert not assets_utils._usable_mirror(on_prem_url) - assert assets_utils.check_file_path(on_prem_url) == 0 - - -def test_using_local_copies_is_announced_once_per_cache_directory(asset_cache, monkeypatch, caplog): - """Test the announcement is visible at the default log level without one line per asset.""" - revision = {"hash": "abc123", "version": "", "size": 12, "modified_time": "2026-07-01 10:00:00"} - other_url = _REMOTE_URL.replace("example.usd", "other.usd") - _cache_asset(asset_cache, _REMOTE_URL, b"cached bytes", revision) - _cache_asset(asset_cache, other_url, b"cached bytes", revision) - _serve(monkeypatch, {_REMOTE_URL: revision, other_url: revision}) - - with caplog.at_level(logging.INFO, logger=assets_utils.logger.name): - assets_utils.read_file(_REMOTE_URL) - assets_utils.read_file(other_url) +def test_overlapping_leases_refresh_and_preserve_prior_revision(asset_cache, http_assets): + """Readers share a validated blob and can finish using it after the provider changes.""" + served, root = http_assets + asset = served / "weights.bin" + url = f"{root}/{asset.name}" + asset.write_bytes(b"old") + with assets_utils.lease_file_path(url) as first: + with assets_utils.lease_file_path(url) as second: + assert Path(second).read_bytes() == b"old" + assert assets_utils.unmirror_file_path(first) == url + assert assets_utils.unmirror_file_path(second) == "" + asset.write_bytes(b"new") + assert assets_utils.read_file(url).read() == b"new" + with assets_utils.lease_file_path(url, force_download=True) as updated: + assert Path(updated).read_bytes() == b"new" + assert Path(first).read_bytes() == b"old" + assert not Path(first).exists() + + +def test_cache_pressure_evicts_a_download_after_its_lease_closes(asset_cache, http_assets, monkeypatch): + """An active file survives eviction pressure. A released file can be evicted and fetched again.""" + served, root = http_assets + monkeypatch.setattr(assets_utils._asset_cache, "_MAX_CACHE_BYTES", 16 * 1024) + requests = [] + get = _QuietHandler.do_GET + + def record_get(handler): + requests.append(handler.path) + get(handler) + + monkeypatch.setattr(_QuietHandler, "do_GET", record_get) + + def lease(index): + (served / f"{index}.bin").write_bytes(bytes([index]) * 4096) + return assets_utils.lease_file_path(f"{root}/{index}.bin") + + with lease(0) as path: + for index in range(1, 8): + with lease(index): + pass + with lease(0) as other: + assert Path(path).read_bytes() == Path(other).read_bytes() == bytes(4096) + assert requests.count("/0.bin") == 1 + for index in range(8, 16): + with lease(index): + pass + with lease(0) as path: + assert Path(path).read_bytes() == bytes(4096) + assert requests.count("/0.bin") == 2 + + +def test_explicit_download_preserves_a_complete_usd_revision(asset_cache, http_assets): + """Concurrent downloads publish one persistent revision, with usable dependencies after a refresh.""" + from pxr import Usd - banners = [record for record in caplog.records if record.levelno == logging.WARNING] - per_asset = [record for record in caplog.records if record.levelno == logging.INFO] - assert len(banners) == 1 - assert str(asset_cache) in banners[0].getMessage() - assert len(per_asset) == 2 - assert {_REMOTE_URL, other_url} == {record.args[0] for record in per_asset} + served, root = http_assets + (served / "scene.usda").write_text("#usda 1.0\n(subLayers = [@body.usda@])\n") + body = served / "body.usda" + body.write_text('#usda 1.0\ndef Cube "Body" {}\n') + destination = asset_cache / "export" + url = f"{root}/scene.usda" + def download(): + return assets_utils.retrieve_file_path(url, str(destination)) -@pytest.mark.parametrize( - "url", - [ - "https://example.com/Assets/Isaac/6.0/Isaac/Props/Blocks/DexCube/Materials/dex_cube_mod.png", - "http://example.com/Assets/example.usd", - "omniverse://nucleus.example-lab.com:3009/Assets/example.usd", - ], -) -def test_unmirror_file_path_recovers_the_url_a_copy_was_cached_from(asset_cache, url): - """Test a cached copy names the asset it came from, so exports do not carry local paths.""" - assert assets_utils.unmirror_file_path(assets_utils._mirror_path(url, str(asset_cache))) == url + with ThreadPoolExecutor(max_workers=2) as executor: + jobs = [executor.submit(download) for _ in range(2)] + first, second = (job.result() for job in jobs) + assert first == second + assert Path(first).is_relative_to(destination) + body.write_text('#usda 1.0\ndef Sphere "Body" {}\n') + updated = download() + for path, expected in [(first, "Cube"), (updated, "Sphere")]: + stage = Usd.Stage.Open(path) + assert stage.GetPrimAtPath("/Body").GetTypeName() == expected + weights = served / "weights.bin" + weights.write_bytes(b"checkpoint") + saved = Path(assets_utils.retrieve_file_path(f"{root}/{weights.name}", str(destination))) + assert saved.is_relative_to(destination) + assert saved.read_bytes() == b"checkpoint" + weights.unlink() + with assets_utils.lease_file_path(str(saved)) as local: + assert local == str(saved) + assert not assets_utils.get_asset_source(local, leased_only=True) @pytest.mark.parametrize( @@ -611,32 +532,6 @@ def test_unmirror_file_path_leaves_paths_outside_the_cache_unclaimed(asset_cache assert assets_utils.unmirror_file_path(path) == "" -def test_unmirror_file_path_does_not_claim_a_windows_drive_letter_path(asset_cache): - """Test a drive letter, which ``urlparse`` also reports as a scheme, is not read as a URL.""" - mirrored = assets_utils._mirror_path("C:/Users/user/assets/robot.usd", str(asset_cache)) - - assert assets_utils.unmirror_file_path(mirrored) == "" - - -def test_unmirror_file_path_recognises_a_copy_reported_with_forward_slashes(asset_cache): - """Test a copy is recognised when USD reports it with forward slashes, as it does on Windows.""" - url = "https://example.com/Assets/Isaac/example.usd" - mirrored = assets_utils._mirror_path(url, str(asset_cache)) - - assert assets_utils.unmirror_file_path(mirrored.replace(os.sep, "/")) == url - - -def test_unmirror_file_path_recognises_a_copy_cached_by_an_earlier_run(asset_cache, monkeypatch): - """Test a warm cache still names its source, since no download happens to record it.""" - revision = {"hash": "abc123", "version": "", "size": 12, "modified_time": "2026-07-01 10:00:00"} - mirrored = _cache_asset(asset_cache, _REMOTE_URL, b"cached bytes", revision) - # no payload is served, so the URL is recovered without the asset being downloaded again - _serve(monkeypatch, {_REMOTE_URL: revision}) - assets_utils.read_file(_REMOTE_URL) - - assert assets_utils.unmirror_file_path(str(mirrored)) == _REMOTE_URL - - def test_newton_asset_dir_uses_environment_override(tmp_path, monkeypatch): """Test that the Newton asset directory is defined from the environment.""" repo_dir = tmp_path / "newton-assets" diff --git a/source/isaaclab_contrib/changelog.d/ovstorage-asset-reads.changed.rst b/source/isaaclab_contrib/changelog.d/ovstorage-asset-reads.changed.rst new file mode 100644 index 000000000000..a3b3c97060c2 --- /dev/null +++ b/source/isaaclab_contrib/changelog.d/ovstorage-asset-reads.changed.rst @@ -0,0 +1,2 @@ +* Loaded GelSight calibration and background assets through the shared asset cache and released + their local files after initialization. diff --git a/source/isaaclab_contrib/isaaclab_contrib/sensors/tacsl_sensor/visuotactile_render.py b/source/isaaclab_contrib/isaaclab_contrib/sensors/tacsl_sensor/visuotactile_render.py index d86bb1c114b4..c91e68cdbe49 100644 --- a/source/isaaclab_contrib/isaaclab_contrib/sensors/tacsl_sensor/visuotactile_render.py +++ b/source/isaaclab_contrib/isaaclab_contrib/sensors/tacsl_sensor/visuotactile_render.py @@ -14,7 +14,7 @@ import scipy import torch -from isaaclab.utils.assets import retrieve_file_path +from isaaclab.utils.assets import lease_file_path logger = logging.getLogger(__name__) @@ -120,24 +120,13 @@ def __init__(self, cfg: GelSightRenderCfg, device: str | torch.device): if self.cfg.mm_per_pixel < eps: raise ValueError(f"Input 'mm_per_pixel' must be positive (>= {eps}), got {self.cfg.mm_per_pixel}") - # Retrieve render data files using the configured base path - bg_path = self._get_render_data(self.cfg.sensor_data_dir_name, self.cfg.background_path) - calib_path = self._get_render_data(self.cfg.sensor_data_dir_name, self.cfg.calib_path) - - if bg_path is None or calib_path is None: - raise FileNotFoundError( - "Failed to retrieve GelSight render data files. " - f"Base path: {self.cfg.base_data_path or 'default (Isaac Lab Nucleus)'}, " - f"Data dir: {self.cfg.sensor_data_dir_name}" - ) - - self.background = cv2.cvtColor(cv2.imread(bg_path), cv2.COLOR_BGR2RGB) - - # Load calibration data directly - calib_data = np.load(calib_path) - calib_grad_r = calib_data["grad_r"] - calib_grad_g = calib_data["grad_g"] - calib_grad_b = calib_data["grad_b"] + data_dir = os.path.join(cfg.base_data_path, cfg.sensor_data_dir_name) + with lease_file_path(os.path.join(data_dir, cfg.background_path)) as path: + self.background = cv2.cvtColor(cv2.imread(path), cv2.COLOR_BGR2RGB) + with lease_file_path(os.path.join(data_dir, cfg.calib_path)) as path, np.load(path) as calibration: + calib_grad_r = calibration["grad_r"] + calib_grad_g = calibration["grad_g"] + calib_grad_b = calibration["grad_b"] image_height = self.cfg.image_height image_width = self.cfg.image_width @@ -215,28 +204,6 @@ def render(self, height_map: torch.Tensor) -> torch.Tensor: Internal Helpers. """ - def _get_render_data(self, data_dir: str, file_name: str) -> str: - """Gets the path for the GelSight render data file. - - Args: - data_dir: The data directory name containing the render data. - file_name: The specific file name to retrieve. - - Returns: - The local path to the file. - - Raises: - FileNotFoundError: If the file is not found locally or on Nucleus. - """ - # Construct path using the configured base path - file_path = os.path.join(self.cfg.base_data_path, data_dir, file_name) - - # Cache directory for downloads - cache_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), data_dir) - - # Use retrieve_file_path to handle local/Nucleus paths and caching - return retrieve_file_path(file_path, download_dir=cache_dir, force_download=False) - def _generate_normals(self, img: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: """Generate the gradient magnitude and direction of the height map. diff --git a/source/isaaclab_rl/changelog.d/ovstorage-asset-reads.changed.rst b/source/isaaclab_rl/changelog.d/ovstorage-asset-reads.changed.rst new file mode 100644 index 000000000000..c3538be051e9 --- /dev/null +++ b/source/isaaclab_rl/changelog.d/ovstorage-asset-reads.changed.rst @@ -0,0 +1,3 @@ +* Loaded published checkpoints through OVStorage while retaining support for pre-fetched files + in the workflow checkpoint directory. Playback and export use the experiment log directory for + outputs produced from leased checkpoints. diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/export_rl_games.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/export_rl_games.py index 0c4b1f60ab94..e125ec9ce7ee 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/export_rl_games.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/export_rl_games.py @@ -31,7 +31,7 @@ import isaaclab_tasks # noqa: F401 from ...rl_games import RlGamesVecEnvWrapper, register_rl_games_env -from ..common import resolve_published_checkpoint +from ..common import checkpoint_log_dir, resolve_published_checkpoint from . import cli_args_rl_games as cli_args from .export_common import ( add_common_export_args, @@ -118,7 +118,7 @@ def export_rl_games_agent(args_cli: argparse.Namespace, env_cfg: Any, agent_cfg: if not resume_path: logger.info(f"No checkpoint found for task: {args_cli.task} in directory: {log_root_path}") return False - log_dir = os.path.dirname(os.path.dirname(resume_path)) + log_dir = checkpoint_log_dir(resume_path, log_root_path, nested=True) env_cfg.log_dir = log_dir env = gym.make(args_cli.task, cfg=env_cfg, render_mode=None) diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/export_rsl_rl.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/export_rsl_rl.py index d7c00421c7cc..972f04c29a25 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/export_rsl_rl.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/export_rsl_rl.py @@ -28,7 +28,7 @@ import isaaclab_tasks # noqa: F401 from ...rsl_rl import RslRlBaseRunnerCfg, RslRlDistillationRunnerCfg, RslRlSacRunnerCfg, RslRlSuperMimicRunnerCfg -from ..common import resolve_published_checkpoint, resolve_seed +from ..common import checkpoint_log_dir, resolve_published_checkpoint, resolve_seed from .export_common import ( add_common_export_args, finalize_export_args, @@ -147,7 +147,7 @@ def export_rsl_rl_agent(args_cli: argparse.Namespace, env_cfg: Any, agent_cfg: R if not resume_path: logger.info(f"No checkpoint found for task: {args_cli.task} in directory: {log_root_path}") return False - log_dir = os.path.dirname(resume_path) + log_dir = checkpoint_log_dir(resume_path, log_root_path) env_cfg.log_dir = log_dir configure_rsl_rl_env_cfg(env_cfg, agent_cfg, inference=True) diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/export_sb3.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/export_sb3.py index 654ee63a6be1..5a650d6176fd 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/export_sb3.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/export_sb3.py @@ -31,6 +31,7 @@ from ..common import ( CHECKPOINT_SELECTORS, + checkpoint_log_dir, normalize_task_name, resolve_checkpoint_selector, resolve_published_checkpoint, @@ -188,7 +189,7 @@ def export_sb3_agent(args_cli: argparse.Namespace, env_cfg: Any, agent_cfg: dict env_cfg.scene.num_envs = 1 env_cfg.seed = agent_cfg["seed"] - log_dir = os.path.dirname(checkpoint_path) + log_dir = checkpoint_log_dir(checkpoint_path, os.path.join("logs", "sb3", normalize_task_name(args_cli.task))) env_cfg.log_dir = log_dir # SB3 constructs torch.distributions.Normal even for deterministic PPO inference. Its eager argument diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/export_skrl.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/export_skrl.py index 5c7bf58ee477..bd6e8c67a2eb 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/export_skrl.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/export_skrl.py @@ -29,7 +29,7 @@ import isaaclab_tasks # noqa: F401 from ...skrl import SkrlVecEnvWrapper, check_skrl_version, import_skrl_runner, resolve_skrl_algorithm -from ..common import resolve_published_checkpoint +from ..common import checkpoint_log_dir, resolve_published_checkpoint from .export_common import ( add_common_export_args, finalize_export_args, @@ -110,7 +110,7 @@ def export_skrl_agent(args_cli: argparse.Namespace, env_cfg: Any, agent_cfg: dic if not resume_path: logger.info(f"No checkpoint found for task: {args_cli.task} in directory: {log_root_path}") return False - log_dir = os.path.dirname(os.path.dirname(resume_path)) + log_dir = checkpoint_log_dir(resume_path, log_root_path, nested=True) env_cfg.log_dir = log_dir env = gym.make(args_cli.task, cfg=env_cfg, render_mode=None) diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_model_based.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_model_based.py index 1ef34505cb36..c95312f4532a 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_model_based.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_model_based.py @@ -25,6 +25,7 @@ add_common_play_args, apply_env_overrides, apply_video_recording, + checkpoint_log_dir, create_isaaclab_env, enable_cameras_for_video, pre_launch_video_config, @@ -54,7 +55,7 @@ def run(argv: list[str]) -> None: parser.error("Playback restores the saved configuration; use explicit relocation/device/seed options.") cfg, agent, checkpoint, checkpoint_path = load_legacy_task(args) apply_env_overrides(args, cfg) - output = str(Path(checkpoint_path).parent) + output = checkpoint_log_dir(checkpoint_path, "logs/model_based/Isaac-Motion-Tracking-G1") enable_cameras_for_video(args) pre_launch_video_config(cfg, args) with launch_simulation(cfg, args): diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rl_games.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rl_games.py index 5b5758217228..b144a3c9f137 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rl_games.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rl_games.py @@ -31,6 +31,7 @@ add_common_play_args, apply_env_overrides, apply_video_recording, + checkpoint_log_dir, close_env, create_isaaclab_env, enable_cameras_for_video, @@ -122,7 +123,7 @@ def run(argv: list[str]) -> None: resume_path = _resolve_checkpoint(args_cli, agent_cfg, env_cfg, log_root_path) if resume_path is None: return - log_dir = os.path.dirname(os.path.dirname(resume_path)) + log_dir = checkpoint_log_dir(resume_path, log_root_path, nested=True) env_cfg.log_dir = log_dir apply_video_recording(env_cfg, log_dir, args_cli, subdir="play") diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py index c59a592e596f..ef852437a0f5 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py @@ -32,6 +32,7 @@ add_common_play_args, apply_env_overrides, apply_video_recording, + checkpoint_log_dir, close_env, create_isaaclab_env, enable_cameras_for_video, @@ -171,7 +172,7 @@ def run(argv: list[str]) -> None: resume_path = _resolve_checkpoint(args_cli, agent_cfg, env_cfg, log_root_path) if resume_path is None: return - log_dir = os.path.dirname(resume_path) + log_dir = checkpoint_log_dir(resume_path, log_root_path) env_cfg.log_dir = log_dir apply_video_recording(env_cfg, log_dir, args_cli, subdir="play", checkpoint_path=resume_path) diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_sb3.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_sb3.py index 150abc2fa724..5d0db51fce67 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_sb3.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_sb3.py @@ -29,6 +29,7 @@ add_common_play_args, apply_env_overrides, apply_video_recording, + checkpoint_log_dir, close_env, create_isaaclab_env, enable_cameras_for_video, @@ -113,7 +114,7 @@ def run(argv: list[str]) -> None: checkpoint_path = _resolve_checkpoint(args_cli, env_cfg, log_root_path) if checkpoint_path is None: return - log_dir = os.path.dirname(checkpoint_path) + log_dir = checkpoint_log_dir(checkpoint_path, log_root_path) env_cfg.log_dir = log_dir apply_video_recording(env_cfg, log_dir, args_cli, subdir="play") diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_skrl.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_skrl.py index 1effae5c46d5..a3a741efd138 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_skrl.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_skrl.py @@ -37,6 +37,7 @@ add_common_play_args, apply_env_overrides, apply_video_recording, + checkpoint_log_dir, close_env, create_isaaclab_env, enable_cameras_for_video, @@ -142,7 +143,7 @@ def _run(args_cli: argparse.Namespace) -> None: resume_path = _resolve_checkpoint(args_cli, env_cfg, log_root_path, algorithm, manifest_metadata) if resume_path is None: return - log_dir = os.path.dirname(os.path.dirname(resume_path)) + log_dir = checkpoint_log_dir(resume_path, log_root_path, nested=True) env_cfg.log_dir = log_dir apply_video_recording(env_cfg, log_dir, args_cli, subdir="play") diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_torchrl.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_torchrl.py index 6d12de0917a7..2bfacb0c079d 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_torchrl.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_torchrl.py @@ -27,6 +27,7 @@ add_common_play_args, apply_env_overrides, apply_video_recording, + checkpoint_log_dir, close_env, create_isaaclab_env, enable_cameras_for_video, @@ -111,7 +112,7 @@ def run(argv: list[str]) -> None: log_root_path = os.path.abspath(os.path.join("logs", "torchrl", agent_cfg.experiment_name)) logger.info(f"Loading experiment from directory: {log_root_path}") checkpoint_path = _resolve_checkpoint(args_cli, log_root_path) - log_dir = os.path.dirname(checkpoint_path) + log_dir = checkpoint_log_dir(checkpoint_path, log_root_path) env_cfg.log_dir = log_dir apply_video_recording(env_cfg, log_dir, args_cli, subdir="play", checkpoint_path=checkpoint_path) diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/common.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/common.py index 95168d664610..d2afaeb09b56 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/common.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/common.py @@ -32,7 +32,7 @@ from isaaclab.envs import DirectMARLEnvCfg, DirectRLEnvCfg, ManagerBasedRLEnvCfg from isaaclab.envs.utils.video_recorder_cfg import VideoRecorderCfg, parse_video_source from isaaclab.renderers.renderer_cfg import RendererCfg -from isaaclab.utils.assets import retrieve_file_path +from isaaclab.utils.assets import get_asset_source, retrieve_file_path from isaaclab.utils.dict import print_dict from isaaclab.utils.images import make_camera_output_grid, normalize_camera_output_for_display from isaaclab.utils.io import dump_yaml @@ -573,6 +573,18 @@ def close_env(env: gym.Env) -> None: """ +def checkpoint_log_dir(checkpoint_path: str, log_root: str, *, nested: bool = False) -> str: + """Choose a durable output directory for a checkpoint loaded by playback or export. + + Local runs place outputs beside the checkpoint or above its backend-specific subdirectory. + A downloaded checkpoint has a leased path, so its outputs belong under the experiment log root. + """ + if get_asset_source(checkpoint_path, leased_only=True): + return os.path.abspath(log_root) + parent = os.path.dirname(checkpoint_path) + return os.path.dirname(parent) if nested else parent + + def resolve_published_checkpoint(library: str, task: str, env_cfg: Any) -> str | None: """Fetch the published pre-trained checkpoint of a task for the configured backends. diff --git a/source/isaaclab_rl/isaaclab_rl/utils/pretrained_checkpoint.py b/source/isaaclab_rl/isaaclab_rl/utils/pretrained_checkpoint.py index 3c08d57a811d..9a4ac36673f4 100644 --- a/source/isaaclab_rl/isaaclab_rl/utils/pretrained_checkpoint.py +++ b/source/isaaclab_rl/isaaclab_rl/utils/pretrained_checkpoint.py @@ -303,8 +303,8 @@ def get_published_pretrained_checkpoint( ) -> str | None: """Gets the path for the pre-trained checkpoint. - If the checkpoint is not cached locally then the file is downloaded. - The cached path is then returned. + Use a pre-fetched local checkpoint when present. Otherwise return a process-lifetime + path to the checkpoint in the shared asset cache. Args: workflow: The workflow. @@ -339,15 +339,15 @@ def get_published_pretrained_checkpoint( ov_path = get_published_pretrained_checkpoint_path( workflow, task_name, physics_backend, render_backend, preset_names=preset_names ) - download_dir = os.path.join(".pretrained_checkpoints", workflow) + prefetch_dir = os.path.join(".pretrained_checkpoints", workflow) if physics_backend is None: - download_dir = os.path.join(download_dir, task_name) - resume_path = os.path.join(download_dir, filename) + prefetch_dir = os.path.join(prefetch_dir, task_name) + resume_path = os.path.join(prefetch_dir, filename) if not os.path.exists(resume_path): print(f"Fetching pre-trained checkpoint : {ov_path}") try: - resume_path = retrieve_file_path(ov_path, download_dir) + resume_path = retrieve_file_path(ov_path) except FileNotFoundError: # the asset server reports a checkpoint that was never published and a server it # cannot reach the same way, so both are covered by the same message @@ -374,8 +374,7 @@ def get_published_pretrained_checkpoint( " a directory left behind by a container run is owned by root." ) raise RuntimeError( - f"Failed to download the pre-trained checkpoint '{ov_path}' into" - f" '{os.path.abspath(download_dir)}': {type(exc).__name__}: {exc}.{hint}" + f"Failed to download the pre-trained checkpoint '{ov_path}': {type(exc).__name__}: {exc}.{hint}" ) from exc else: print("Using pre-fetched pre-trained checkpoint") diff --git a/source/isaaclab_rl/test/test_pretrained_checkpoint.py b/source/isaaclab_rl/test/test_pretrained_checkpoint.py index 5b616456bf49..239c0a9d8c3a 100644 --- a/source/isaaclab_rl/test/test_pretrained_checkpoint.py +++ b/source/isaaclab_rl/test/test_pretrained_checkpoint.py @@ -193,26 +193,25 @@ def test_get_pretrained_checkpoint_publish_path_uses_flat_workflow_directory(mon assert path == "omniverse://IsaacLab/PretrainedCheckpoints/rsl_rl/Isaac-Cartpole_physx_none_rsl_rl.pt" -def test_get_published_pretrained_checkpoint_downloads_to_flat_cache( +def test_get_published_pretrained_checkpoint_uses_shared_asset_cache( monkeypatch: pytest.MonkeyPatch, tmp_path: Path, ): - """Test that backend-aware downloads use the workflow cache directory.""" + """The published remote address identifies the backend and the returned asset path is usable.""" monkeypatch.chdir(tmp_path) monkeypatch.setattr(pretrained_checkpoint, "ISAACLAB_NUCLEUS_DIR", "omniverse://IsaacLab") monkeypatch.setattr("sys.argv", ["play.py", "presets=depth"]) - retrieved = {} + from isaaclab.utils import assets - def _retrieve_file_path(remote_path: str, download_dir: str) -> str: - retrieved["remote_path"] = remote_path - retrieved["download_dir"] = download_dir - destination = Path(download_dir) / Path(remote_path).name - destination.parent.mkdir(parents=True) - destination.touch() - return str(destination) + monkeypatch.setenv("XDG_CACHE_HOME", str(tmp_path / "cache")) + filename = "Isaac-Cartpole-Camera-Direct_depth_newtonmjwarp_newton_rl_games.pth" + url = f"omniverse://IsaacLab/PretrainedCheckpoints/rl_games/{filename}" - monkeypatch.setattr(pretrained_checkpoint, "retrieve_file_path", _retrieve_file_path) + def read(address, **kwargs): + assert address == url + return b"checkpoint" + monkeypatch.setattr(assets, "_remote_read", read) path = pretrained_checkpoint.get_published_pretrained_checkpoint( "rl_games", "Isaac-Cartpole-Camera-Direct", @@ -220,13 +219,14 @@ def _retrieve_file_path(remote_path: str, download_dir: str) -> str: "newton", ) - expected_download_dir = str(Path(".pretrained_checkpoints") / "rl_games") - filename = "Isaac-Cartpole-Camera-Direct_depth_newtonmjwarp_newton_rl_games.pth" - assert path == str(Path(expected_download_dir) / filename) - assert retrieved == { - "remote_path": f"omniverse://IsaacLab/PretrainedCheckpoints/rl_games/{filename}", - "download_dir": expected_download_dir, - } + assert Path(path).read_bytes() == b"checkpoint" + assert not Path(".pretrained_checkpoints").exists() + + from isaaclab_rl.entrypoints.common import checkpoint_log_dir + + output_dir = str(tmp_path / "logs") + assert checkpoint_log_dir(path, output_dir) == output_dir + assert checkpoint_log_dir(path, output_dir, nested=True) == output_dir def test_get_published_pretrained_checkpoint_reports_unpublished_checkpoint( @@ -238,7 +238,7 @@ def test_get_published_pretrained_checkpoint_reports_unpublished_checkpoint( monkeypatch.chdir(tmp_path) monkeypatch.setattr(pretrained_checkpoint, "ISAACLAB_NUCLEUS_DIR", "omniverse://IsaacLab") - def _retrieve_file_path(remote_path: str, download_dir: str) -> str: + def _retrieve_file_path(remote_path: str) -> str: raise FileNotFoundError(f"Unable to find the file: {remote_path}") monkeypatch.setattr(pretrained_checkpoint, "retrieve_file_path", _retrieve_file_path) @@ -264,9 +264,9 @@ def test_get_published_pretrained_checkpoint_raises_on_unwritable_cache( """Test that a local download failure is reported instead of being reported as unavailable.""" monkeypatch.chdir(tmp_path) monkeypatch.setattr(pretrained_checkpoint, "ISAACLAB_NUCLEUS_DIR", "omniverse://IsaacLab") - cause = PermissionError(13, "Permission denied", str(tmp_path / ".pretrained_checkpoints")) + cause = PermissionError(13, "Permission denied", str(tmp_path / "cache")) - def _retrieve_file_path(remote_path: str, download_dir: str) -> str: + def _retrieve_file_path(remote_path: str) -> str: raise cause monkeypatch.setattr(pretrained_checkpoint, "retrieve_file_path", _retrieve_file_path) @@ -276,6 +276,5 @@ def _retrieve_file_path(remote_path: str, download_dir: str) -> str: message = str(error.value) assert "Isaac-Cartpole_physx_none_rsl_rl.pt" in message - assert str(tmp_path / ".pretrained_checkpoints" / "rsl_rl") in message assert "Permission denied" in message assert error.value.__cause__ is cause diff --git a/source/isaaclab_tasks/changelog.d/ovstorage-asset-reads.changed.rst b/source/isaaclab_tasks/changelog.d/ovstorage-asset-reads.changed.rst new file mode 100644 index 000000000000..a7cedd58d3ca --- /dev/null +++ b/source/isaaclab_tasks/changelog.d/ovstorage-asset-reads.changed.rst @@ -0,0 +1,2 @@ +* Loaded AutoMate task assets and the Drone ARL encoder through the shared asset cache, releasing + their local files after initialization. diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/automate/assembly_env.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/automate/assembly_env.py index f06e7a3108cd..c44a4153ecb5 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/automate/assembly_env.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/automate/assembly_env.py @@ -11,7 +11,7 @@ from isaaclab.envs import DirectRLEnv from isaaclab.utils import index_fill_ -from isaaclab.utils.assets import retrieve_file_path +from isaaclab.utils.assets import read_file from isaaclab.utils.math import ( axis_angle_from_quat, combine_frame_transforms, @@ -192,14 +192,10 @@ def _init_tensors(self): def _load_assembly_info(self): """Load grasp pose and disassembly distance for plugs in each environment.""" - plug_grasp_path = retrieve_file_path(self.cfg_task.plug_grasp_json) - with open(plug_grasp_path) as f: - plug_grasp_dict = json.load(f) + plug_grasp_dict = json.load(read_file(self.cfg_task.plug_grasp_json)) plug_grasps = [plug_grasp_dict[f"asset_{self.cfg_task.assembly_id}"] for i in range(self.num_envs)] - disassembly_dist_path = retrieve_file_path(self.cfg_task.disassembly_dist_json) - with open(disassembly_dist_path) as f: - disassembly_dist_dict = json.load(f) + disassembly_dist_dict = json.load(read_file(self.cfg_task.disassembly_dist_json)) disassembly_dists = [disassembly_dist_dict[f"asset_{self.cfg_task.assembly_id}"] for i in range(self.num_envs)] return torch.as_tensor(plug_grasps).to(self.device), torch.as_tensor(disassembly_dists).to(self.device) @@ -220,9 +216,7 @@ def _get_curriculum_info(self, disassembly_dists): def _load_disassembly_data(self): """Load pre-collected disassembly trajectories (end-effector position only).""" - local_path = retrieve_file_path(self.cfg_task.disassembly_path_json, download_dir="./") - with open(local_path) as f: - disassembly_traj = json.load(f) + disassembly_traj = json.load(read_file(self.cfg_task.disassembly_path_json)) eef_pos_traj = [] diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/automate/automate_algo_utils.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/automate/automate_algo_utils.py index 7c053044f28b..4861ab2e688f 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/automate/automate_algo_utils.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/automate/automate_algo_utils.py @@ -16,7 +16,7 @@ base_dir = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".")) sys.path.append(base_dir) -from isaaclab.utils.assets import retrieve_file_path +from isaaclab.utils.assets import lease_file_path """ Util Functions @@ -24,8 +24,8 @@ def get_gripper_open_width(obj_filepath): - local_path = retrieve_file_path(obj_filepath, download_dir="./") - obj_mesh = trimesh.load_mesh(local_path) + with lease_file_path(obj_filepath) as local_path: + obj_mesh = trimesh.load_mesh(local_path) aabb = obj_mesh.bounds return min(0.04, (aabb[1][1] - aabb[0][1]) / 1.25) diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/automate/disassembly_env.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/automate/disassembly_env.py index d9bfd1cf29e7..38a71eab6be3 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/automate/disassembly_env.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/automate/disassembly_env.py @@ -11,7 +11,7 @@ from isaaclab.envs import DirectRLEnv from isaaclab.utils import index_fill_ -from isaaclab.utils.assets import retrieve_file_path +from isaaclab.utils.assets import read_file from isaaclab.utils.math import ( axis_angle_from_quat, combine_frame_transforms, @@ -152,14 +152,10 @@ def _init_tensors(self): def _load_assembly_info(self): """Load grasp pose and disassembly distance for plugs in each environment.""" - plug_grasp_path = retrieve_file_path(self.cfg_task.plug_grasp_json) - with open(plug_grasp_path) as f: - plug_grasp_dict = json.load(f) + plug_grasp_dict = json.load(read_file(self.cfg_task.plug_grasp_json)) plug_grasps = [plug_grasp_dict[f"asset_{self.cfg_task.assembly_id}"] for i in range(self.num_envs)] - disassembly_dist_path = retrieve_file_path(self.cfg_task.disassembly_dist_json) - with open(disassembly_dist_path) as f: - disassembly_dist_dict = json.load(f) + disassembly_dist_dict = json.load(read_file(self.cfg_task.disassembly_dist_json)) disassembly_dists = [disassembly_dist_dict[f"asset_{self.cfg_task.assembly_id}"] for i in range(self.num_envs)] return torch.as_tensor(plug_grasps).to(self.device), torch.as_tensor(disassembly_dists).to(self.device) diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/automate/industreal_algo_utils.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/automate/industreal_algo_utils.py index 43604bef0926..4df2123b5f15 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/automate/industreal_algo_utils.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/automate/industreal_algo_utils.py @@ -55,7 +55,7 @@ import warp as wp from trimesh.exchange.load import load -from isaaclab.utils.assets import retrieve_file_path +from isaaclab.utils.assets import lease_file_path """ Simulation-Aware Policy Update (SAPU) @@ -64,10 +64,10 @@ def load_asset_mesh_in_warp(held_asset_obj, fixed_asset_obj, num_samples, device): """Create mesh objects in Warp for all environments.""" - held_asset_local = retrieve_file_path(held_asset_obj, download_dir="./") - plug_trimesh = load(held_asset_local) - fixed_asset_local = retrieve_file_path(fixed_asset_obj, download_dir="./") - socket_trimesh = load(fixed_asset_local) + with lease_file_path(held_asset_obj) as held_asset_local: + plug_trimesh = load(held_asset_local) + with lease_file_path(fixed_asset_obj) as fixed_asset_local: + socket_trimesh = load(fixed_asset_local) plug_wp_mesh = wp.Mesh( points=wp.array(plug_trimesh.vertices, dtype=wp.vec3, device=device), diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/drone_arl/mdp/observations.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/drone_arl/mdp/observations.py index ad04a3b2ea78..a54f8e5d91d7 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/drone_arl/mdp/observations.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/drone_arl/mdp/observations.py @@ -32,7 +32,7 @@ from isaaclab_contrib.assets import Multirotor from isaaclab.envs.utils.io_descriptors import generic_io_descriptor, record_shape -from isaaclab.utils.assets import ISAACLAB_NUCLEUS_DIR, retrieve_file_path +from isaaclab.utils.assets import ISAACLAB_NUCLEUS_DIR, lease_file_path """ State. @@ -153,9 +153,8 @@ def _get_model(cls, device): """ if cls._model is None: model_path = os.path.join(ISAACLAB_NUCLEUS_DIR, "Contrib/Drone/vae_model.pt") - download_dir = os.path.join(".pretrained_checkpoints", "drone_arl", "vae_model.pt") - resume_path = retrieve_file_path(model_path, download_dir) - cls._model = torch.jit.load(resume_path, map_location=device) + with lease_file_path(model_path) as local_path: + cls._model = torch.jit.load(local_path, map_location=device) cls._model.eval() return cls._model