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
@@ -1,10 +1,12 @@
import json
import os
import socket
import time
from collections.abc import Iterator
from contextlib import contextmanager
from dataclasses import dataclass
from pathlib import Path
from typing import TypedDict
from typing import NotRequired, TypedDict

from filelock import FileLock

Expand All @@ -28,6 +30,42 @@ class LeasePayload(TypedDict):
owner_instance_id: str
generation: int
expires_at: float
# Optional fields added for crash-recovery. They are absent in lease
# files written by older versions of the agent server, so consumers
# must treat them as optional.
owner_host: NotRequired[str]
owner_pid: NotRequired[int]


def _current_host() -> str:
try:
return socket.gethostname()
except Exception:
return ""


def _is_pid_alive(pid: int) -> bool:
"""Best-effort check for whether ``pid`` is a live process on this host.

Uses ``os.kill(pid, 0)`` which is portable across POSIX platforms and
available on Windows since Python 3.2. When liveness cannot be
determined (permission errors, unsupported platforms, etc.) we
conservatively report the process as alive so we never steal a lease
that might still be in use.
"""
if pid <= 0:
return False
try:
os.kill(pid, 0)
except ProcessLookupError:
return False
except PermissionError:
# Process exists but is owned by another user.
return True
except OSError:
# Unknown error - be conservative and assume the process is alive.
return True
return True


class ConversationLeaseHeldError(RuntimeError):
Expand Down Expand Up @@ -91,17 +129,31 @@ def claim(self) -> LeaseClaim:
current_owner = payload["owner_instance_id"]
current_generation = payload["generation"]
expires_at = payload["expires_at"]
if current_owner != self._owner_instance_id and expires_at > now:
same_owner = current_owner == self._owner_instance_id
if (
not same_owner
and expires_at > now
and not self._owner_is_dead(payload)
):
raise ConversationLeaseHeldError(
conversation_dir=self._conversation_dir,
owner_instance_id=current_owner,
expires_at=expires_at,
)
same_owner = current_owner == self._owner_instance_id
generation = (
current_generation if same_owner else current_generation + 1
)
takeover = not same_owner
if takeover and expires_at > now:
logger.info(
"Taking over conversation lease in %s from dead owner "
"%s (pid=%s host=%s); lease nominally valid until %s",
self._conversation_dir,
current_owner,
payload.get("owner_pid"),
payload.get("owner_host"),
expires_at,
)
else:
generation = 1
takeover = False
Expand All @@ -111,6 +163,27 @@ def claim(self) -> LeaseClaim:
)
return LeaseClaim(generation=generation, takeover=takeover)

def _owner_is_dead(self, payload: LeasePayload) -> bool:
"""Return True if the lease's recorded owner process is gone.

Only considered when the recorded ``owner_host`` matches this
host: liveness checks for PIDs on other hosts are meaningless.
Lease files written by older agent-server versions don't include
host/pid, so this returns False (preserving the legacy
TTL-only behavior) for them.
"""
owner_host = payload.get("owner_host")
owner_pid = payload.get("owner_pid")
if not owner_host or not isinstance(owner_pid, int):
return False
if owner_host != _current_host():
return False
# Don't mistakenly consider ourselves dead if the lease points at
# this very process (e.g. a same-process re-claim).
if owner_pid == os.getpid():
return False
return not _is_pid_alive(owner_pid)

def renew(self, generation: int) -> None:
"""Extend the current lease while keeping the same generation."""
with FileLock(str(self._lock_path)):
Expand Down Expand Up @@ -176,11 +249,18 @@ def _read_payload(self) -> LeasePayload | None:
if not isinstance(expires_at, int | float):
raise ValueError("lease expires_at must be numeric")

