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
93 changes: 67 additions & 26 deletions src/agent_env/runner/local_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,18 @@
semaphore. ``submit()`` fires the run in the background and returns immediately; there is no
persisted queue or lease, so the run's asyncio task lives only in this process.

Consequence: a run does not survive its process. Each run records the process that owns it, which marks it seen
while it runs; ``start()``, and a started runner from then on, fails a run left non-terminal by an owner that is
gone (it can't still be executing), and ``stop()`` cancels the ones in flight. A durable, lease-based runner that resurrects a run across a restart — and supports
multiple worker processes — is a follow-up; configure an external durable ``[runner]`` where that matters.
Consequence: a run does not survive its process. Each run records the process that owns it, and that process marks
the run seen while it runs. An episode records and marks its run the same way. ``start()``, and a started runner
from then on, fails a run whose owner is gone, since nothing can still be executing it, and ends its instance failed
too. ``stop()`` cancels the runs in flight. A durable, lease-based runner that resurrects a run across a restart, and
supports multiple worker processes, is a follow-up; configure an external durable ``[runner]`` where that matters.
"""

from __future__ import annotations

import asyncio
import contextlib
import functools
import logging
import os
import socket
Expand All @@ -21,10 +23,11 @@

from agent_env.runner import store as run_store
from agent_env.runner.runner import KEEP_KEY, RunHandle, RunRecord, Runner, RunStatus, run_outcome
from agent_env.task.store import new_instance_id
from agent_env.task.store import get_task_instance_store, new_instance_id
from agent_env.task.teardown import TERMINATE_TIMEOUT_SECONDS, teardown_run

logger = logging.getLogger(__name__)
ORPHANED_ERROR = "the process running it is gone, as after a restart"


class LocalRunner(Runner):
Expand All @@ -41,9 +44,9 @@ class LocalRunner(Runner):
# After those waits, how long stop() gives a run it cancels again before shutting down without it.
ABANDON_WAIT_SECONDS = 1
# How often a runner marks its runs seen, and a started one reconciles orphans.
OWNER_SEEN_SECONDS = 30
# How long after it last marked a run seen an owner on another host still counts as alive.
OWNER_LEASE_SECONDS = 120
OWNER_SEEN_SECONDS = run_store.OWNER_SEEN_SECONDS
# How long after it last marked a run seen an owner still counts as alive, whatever its pid looks like.
OWNER_LEASE_SECONDS = run_store.OWNER_LEASE_SECONDS

def __init__(self, workers: int = 2) -> None:
if workers < 1:
Expand All @@ -61,9 +64,10 @@ def __init__(self, workers: int = 2) -> None:
# --- lifecycle ---------------------------------------------------------

async def start(self) -> None:
"""Reconcile orphans now and every ``OWNER_SEEN_SECONDS`` after: a run left QUEUED/RUNNING by an owner that is
gone has no live task anywhere, so fail it rather than leave it hanging. One a live process owns, such as a
CLI following its runs, is left to it. There is no queue to resume."""
"""Reconcile orphans now and every ``OWNER_SEEN_SECONDS`` after. A run left QUEUED/RUNNING by an owner that is
gone, and past its lease, has no live task anywhere, so fail it and its instance rather than leave them
hanging. One a live process owns, such as a CLI following its runs, is left to it, and so is an instance a
live run resumed. There is no queue to resume."""
run_store.ensure_indexes()
self._reconciles = True
self._reconcile()
Expand All @@ -86,11 +90,18 @@ async def _watch_runs(self) -> None:
self.OWNER_SEEN_SECONDS, exc_info=True)

def _reconcile(self) -> None:
orphaned = 0
for record in run_store.active_runs(self.type):
if _owner_alive(record.owner):
from agent_env.task import Task

orphaned, owned = 0, (self.type, run_store.EPISODE_RUNNER)
for record in (record for runner in owned for record in run_store.active_runs(runner)):
if not _reaped(record, owned) or _owner_alive(record.owner):
continue
run_store.mark_terminal(record.run_id, RunStatus.FAILED, error="interrupted by a hub restart")
ended = get_task_instance_store().fail_unless_held_sync(
record.instance_id, ORPHANED_ERROR, Task._utc_now_str(),
held=functools.partial(_may_still_run, record, owned))
if not ended:
continue # its owner came back, or a live run resumed its instance; a later pass looks again
run_store.mark_terminal(record.run_id, RunStatus.FAILED, error=ORPHANED_ERROR)
orphaned += 1
if orphaned:
logger.info("Failed %d run(s) left non-terminal by a previous process", orphaned)
Expand Down Expand Up @@ -299,19 +310,49 @@ def _seed_context(self, record: RunRecord, stored):
return context


def _may_still_run(record: RunRecord, owned: tuple[str, ...]) -> bool:
"""Whether, by a fresh read of the run index, ``record``'s instance may still be played: ``record`` has ended or its
owner is alive after all, or another run in flight on the instance may still be running. The reconciler listed
``record`` earlier, and its owner may have marked it seen since."""
in_flight = run_store.in_flight_runs(record.instance_id)
if all(run.run_id != record.run_id for run in in_flight):
return True
for run in in_flight:
if not _reaped(run, owned):
logger.debug("Leaving run %s in flight: run %s of runner %r, which the reconciler leaves to its owner, is in "
"flight on its instance", record.run_id, run.run_id, run.runner)
return True
if _owner_alive(run.owner):
return True
return False


def _reaped(record: RunRecord, owned: tuple[str, ...]) -> bool:
"""Whether the reconciler may fail ``record`` once its owner looks gone. An episode qualifies only when its owner
says it renews ``seen``: an episode recorded by an earlier version never renews it, so its lease lapses while it
still plays, and it is left to its owner."""
if record.runner == run_store.EPISODE_RUNNER:
return bool((record.owner or {}).get(run_store.OWNER_RENEWS))
return record.runner in owned


def _owner_alive(owner: Optional[dict]) -> bool:
"""Whether the process that submitted a run may still be running it: on this host, whether its pid is alive; on
another, whether it marked the run seen within ``OWNER_LEASE_SECONDS``. A run naming no owner predates owners."""
"""Whether the process that submitted a run may still be running it: whether it marked the run seen within
``OWNER_LEASE_SECONDS``, or, on this host, whether its pid is alive. A host name can be shared across pid
namespaces, as by containers on the host's network, so a pid that looks gone counts only once the lease has
lapsed too. A run naming no owner predates owners."""
if not owner:
return False
if owner["host"] == socket.gethostname():
try:
os.kill(owner["pid"], 0)
except ProcessLookupError:
return False
except PermissionError:
return True
return True
seen = owner.get("seen")
lease = timedelta(seconds=LocalRunner.OWNER_LEASE_SECONDS)
return seen is not None and datetime.now(timezone.utc) - datetime.fromisoformat(seen) < lease
if seen is not None and datetime.now(timezone.utc) - datetime.fromisoformat(seen) < lease:
return True
if owner["host"] != socket.gethostname():
return False
try:
os.kill(owner["pid"], 0)
except ProcessLookupError:
return False
except PermissionError:
return True
return True
31 changes: 25 additions & 6 deletions src/agent_env/runner/store.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,13 @@
from agent_env.task_step.context import strip_redacted_keys

RUNS_COLLECTION = "runs"
# The runner an episode records its run under, naming the process that plays it as a LocalRunner names its own.
EPISODE_RUNNER = "episode"
# Set in an episode's owner by the versions that renew its ``seen``, the only episodes the reconciler fails.
OWNER_RENEWS = "renews"
# How often a process marks the runs it owns seen, and how long after its last mark it still counts as alive.
OWNER_SEEN_SECONDS = 30
OWNER_LEASE_SECONDS = 120

# Terminal states are never overwritten: mark_terminal/set_running only act on a run that
# is still QUEUED or RUNNING, so a completion racing a cancel can't resurrect a CANCELED run.
Expand All @@ -30,13 +37,14 @@ def _now() -> str:


def _docs():
"""The configured document store, with the indexes backing the two reads (status-by-run-id and the per-task
listing) made once per store: a caller that never ``start()``s a runner still gets them."""
"""The configured document store, with the indexes backing its reads (status-by-run-id, the per-task listing and
the runs of an instance) made once per store: a caller that never ``start()``s a runner still gets them."""
global _indexed
docs = get_config().get_document_store()
if _indexed is not docs:
docs.ensure_index(RUNS_COLLECTION, ["run_id"], unique=True)
docs.ensure_index(RUNS_COLLECTION, ["task_id", "created_at_utc"])
docs.ensure_index(RUNS_COLLECTION, ["instance_id"])
_indexed = docs
return docs

Expand Down Expand Up @@ -85,6 +93,16 @@ def active_runs(runner: str, limit: int = 100_000) -> list[RunRecord]:
return [RunRecord.from_dict(d) for d in docs]


def in_flight_runs(instance_id: str) -> list[RunRecord]:
"""Every QUEUED/RUNNING run naming one instance: the run that made it, any that resumed it, and any submitted for
it under another task, which fails only once it starts."""
docs = _docs().query(
RUNS_COLLECTION,
Filter(conditions={"instance_id": [Eq(instance_id)], "status": _NON_TERMINAL}),
)
return [RunRecord.from_dict(d) for d in docs]


def set_running(run_id: str) -> None:
"""QUEUED -> RUNNING once a worker slot frees. No-op if the run is no longer QUEUED
(e.g. it was canceled while waiting for the slot)."""
Expand All @@ -95,13 +113,14 @@ def set_running(run_id: str) -> None:
)


def see(run_id: str) -> None:
"""Mark a non-terminal run as still seen by its owner: what keeps an owner on another host counting as alive."""
_docs().update(
def see(run_id: str) -> bool:
"""Mark a non-terminal run as still seen by its owner: what keeps an owner on another host counting as alive.
Whether the run was still in flight to mark."""
return bool(_docs().update(
RUNS_COLLECTION,
Filter(conditions={"run_id": [Eq(run_id)], "status": _NON_TERMINAL}),
UpdateSpec(set={"owner.seen": _now()}),
)
))


def mark_terminal(run_id: str, status: RunStatus, error: Optional[str] = None) -> None:
Expand Down
29 changes: 27 additions & 2 deletions src/agent_env/task/episode/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,10 +260,12 @@ async def _drive(self, running: asyncio.Event) -> None:
running.set()
with namespace_routing():
failure: BaseException | None = None
seeing: asyncio.Task[None] | None = None
try:
# Before any await, so start() returns with the run listed; a write that fails is the run's error, and
# the finally below still takes the episode out of _live.
_record_run(self._task, self.id, self._context.metadata)
seeing = asyncio.create_task(self._keep_seen())
await self._task.run(context=self._context, instance_id=self.id)
self._ran = True
self._notify()
Expand All @@ -283,11 +285,29 @@ async def _drive(self, running: asyncio.Event) -> None:
await asyncio.to_thread(_record_cancelled, self._task.id, self.id, self._abandoned,
self._seeded_steps(), self._context, epoch)
finally:
if seeing is not None:
seeing.cancel()
try:
await asyncio.to_thread(_record_ended, self._task.id, self.id, *self._outcome(failure))
finally:
del _live[self.id]

async def _keep_seen(self) -> None:
"""Mark the run seen as a LocalRunner marks its own, through teardown, so a reconciler on another host leaves
it while this process plays it and fails it once it doesn't. A run already ended under it, as a reconciler
ends one whose owner looked gone, can't be marked again: the episode plays on and its run stays ended."""
while True:
await asyncio.sleep(run_store.OWNER_SEEN_SECONDS)
try:
if not await asyncio.to_thread(_record_seen, self._task.id, self.id):
logger.warning("episode %s: run %s was ended by another process, as a reconciler ends a run whose "
"owner looks gone; the episode plays on, but its run and instance stay ended",
self.id, _run_id(self.id))
return
except Exception:
logger.warning("episode %s: couldn't mark its run seen; trying again in %ss", self.id,
run_store.OWNER_SEEN_SECONDS, exc_info=True)

def _outcome(self, failure: BaseException | None) -> tuple[RunStatus, str | None]:
"""How the run ended, by the rule every runner records a run's end by (``run_outcome``: a step that failed
without failing the task fails the run too), but cancelled when it was abandoned or cancelled."""
Expand Down Expand Up @@ -405,9 +425,9 @@ def _record_run(task: Task, instance_id: str, metadata: dict[str, Any]) -> None:
now = datetime.now(timezone.utc).isoformat()
with run_scope(task.id):
run_store.insert_run(RunRecord(
run_id=_run_id(instance_id), runner="episode", task_id=task.id, task_version=task.version,
run_id=_run_id(instance_id), runner=run_store.EPISODE_RUNNER, task_id=task.id, task_version=task.version,
instance_id=instance_id, status=RunStatus.RUNNING, started_at_utc=now,
owner={"host": socket.gethostname(), "pid": os.getpid(), "seen": now},
owner={"host": socket.gethostname(), "pid": os.getpid(), "seen": now, run_store.OWNER_RENEWS: True},
overrides={"metadata": {key: metadata[key] for key in ("episode", "run_group_id", "seed")
if key in metadata}}))

Expand All @@ -417,6 +437,11 @@ def _record_ended(task_id: str, instance_id: str, status: RunStatus, error: str
run_store.mark_terminal(_run_id(instance_id), status, error=error)


def _record_seen(task_id: str, instance_id: str) -> bool:
with run_scope(task_id):
return run_store.see(_run_id(instance_id))


def _run_id(instance_id: str) -> str:
return f"episode-{instance_id}"

Expand Down
16 changes: 16 additions & 0 deletions src/agent_env/task/store.py
Original file line number Diff line number Diff line change
Expand Up @@ -945,6 +945,22 @@ def replaced(entries: list | None, entry: dict) -> list[dict]:
return compare_and_swap(docs or self._doc_store, TASK_INSTANCES_COLLECTION, Filter.of(instance_id=instance_id),
_mutate, counter_field=_RUN_RECORDS_REV) is not None

def fail_unless_held_sync(self, instance_id: str, error: str, completed_at_utc: str, *,
held: Callable[[], bool]) -> bool:
"""End a ``running`` instance ``failed``, unless ``held()`` says a live run may hold it. ``held()`` is asked
first, then again on each read of the document the write would land on. Whether no live run held it."""
free = not held()

def owns(doc: dict) -> bool:
nonlocal free
free = not held()
return free and doc.get("status") == "running"

if free:
self._end_write(instance_id, [], lambda doc: {"status": "failed", "error": error,
"completed_at_utc": completed_at_utc}, owns=owns)
return free

def record_teardown_sync(self, instance_id: str, context: "TaskStepContext", attempt_epoch: int) -> None:
"""Keep the context a run's teardown ended with: what the run deployed, writes of a step a signal cut short
included, and what the teardown took down and left up, unless an attempt later than ``attempt_epoch``, the
Expand Down
Loading
Loading