Repository navigation
Manage localized asset lifetimes with OVStorage leases #9358
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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. |
| 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. |
| 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): | ||
| """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): | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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: | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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() | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| 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() | ||
There was a problem hiding this comment.
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.