return LeasePayload(
payload: LeasePayload = LeasePayload(
owner_instance_id=owner_instance_id,
generation=generation,
expires_at=float(expires_at),
)
owner_host = raw_payload.get("owner_host")
if isinstance(owner_host, str) and owner_host:
payload["owner_host"] = owner_host
owner_pid = raw_payload.get("owner_pid")
if isinstance(owner_pid, int):
payload["owner_pid"] = owner_pid
return payload
except Exception:
logger.warning(
"Failed to parse conversation lease file; treating as stale: %s",
Expand All @@ -193,6 +273,8 @@ def _write_payload(self, *, generation: int, expires_at: float) -> None:
"owner_instance_id": self._owner_instance_id,
"generation": generation,
"expires_at": expires_at,
"owner_host": _current_host(),
"owner_pid": os.getpid(),
}
tmp_path = self._lease_path.with_suffix(".tmp")
tmp_path.write_text(json.dumps(payload))
Expand Down
172 changes: 172 additions & 0 deletions tests/agent_server/test_conversation_lease.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import json
import os
import socket
import time
from pathlib import Path
from typing import cast

import pytest

from openhands.agent_server import conversation_lease as conversation_lease_module
from openhands.agent_server.conversation_lease import (
LEASE_FILE_NAME,
ConversationLease,
Expand Down Expand Up @@ -132,3 +135,172 @@ def test_release_keeps_new_owner_lease_intact_after_takeover(tmp_path: Path) ->

secondary.release(secondary_claim.generation)
assert not (conversation_dir / LEASE_FILE_NAME).exists()


def test_claim_writes_owner_host_and_pid(tmp_path: Path) -> None:
conversation_dir = tmp_path / "conversation"
lease = ConversationLease(
conversation_dir=conversation_dir,
owner_instance_id="primary",
)

lease.claim()
payload = _read_lease_payload(conversation_dir)

assert payload.get("owner_host") == socket.gethostname()
assert payload.get("owner_pid") == os.getpid()


def test_claim_takes_over_when_previous_owner_pid_is_dead(
tmp_path: Path,
) -> None:
"""Simulates a non-graceful shutdown: a dead PID still owns a live lease.

Without the crash-recovery check the second claim would fail with
``ConversationLeaseHeldError`` until the TTL elapsed and the
conversation would be skipped on agent-server restart.
"""
conversation_dir = tmp_path / "conversation"
primary = ConversationLease(
conversation_dir=conversation_dir,
owner_instance_id="primary",
ttl_seconds=3600.0, # Make sure the TTL is far from elapsing.
)
primary_claim = primary.claim()
payload = _read_lease_payload(conversation_dir)
# Sanity: lease is nominally valid.
assert payload["expires_at"] > time.time() + 60

# Forge a lease that points at a PID guaranteed not to exist on this
# host. PID 2**31 - 1 is well beyond /proc/sys/kernel/pid_max in any
# real environment.
dead_pid = 2**31 - 1
forged = dict(payload)
forged["owner_pid"] = dead_pid
(conversation_dir / LEASE_FILE_NAME).write_text(json.dumps(forged))

secondary = ConversationLease(
conversation_dir=conversation_dir,
owner_instance_id="secondary",
)
secondary_claim = secondary.claim()

new_payload = _read_lease_payload(conversation_dir)
assert secondary_claim.takeover is True
assert secondary_claim.generation == primary_claim.generation + 1
assert new_payload["owner_instance_id"] == "secondary"
assert new_payload.get("owner_pid") == os.getpid()


def test_claim_blocks_takeover_when_owner_is_on_a_different_host(
tmp_path: Path,
) -> None:
"""Liveness checks must not fire for owners on other hosts.

If the lease was written by a peer agent-server running on a
different machine, our local PID table tells us nothing about
whether that process is alive, so we must fall back to the TTL.
"""
conversation_dir = tmp_path / "conversation"
primary = ConversationLease(
conversation_dir=conversation_dir,
owner_instance_id="primary",
ttl_seconds=3600.0,
)
primary.claim()

payload = _read_lease_payload(conversation_dir)
forged = dict(payload)
forged["owner_host"] = "some-other-host"
forged["owner_pid"] = 2**31 - 1 # would be "dead" if checked locally
(conversation_dir / LEASE_FILE_NAME).write_text(json.dumps(forged))

secondary = ConversationLease(
conversation_dir=conversation_dir,
owner_instance_id="secondary",
)
with pytest.raises(ConversationLeaseHeldError):
secondary.claim()


def test_claim_falls_back_to_ttl_for_legacy_lease_files(
tmp_path: Path,
) -> None:
"""Lease files written by older versions don't include host/pid.

They must continue to behave exactly as before: TTL-only expiry
decides whether a takeover may occur.
"""
conversation_dir = tmp_path / "conversation"
conversation_dir.mkdir(parents=True)
legacy_payload = {
"owner_instance_id": "primary",
"generation": 7,
"expires_at": time.time() + 3600.0,
}
(conversation_dir / LEASE_FILE_NAME).write_text(json.dumps(legacy_payload))

secondary = ConversationLease(
conversation_dir=conversation_dir,
owner_instance_id="secondary",
)
with pytest.raises(ConversationLeaseHeldError):
secondary.claim()


def test_owner_pid_check_treats_unknown_errors_as_alive(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""We must err on the side of not stealing live leases."""
conversation_dir = tmp_path / "conversation"
primary = ConversationLease(
conversation_dir=conversation_dir,
owner_instance_id="primary",
ttl_seconds=3600.0,
)
primary.claim()

def _raise_oserror(_pid: int, _sig: int) -> None:
raise OSError("EPERM-like error from a sandbox")

monkeypatch.setattr(conversation_lease_module.os, "kill", _raise_oserror)

# Forge the lease so it points at a PID that is NOT this process
# (otherwise the same-process short-circuit kicks in before
# _is_pid_alive is consulted).
payload = _read_lease_payload(conversation_dir)
forged = dict(payload)
forged["owner_pid"] = os.getpid() + 1
(conversation_dir / LEASE_FILE_NAME).write_text(json.dumps(forged))

secondary = ConversationLease(
conversation_dir=conversation_dir,
owner_instance_id="secondary",
)
with pytest.raises(ConversationLeaseHeldError):
secondary.claim()


def test_claim_self_pid_match_is_not_treated_as_dead(tmp_path: Path) -> None:
"""A lease referring to *this* process must never be considered dead.

Otherwise a same-process re-entry (e.g. tests, or a fast restart that
happens to reuse the same PID) could erroneously trigger a takeover.
"""
conversation_dir = tmp_path / "conversation"
primary = ConversationLease(
conversation_dir=conversation_dir,
owner_instance_id="primary",
ttl_seconds=3600.0,
)
primary.claim()

# The lease already has owner_pid == os.getpid(). A different-owner
# claim must still be rejected.
secondary = ConversationLease(
conversation_dir=conversation_dir,
owner_instance_id="secondary",
)
with pytest.raises(ConversationLeaseHeldError):
secondary.claim()
45 changes: 45 additions & 0 deletions tests/agent_server/test_conversation_service.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import asyncio
import json
import socket
import tempfile
import threading
import time
Expand Down Expand Up @@ -219,6 +220,50 @@ async def test_stale_owner_cannot_append_after_lease_takeover(tmp_path):
primary_state.execution_status = ConversationExecutionStatus.ERROR


@pytest.mark.asyncio
async def test_restart_resumes_conversations_after_non_graceful_shutdown(tmp_path):
"""Reproduces the crash-recovery bug: after a non-graceful shutdown the lease
file is left on disk pointing at a still-future expires_at. A fresh server
started before the TTL elapses must still pick up the conversation rather
than skipping it for up to the full TTL window.
"""
conversations_dir = tmp_path / "conversations"
workspace_dir = tmp_path / "workspace"
workspace_dir.mkdir()

request = StartConversationRequest(
agent=Agent(llm=LLM(model="gpt-4o", usage_id="test-llm"), tools=[]),
workspace=LocalWorkspace(working_dir=str(workspace_dir)),
confirmation_policy=NeverConfirm(),
)

async with ConversationService(conversations_dir=conversations_dir) as primary:
conversation_info, _ = await primary.start_conversation(request)
conversation_id = conversation_info.id

# Simulate a non-graceful shutdown: forge a lease pointing at a PID
# that is guaranteed not to be running, with a far-future expires_at.
# A clean exit would have removed the lease via release(); a crash
# leaves it behind, which is what we are reproducing here.
lease_path = conversations_dir / conversation_id.hex / LEASE_FILE_NAME
forged_payload = {
"owner_instance_id": "ghost-instance-from-crashed-server",
"generation": 1,
"expires_at": time.time() + 3600.0,
"owner_host": socket.gethostname(),
"owner_pid": 2**31 - 1,
}
lease_path.write_text(json.dumps(forged_payload))

async with ConversationService(conversations_dir=conversations_dir) as restarted:
assert restarted._event_services is not None
# The conversation must be present in the restarted service.
assert conversation_id in restarted._event_services, (
"Restart failed to pick up an existing conversation whose lease "
"was left orphaned by a non-graceful shutdown."
)


class TestConversationServiceSearchConversations:
"""Test cases for ConversationService.search_conversations method."""

Expand Down
Loading