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
120 changes: 112 additions & 8 deletions openhands/app_server/sandbox/lifecycle/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,13 @@
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from openhands.app_server.app_conversation.app_conversation_info_service import (
AppConversationInfoService,
)
from openhands.app_server.app_conversation.app_conversation_models import (
ARCHIVE_WORKSPACE_PATH_TAG_KEY,
)
from openhands.app_server.sandbox import workspace_archive
from openhands.app_server.sandbox.lifecycle.rules import (
Action,
Decision,
Expand Down Expand Up @@ -58,23 +65,34 @@ def _managed_backend() -> ManagedSandboxServiceInjector | None:


@contextlib.asynccontextmanager
async def _services() -> AsyncIterator[tuple[AsyncSession, ManagedSandboxService]]:
async def _services() -> AsyncIterator[
tuple[AsyncSession, ManagedSandboxService, AppConversationInfoService]
]:
"""The services the jobs use, acting for every user.

They share one database session, committed when the block ends.
They share one database session, committed when the block ends. The
conversation info service is built on that same session so the archive
step's reads and the row lock see one consistent transaction.
"""
from openhands.app_server.config import get_sandbox_service
from openhands.app_server.app_conversation.sql_app_conversation_info_service import (
SQLAppConversationInfoService,
)
from openhands.app_server.config import get_sandbox_service, get_user_context
from openhands.app_server.services.db_session import get_db_session

state = InjectorState()
setattr(state, USER_CONTEXT_ATTR, ADMIN)
async with (
get_db_session(state) as db_session,
get_sandbox_service(state) as sandbox_service,
get_user_context(state, None) as user_context,
):
# The jobs only run when the backend's injector is managed.
assert isinstance(sandbox_service, ManagedSandboxService)
yield db_session, sandbox_service
conversation_info_service = SQLAppConversationInfoService(
db_session=db_session, user_context=user_context
)
yield db_session, sandbox_service, conversation_info_service


async def pause_running_sandboxes() -> None:
Expand All @@ -85,7 +103,7 @@ async def pause_running_sandboxes() -> None:
backend = _managed_backend()
if backend is None:
return
async with _services() as (db_session, _):
async with _services() as (db_session, _, _):
result = await db_session.execute(
select(StoredSandbox.id).where(
StoredSandbox.backend == backend.backend,
Expand All @@ -96,7 +114,7 @@ async def pause_running_sandboxes() -> None:

async def pause(sandbox_id: str) -> None:
try:
async with _services() as (_, sandbox_service):
async with _services() as (_, sandbox_service, _):
paused = await sandbox_service.pause_sandbox(sandbox_id)
except Exception:
_logger.exception(
Expand All @@ -120,7 +138,7 @@ async def sweep(context: JobContext, timestamp: int) -> None:
backend = _managed_backend()
if backend is None:
return
async with _services() as (db_session, _):
async with _services() as (db_session, _, _):
sandbox_ids = await find_due_sandbox_ids(
db_session,
backend.backend,
Expand Down Expand Up @@ -154,25 +172,89 @@ async def check(sandbox_id: str) -> None:
return
async with (
asyncio.timeout(CHECK_TIMEOUT_SECONDS),
_services() as (db_session, sandbox_service),
_services() as (db_session, sandbox_service, conversation_info_service),
):
await check_sandbox(
sandbox_id,
backend=backend.backend,
settings=backend.lifecycle,
db_session=db_session,
sandbox_service=sandbox_service,
conversation_info_service=conversation_info_service,
now=datetime.now(UTC),
)


async def _archive_conversations_for_sandbox(
sandbox_service: ManagedSandboxService,
conversation_info_service: AppConversationInfoService,
sandbox_id: str,
) -> bool:
"""Archive every conversation workspace tied to the sandbox before it is torn down.

The idle/expiry reap path pauses or deletes a sandbox without going through
conversation delete, so on Docker Compose / self-hosted installs the
workspace would be captured by nobody. This closes that gap by running the
same conversation-scoped capture the delete finalizer does, for every
conversation still referencing the sandbox, using the workspace path pinned
at creation (read from the conversation's tags).

Returns whether the sandbox is safe to pause or delete. A REQUIRED archive
that could not confirm a capture returns False so the caller leaves the
sandbox (and its runtime) for the next sweep to retry — the durability
backstop. Missing conversations, disabled archiving, or best-effort failures
return True. Never raises.
"""
if not workspace_archive.archive_enabled():
return True
try:
page = await conversation_info_service.search_app_conversation_info(
sandbox_id__eq=sandbox_id, limit=100, include_sub_conversations=True
)
except Exception:
_logger.exception(
'sandbox_lifecycle.archive_lookup_failed',
extra={'sandbox_id': sandbox_id},
)
# Could not read who to capture: keep the sandbox for a retry rather
# than risk tearing it down with uncaptured work.
return not workspace_archive.archive_required()
if not page.items:
# No conversation references it (or all were already deleted): nothing
# to capture, proceed.
return True
safe_to_reap = True
for info in page.items:
workspace_path = info.tags.get(ARCHIVE_WORKSPACE_PATH_TAG_KEY)
try:
archived = await sandbox_service.archive_conversation_workspace(
sandbox_id,
conversation_id=info.id.hex,
workspace_path=workspace_path,
)
except Exception:
_logger.exception(
'sandbox_lifecycle.archive_conversation_failed',
extra={'sandbox_id': sandbox_id, 'conversation_id': str(info.id)},
)
archived = False
if not archived:
safe_to_reap = False
_logger.warning(
'sandbox_lifecycle.archive_required_failed',
extra={'sandbox_id': sandbox_id, 'conversation_id': str(info.id)},
)
return safe_to_reap


async def check_sandbox(
sandbox_id: str,
*,
backend: str,
settings: SandboxLifecycleSettings,
db_session: AsyncSession,
sandbox_service: ManagedSandboxService,
conversation_info_service: AppConversationInfoService,
now: datetime,
) -> Decision | None:
"""Apply the rules to one sandbox. The caller commits.
Expand Down Expand Up @@ -206,6 +288,17 @@ async def check_sandbox(
'state_changed_at': row.state_changed_at.isoformat(),
}
if decision.action == Action.PAUSE:
# Capture every conversation's workspace before the runtime is stopped,
# so an idle/max-session pause does not lose work on self-hosted installs
# where the runtime's own idle reap does not run.
if not await _archive_conversations_for_sandbox(

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.

Blocking: a slow capture now stops idle pause and inactive delete, even when archiving is best-effort.

check() runs this whole function inside asyncio.timeout(CHECK_TIMEOUT_SECONDS), which is 120s. The capture this step runs can legitimately take much longer:

  • workspace_archive._archive_timeout() defaults to 660s. That limit exists to cover the agent-server git build for large repos.
  • On the delete path, the Docker backend first restarts the stopped container (_resume_for_archive) and waits up to ARCHIVE_RESUME_HEALTH_TIMEOUT_SECONDS = 60 for it to become healthy.
  • Conversations are archived one after another (up to 100 per sandbox).

When the budget runs out, the timeout raises CancelledError/TimeoutError. The except Exception here doesn't catch them, so pause_sandbox and delete_sandbox never run and the transaction rolls back. The next sweep repeats the same capture and times out again. A sandbox with a large workspace is then never paused or deleted, regardless of RUNTIME_FILE_ARCHIVE_REQUIRED. On main, the same sandbox would simply be paused.

On Docker's delete path it also leaks a container. _resume_for_archive has already restarted it, but the rollback reverts mark_running, so the container keeps running while its row still says paused.

I confirmed the best-effort case with a throwaway probe: an archive slower than an outer asyncio.timeout left the sandbox RUNNING on all three harnesses.

Fix options, any of which works:

  • Give the archive step its own time budget, outside or larger than the check timeout.
  • Bound each capture, and in best-effort mode treat a timeout as "proceed".
  • Move the capture to its own job that the pause or delete waits for.

Whichever you pick, add a test for the slow and timeout case.

sandbox_service, conversation_info_service, sandbox_id
):
_logger.info(
'sandbox_lifecycle.pause_deferred_for_archive',
extra=log_extra,
)
return decision
# pause_sandbox updates this same row, through the session's identity
# map, and leaves it running when the provider skips the pause.
if not await sandbox_service.pause_sandbox(sandbox_id):
Expand All @@ -215,6 +308,17 @@ async def check_sandbox(
else:
_logger.info('sandbox_lifecycle.pause_skipped', extra=log_extra)
elif decision.action == Action.DELETE:
# The last step before teardown: capture every conversation's workspace
# so the delete does not lose work. A REQUIRED failure keeps the sandbox
# + runtime for the next sweep to retry, instead of tearing it down.
if not await _archive_conversations_for_sandbox(
sandbox_service, conversation_info_service, sandbox_id
):
_logger.info(
'sandbox_lifecycle.delete_deferred_for_archive',
extra=log_extra,
)
return decision
await sandbox_service.delete_sandbox(sandbox_id)
_logger.info('sandbox_lifecycle.deleted', extra=log_extra)
elif decision.action == Action.RECORD_PAUSE:
Expand Down
Loading
Loading