Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions source/isaaclab/changelog.d/ovstorage-asset-reads.added.rst
Original file line number Diff line number Diff line change
@@ -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.
5 changes: 5 additions & 0 deletions source/isaaclab/changelog.d/ovstorage-asset-reads.changed.rst
Original file line number Diff line number Diff line change
@@ -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.
Empty file.
36 changes: 11 additions & 25 deletions source/isaaclab/isaaclab/sim/spawners/from_files/from_files.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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

Expand Down
29 changes: 15 additions & 14 deletions source/isaaclab/isaaclab/sim/usd_export/base_usd_exporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,18 @@
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

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
Expand Down Expand Up @@ -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."""
Expand Down Expand Up @@ -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:
Expand Down
27 changes: 16 additions & 11 deletions source/isaaclab/isaaclab/sim/utils/prims.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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


Expand Down
216 changes: 216 additions & 0 deletions source/isaaclab/isaaclab/utils/_asset_cache.py
Original file line number Diff line number Diff line change
@@ -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):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Warning · Style Consistency — Group public definitions first

Private classes and functions precede public functions in the new module, contrary to the contribution guide's module order. Group constants, public functions, private functions, then private classes.

"""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):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Warning · Style Consistency — Annotate new helper returns

_PublishedContent.stat and read, _recover_views, and AssetLease.init omit return annotations required by the typing guide. Add concrete results and -> None where appropriate.

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:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Warning · Style Consistency — Move private cleanup below public methods

_remove_view interrupts AssetLease's public lifecycle methods, contrary to the prescribed class order. Place it after close.

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()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Warning · Scope Complexity — Remove synthetic rewritten-byte caching

Rewritten layer bytes already have a lease-owned tree. The synthetic origin adds another stack, hash, lock, and materialization before writing that tree. Write the bytes directly and remove that origin.

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)
Comment on lines +205 to +206

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Writes can change shared assets

publish exposes the shared cache file through a hard link without enforcing the promised read-only access. If a consumer writes in place through the returned path, it changes the cached bytes and every other hard-linked lease. One consumer's mistake can then give other readers bad data. Enforce read-only access before exposing the path, or use a separate copy when writes cannot be blocked.

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()
Loading
Loading