Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,26 @@
import os
import subprocess
import time
from contextlib import suppress
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager, suppress
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, Final
from urllib.error import URLError
from urllib.request import urlopen
from uuid import UUID, uuid4

from openhands.agent_server.config import V1_SESSION_API_KEY_ENV, Config
from openhands.agent_server.conversation_registry import ConversationRegistry
from openhands.agent_server.docker_runtime.provisioning import RuntimeProvisioningStore
from openhands.agent_server.docker_runtime.storage import DockerRuntimeStorage
from openhands.agent_server.launch import container_browser_enabled
from openhands.agent_server.models import (
ConversationRuntimeInfo,
ConversationRuntimeStatus,
)
from openhands.agent_server.persistence.store import _get_persistence_dir
from openhands.agent_server.storage import Reclaimer
from openhands.sdk.conversation.state import ConversationExecutionStatus
from openhands.sdk.logger import get_logger
from openhands.sdk.utils.cipher import Cipher
Expand All @@ -38,10 +41,10 @@

logger = get_logger(__name__)

_CONVERSATIONS_DIR = "/var/openhands/conversations"
_PERSISTENCE_DIR = "/var/openhands/.openhands"
_WORKSPACE_DIR = "/workspace"
_OWNER_LABEL = "ai.openhands.runtime-owner"
_CONVERSATIONS_DIR: Final[str] = "/var/openhands/conversations"
_PERSISTENCE_DIR: Final[str] = "/var/openhands/.openhands"
_WORKSPACE_DIR: Final[str] = "/workspace"
_OWNER_LABEL: Final[str] = "ai.openhands.runtime-owner"


@dataclass(slots=True)
Expand Down Expand Up @@ -81,6 +84,7 @@ def __init__(self, config: Config) -> None:
self._last_access: dict[UUID, float] = {}
self._sessions: dict[UUID, int] = {}
self._eviction_task: asyncio.Task[None] | None = None
self.reclaimer = Reclaimer(DockerRuntimeStorage(self))

def configure_service(self, service: ConversationService) -> None:
self._service = service
Expand Down Expand Up @@ -120,6 +124,8 @@ def serves_persisted_event_reads(self) -> bool:

async def start(self) -> None:
await asyncio.to_thread(self.cleanup_stale_containers)
# After the cleanup: with no container left, every runtime is reclaimable.
await self.reclaimer.start()
if self.config.conversation_idle_ttl_seconds:
self._eviction_task = asyncio.create_task(self._evict_idle_runtimes_loop())

Expand Down Expand Up @@ -174,6 +180,21 @@ def get(self, conversation_id: UUID) -> ConversationContainer | None:
def is_starting(self, conversation_id: UUID) -> bool:
return conversation_id in self._starts

@asynccontextmanager
async def runtime_idle(self, conversation_id: UUID) -> AsyncIterator[bool]:
"""Hold the lifecycle lock; True if no container runs or starts for the
runtime and it is not being deleted.

Nothing can start a container until the block exits, so files moved
inside it are not in use.
"""
async with self._lock:
yield not (
self.get(conversation_id)
or self.is_starting(conversation_id)
or conversation_id in self._deleting
)

def attach_session(self, conversation_id: UUID) -> None:
"""Record an outer proxied session attached to this runtime.

Expand Down Expand Up @@ -280,6 +301,7 @@ async def stop(self, conversation_id: UUID) -> None:
container = container or started
if container is not None:
await asyncio.to_thread(container.stop)
await self.reclaimer.on_stop(conversation_id)

async def shutdown(self) -> None:
if self._eviction_task is not None:
Expand All @@ -289,6 +311,8 @@ async def shutdown(self) -> None:
self._eviction_task = None
ids = set(self._containers) | set(self._starts)
await asyncio.gather(*(self.stop(cid) for cid in ids), return_exceptions=True)
# Last, so it also covers the stops above; the next start sweeps them.
await self.reclaimer.shutdown()

async def _evict_idle_runtimes_loop(self) -> None:
ttl = self.config.conversation_idle_ttl_seconds
Expand Down Expand Up @@ -350,6 +374,7 @@ async def _evict_idle_runtimes(self, ttl_seconds: float) -> None:
ttl_seconds,
)
await service.refresh_persisted_conversation(conversation_id)
await self.reclaimer.on_stop(conversation_id)

def _build_container(self, conversation_id: UUID) -> ConversationContainer:
identity = self.provisioning.load(conversation_id)
Expand Down Expand Up @@ -422,6 +447,9 @@ def _build_container(self, conversation_id: UUID) -> ConversationContainer:
"ALL",
"--security-opt",
"no-new-privileges",
# Core dumps land in the bind-mounted workspace at 1-2 GB each.
"--ulimit",
"core=0",
"--add-host",
"host.docker.internal:host-gateway",
"--label",
Expand Down
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"]
21 changes: 21 additions & 0 deletions openhands-agent-server/openhands/agent_server/storage/model.py
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
80 changes: 80 additions & 0 deletions openhands-agent-server/openhands/agent_server/storage/reclaimer.py
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:
Comment thread
VascoSch92 marked this conversation as resolved.
Resolved
"""Frees what a runtime mode stores per conversation, by tier.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The 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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The 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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

