Repository navigation
feat(agent-server): reclaim Docker runtime caches and disable core dumps #5263
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
Changes from all commits
c90aec9
98f78b3
6350640
72f6942
15eb760
b80873e
80f7f5e
1d994bb
cc95444
e529a32
e0ec9ef
f10ef3e
a4bb58b
5e1ddaa
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,66 @@ | ||
| from contextlib import AbstractAsyncContextManager, suppress | ||
| from dataclasses import dataclass | ||
| from pathlib import Path | ||
| from typing import TYPE_CHECKING | ||
| from uuid import UUID | ||
|
|
||
| from openhands.agent_server.docker_runtime.provisioning import RuntimeProvisioningStore | ||
| from openhands.agent_server.storage import StoredRuntime | ||
|
|
||
|
|
||
| if TYPE_CHECKING: | ||
| from openhands.agent_server.docker_runtime.registry import ( | ||
| DockerConversationRegistry, | ||
| ) | ||
|
|
||
|
|
||
| @dataclass(frozen=True, slots=True) | ||
| class DockerRuntimeStorage: | ||
| """``runtime-data/<id>/``: the sandbox home and, usually, its workspace.""" | ||
|
|
||
| registry: "DockerConversationRegistry" | ||
|
|
||
| @property | ||
| def provisioning(self) -> RuntimeProvisioningStore: | ||
| return self.registry.provisioning | ||
|
|
||
| @property | ||
| def root(self) -> Path: | ||
| return self.provisioning.data_root | ||
|
|
||
| def runtime(self, conversation_id: UUID) -> StoredRuntime | None: | ||
| runtime_dir = self.provisioning.runtime_dir(conversation_id) | ||
| if runtime_dir.is_symlink() or not runtime_dir.is_dir(): | ||
| return None | ||
| state = self.registry.conversation_dir(conversation_id) / "base_state.json" | ||
| try: | ||
| last_active = state.stat().st_mtime | ||
| except OSError: | ||
| try: | ||
| last_active = runtime_dir.stat().st_mtime | ||
| except OSError: | ||
| # Deleted since the check above; nothing left to reclaim. | ||
| return None | ||
| try: | ||
| home = self.provisioning.direct_child(runtime_dir, "persistence") | ||
| except ValueError: | ||
| home = None | ||
| return StoredRuntime(conversation_id, last_active, home=home) | ||
|
|
||
| def runtimes(self) -> list[StoredRuntime]: | ||
| runtimes = [ | ||
| runtime | ||
| for runtime_dir in self.root.iterdir() | ||
| if (conversation_id := _parse_id(runtime_dir.name)) | ||
| and (runtime := self.runtime(conversation_id)) | ||
| ] | ||
| return sorted(runtimes, key=lambda runtime: runtime.last_active) | ||
|
|
||
| def idle(self, conversation_id: UUID) -> AbstractAsyncContextManager[bool]: | ||
| return self.registry.runtime_idle(conversation_id) | ||
|
|
||
|
|
||
| def _parse_id(name: str) -> UUID | None: | ||
| with suppress(ValueError): | ||
| return UUID(hex=name) | ||
| return None |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| """Reclaim disk the agent-server itself stores per conversation.""" | ||
|
|
||
| from openhands.agent_server.storage.model import StoredRuntime, Tier | ||
| from openhands.agent_server.storage.reclaimer import ReclaimableStorage, Reclaimer | ||
| from openhands.agent_server.storage.trash import Trash | ||
|
|
||
|
|
||
| __all__ = ["Reclaimer", "ReclaimableStorage", "StoredRuntime", "Tier", "Trash"] |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| from dataclasses import dataclass | ||
| from enum import IntEnum | ||
| from pathlib import Path | ||
| from uuid import UUID | ||
|
|
||
|
|
||
| class Tier(IntEnum): | ||
| """What may be dropped from a stopped runtime; each tier includes the lower.""" | ||
|
|
||
| # Package caches in the sandbox home ($HOME/.cache, $HOME/.npm). | ||
| CACHES = 1 | ||
|
|
||
|
|
||
| @dataclass(frozen=True, slots=True) | ||
| class StoredRuntime: | ||
| """A conversation's storage on this host, limited to what the server owns.""" | ||
|
|
||
| id: UUID | ||
| last_active: float | ||
| # The sandbox's own $HOME, if it has one apart from the host's. | ||
| home: Path | None = None |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| import asyncio | ||
| from contextlib import AbstractAsyncContextManager | ||
| from pathlib import Path | ||
| from typing import Protocol | ||
| from uuid import UUID | ||
|
|
||
| from openhands.agent_server.storage.model import StoredRuntime, Tier | ||
| from openhands.agent_server.storage.selectors import caches | ||
| from openhands.agent_server.storage.trash import Trash | ||
| from openhands.sdk.logger import get_logger | ||
|
|
||
|
|
||
| logger = get_logger(__name__) | ||
|
|
||
|
|
||
| class ReclaimableStorage(Protocol): | ||
| """How one ``Config.conversation_runtime`` (local, docker) stores | ||
| conversations on this host.""" | ||
|
|
||
| @property | ||
| def root(self) -> Path: | ||
| """Where the runtimes live; the trash goes here, on the same filesystem.""" | ||
| ... | ||
|
|
||
| def runtime(self, conversation_id: UUID) -> StoredRuntime | None: | ||
| """The conversation's stored runtime, or None if it has none here.""" | ||
| ... | ||
|
|
||
| def runtimes(self) -> list[StoredRuntime]: | ||
| """Every stored runtime, least recently active first.""" | ||
| ... | ||
|
|
||
| def idle(self, conversation_id: UUID) -> AbstractAsyncContextManager[bool]: | ||
| """Hold the runtime still; True if nothing runs or starts in it.""" | ||
| ... | ||
|
|
||
|
|
||
| class Reclaimer: | ||
| """Frees what a runtime mode stores per conversation, by tier. | ||
|
Member
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. @OpenHands what is a runtime mode? Investigate the codebase deeply. I thought it would be only docker or local but local is in the same place so I guess only docker, but you need to correct me if it means something else or there are more modes. 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. I'm on it! enyst can track my progress at all-hands.dev
Member
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. "runtime mode" is the value of
So your guess needs one correction. Local mode is not "in the same place" in the sense this module cares about: a host-local conversation has no per-conversation sandbox That's also why the abstraction is a This reply was authored by an AI agent (OpenHands). 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. I've investigated the codebase and answered the reviewer's question directly on the thread. Answer to the commentI found and confirmed the facts, then posted a reply to enyst on PR #5263 (thread "Runtime mode" is the value of
The key correction to the reviewer's mental model: local mode is not "in the same place." A host-local conversation runs in-process on the host and uses the host's own I also explained why the abstraction is a I left the thread unresolved since it's a pure question and the reviewer may want to follow up or confirm before I mark it resolved.
Member
Author
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. |
||
|
|
||
| Files are only moved into the trash, and only while the storage holds the | ||
| runtime idle; the trash deletes them in the background. | ||
| """ | ||
|
|
||
| def __init__(self, storage: ReclaimableStorage) -> None: | ||
| self.storage = storage | ||
| self.trash = Trash(storage.root) | ||
|
|
||
| async def start(self) -> None: | ||
| """Only safe before any runtime starts: every one is reclaimed.""" | ||
| for runtime in await asyncio.to_thread(self.storage.runtimes): | ||
| await self.reclaim(runtime, Tier.CACHES) | ||
| self.trash.empty_soon() | ||
|
|
||
| async def shutdown(self) -> None: | ||
| await self.trash.close() | ||
|
|
||
| async def on_stop(self, conversation_id: UUID) -> None: | ||
| runtime = await asyncio.to_thread(self.storage.runtime, conversation_id) | ||
| if runtime is not None and await self.reclaim(runtime, Tier.CACHES): | ||
| self.trash.empty_soon() | ||
|
|
||
| async def reclaim(self, runtime: StoredRuntime, tier: Tier) -> bool: | ||
| """Discard what ``tier`` allows, unless the runtime is in use.""" | ||
| paths = await asyncio.to_thread(_select, runtime, tier) | ||
| if not paths: | ||
| return False | ||
| async with self.storage.idle(runtime.id) as idle: | ||
| if not idle: | ||
| return False | ||
| # Only renames here: the lock is held for microseconds. | ||
| moved = [path for path in paths if self.trash.discard(path)] | ||
| return bool(moved) | ||
|
|
||
|
|
||
| def _select(runtime: StoredRuntime, tier: Tier) -> list[Path]: | ||
| paths: list[Path] = [] | ||
| if tier >= Tier.CACHES and runtime.home is not None: | ||
| paths += caches(runtime.home) | ||
| return paths | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| """What each tier may drop: paths a stopped runtime can rebuild.""" | ||
|
|
||
| import os | ||
|
VascoSch92 marked this conversation as resolved.
Resolved
|
||
| from pathlib import Path | ||
| from typing import Final | ||
|
|
||
|
|
||
| # Rebuildable caches under $HOME: XDG tools (uv, pip, yarn, go) use .cache, | ||
| # npm ignores XDG and uses .npm. | ||
| CACHE_DIRS: Final[tuple[str, ...]] = (".cache", ".npm") | ||
|
|
||
|
|
||
| def caches(home: Path) -> list[Path]: | ||
| # lexists: a symlinked cache is still discarded (unlinked, never followed). | ||
| return [home / name for name in CACHE_DIRS if os.path.lexists(home / name)] | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,84 @@ | ||
| import asyncio | ||
| from contextlib import suppress | ||
| from pathlib import Path | ||
| from uuid import uuid4 | ||
|
|
||
| from openhands.agent_server.utils import safe_rmtree | ||
| from openhands.sdk.logger import get_logger | ||
|
|
||
|
|
||
| logger = get_logger(__name__) | ||
|
|
||
|
|
||
| class Trash: | ||
| """The only place stored files are deleted. | ||
|
|
||
| ``discard`` is one rename, so it can run under a lock and races nothing: a | ||
| reader sees the path whole or not at all. Deletion happens in the | ||
| background, and whatever an interrupted run leaves is emptied on the next | ||
| start. ``root`` must be on the same filesystem as everything discarded. | ||
| """ | ||
|
|
||
| def __init__(self, root: Path) -> None: | ||
| self.dir = root / ".trash" | ||
| self._emptying: asyncio.Task[None] | None = None | ||
|
|
||
| def discard(self, path: Path) -> bool: | ||
| try: | ||
| self.dir.mkdir(mode=0o700, exist_ok=True) | ||
| path.rename(self.dir / uuid4().hex) | ||
| except FileNotFoundError: | ||
| return False | ||
| except OSError: | ||
| logger.warning("Failed to discard %s", path, exc_info=True) | ||
| return False | ||
| return True | ||
|
|
||
| def empty_soon(self) -> None: | ||
| if self._emptying is None or self._emptying.done(): | ||
| self._emptying = asyncio.create_task(self._empty()) | ||
|
|
||
| async def drain(self) -> None: | ||
| """Wait until everything discarded so far is deleted.""" | ||
| while self._emptying is not None and not self._emptying.done(): | ||
| await asyncio.shield(self._emptying) | ||
|
|
||
| async def close(self) -> None: | ||
| """Abandon deletion; the next start picks up what is left. | ||
|
|
||
| A deletion already running in a worker thread cannot be interrupted: | ||
| it finishes after this returns. Only the entries not yet started wait. | ||
| """ | ||
| if self._emptying is not None: | ||
| self._emptying.cancel() | ||
| await asyncio.gather(self._emptying, return_exceptions=True) | ||
| self._emptying = None | ||
|
|
||
| async def _empty(self) -> None: | ||
| # Re-list for entries discarded meanwhile, but try each once per run: | ||
| # one that cannot be deleted must not spin; the next start retries it. | ||
| tried: set[Path] = set() | ||
| while entries := [ | ||
| entry | ||
| for entry in await asyncio.to_thread(self._entries) | ||
| if entry not in tried | ||
| ]: | ||
| for entry in entries: | ||
| tried.add(entry) | ||
| try: | ||
| await asyncio.to_thread(_remove, entry) | ||
| except Exception: | ||
| logger.warning("Failed to delete %s", entry, exc_info=True) | ||
|
|
||
| def _entries(self) -> list[Path]: | ||
| with suppress(FileNotFoundError): | ||
| return list(self.dir.iterdir()) | ||
| return [] | ||
|
|
||
|
|
||
| def _remove(path: Path) -> None: | ||
| if path.is_symlink(): | ||
| path.unlink(missing_ok=True) | ||
| # safe_rmtree reports failure instead of raising. | ||
| elif not safe_rmtree(path, "discarded conversation storage"): | ||
| raise OSError(f"Could not delete {path}") |
Uh oh!
There was an error while loading. Please reload this page.