"runtime mode" is the value of Config.conversation_runtime, the Literal["local", "docker"] at openhands-agent-server/openhands/agent_server/config.py:367, selected once in create_conversation_registry() (conversation_registry.py:84). That factory returns the registry — the runtime-mode adapter — that the rest of the server programs against:

  • conversation_runtime == "docker" → DockerConversationRegistry (a subclass of ConversationRegistry) is the only registry that constructs a Reclaimer today (docker_runtime/registry.py:85), backed by DockerRuntimeStorage, the only ReclaimableStorage implementation.
  • anything else — only "local" — → the base ConversationRegistry, which has no reclaimer and no storage adapter.

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 $HOME. The agent runs in-process on the host and uses the host's own $HOME/.cache / .npm, so there is nothing per-conversation to reclaim — which is exactly why local has no ReclaimableStorage implementation. The per-conversation storage this module targets (runtime-data/<id>/persistence, the sandbox's own $HOME) exists only in docker mode.

That's also why the abstraction is a Protocol rather than docker-only: the per-conversation things that do pile up in local mode are the git worktrees under conversation_worktree_root, and the follow-up #5433 is the same storage layer for those. So today there are two runtime modes, only one of which has reclaimable per-conversation storage; the generic ReclaimableStorage/Reclaimer shape is there so the layer isn't tied to Docker.


This reply was authored by an AI agent (OpenHands).

Copy link
Copy Markdown

Choose a reason for hiding this comment

The 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 comment

I found and confirmed the facts, then posted a reply to enyst on PR #5263 (thread r4166906195):

"Runtime mode" is the value of Config.conversation_runtime — a Literal["local", "docker"] at openhands-agent-server/openhands/agent_server/config.py:367. It's selected exactly once, in create_conversation_registry() (conversation_registry.py:84), which returns the registry (the runtime-mode adapter) and:

  • "docker" → DockerConversationRegistry, the only registry that constructs a Reclaimer (backed by DockerRuntimeStorage, the only ReclaimableStorage implementation).
  • anything else (only "local") → the base ConversationRegistry, which has no reclaimer and no storage adapter.

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 $HOME/.cache / .npm, so there's no per-conversation sandbox $HOME to reclaim — which is exactly why local has no ReclaimableStorage implementation. The per-conversation dir this module targets (runtime-data/<id>/persistence) only exists in docker mode.

I also explained why the abstraction is a Protocol rather than docker-specific: the per-conversation things that do pile up in local mode are the git worktrees under conversation_worktree_root, and follow-up #5433 reuses the same ReclaimableStorage/Reclaimer layer for those. So today there are two modes, one of which has reclaimable per-conversation storage, and the generic shape is future-proofing so the layer isn't tied to Docker.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The answer above is right: a runtime mode is Config.conversation_runtime, local or docker. In this PR only Docker has a storage adapter; #5433 adds the local one (git worktrees). The ReclaimableStorage docstring now says so (5e1ddaa).


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
15 changes: 15 additions & 0 deletions openhands-agent-server/openhands/agent_server/storage/selectors.py
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
Comment thread
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)]
84 changes: 84 additions & 0 deletions openhands-agent-server/openhands/agent_server/storage/trash.py
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}")
Loading
Loading