diff --git a/src/agent_env/runner/local_runner.py b/src/agent_env/runner/local_runner.py index 400dd1ef7..be73021a5 100644 --- a/src/agent_env/runner/local_runner.py +++ b/src/agent_env/runner/local_runner.py @@ -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 @@ -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): @@ -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: @@ -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() @@ -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) @@ -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 diff --git a/src/agent_env/runner/store.py b/src/agent_env/runner/store.py index b4356fff6..0ae7dd86e 100644 --- a/src/agent_env/runner/store.py +++ b/src/agent_env/runner/store.py @@ -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. @@ -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 @@ -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).""" @@ -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: diff --git a/src/agent_env/task/episode/run.py b/src/agent_env/task/episode/run.py index a9af65c3d..595b65555 100644 --- a/src/agent_env/task/episode/run.py +++ b/src/agent_env/task/episode/run.py @@ -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() @@ -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.""" @@ -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}})) @@ -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}" diff --git a/src/agent_env/task/store.py b/src/agent_env/task/store.py index 4b7d400a2..985e6e303 100644 --- a/src/agent_env/task/store.py +++ b/src/agent_env/task/store.py @@ -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 diff --git a/tst/formal/run_orphan_reaping/AGENTS.md b/tst/formal/run_orphan_reaping/AGENTS.md new file mode 100644 index 000000000..dbcb7f92a --- /dev/null +++ b/tst/formal/run_orphan_reaping/AGENTS.md @@ -0,0 +1,254 @@ +# AGENTS.md: model-checking how orphaned runs are reaped + +How to check a change to the reconciler that fails runs whose process died, and ends their task instances, against the +TLA+ model in this directory. The repository-wide rules are in the root `AGENTS.md`. + +A run has two records: its entry in the run index (`runs`, written by the runner) and its task instance +(`task_instances`, written by `Task.run`). When the process running a run dies, it never writes either again. A started +`LocalRunner` reconciles every `OWNER_SEEN_SECONDS`. It fails each in-flight `local` run whose owner is gone, and ends +that run's instance `failed` first. It does the same for an `episode` run only when the run's owner carries +`renews: true`. Only versions that renew an episode's lease write that marker. An episode recorded by an earlier version +never renews its lease, so the reconciler leaves it to its owner, as before episodes were reaped. `RunOrphanReaping.tla` models both records, the processes that run +the runs, and the reconciler. Each action is one store call (an insert, an update, a query, or one compare-and-swap read +or write) or a process that dies, stalls or comes back. TLC, the TLA+ model checker, explores every interleaving of them. +It checks four rules: + +- `InstanceEndsWithItsRuns`. An instance shown `running` always has a run in flight, so once every run of an instance + has ended, the instance has ended too. If this breaks, the explorer's instance progress never reports `done`, a client + polling it never stops, and `agent-env task teardown` refuses the instance without `--force`. The run index spells + statuses `QUEUED`, `RUNNING`, `COMPLETED`, `FAILED`, `CANCELED`. The instance spells `running`, `completed`, `failed`, + `cancelled`. +- `NoLiveAttemptEnded`. The reconciler never ends an instance while a live run is making its attempt on it. If this + breaks, a working run is shown failed, and its last step's completion can no longer mark the instance `completed` + (`record_step_complete_sync` never overwrites `failed`). +- `NoLiveRunFailed`. The reconciler never fails a run whose process was live when it last looked at the run. If this + breaks, a live run, such as an episode a trainer plays on another host, is shown failed while it runs. +- `DeadRunsEnd`. A run whose process died is eventually terminal. Episodes recorded by an earlier version are exempt: + they never renew their lease, so they are left to their owner, as before. If this breaks, the run shows `RUNNING` forever, and an episode's run + group never completes. + +A process counts as live when it is alive and either keeps marking its run seen or runs on the reconciler's host where +its pid shows (`Live` in the model). A process that stalls past the lease where its pid can't be seen counts as gone. +That is the lease's design, and it is a real limit: see "Live runs the reconciler can still fail" below. + +## Runs and configs + +`r1` and `r2` are `LocalRunner` runs of one instance, and `r2` resumes it. `r3` is an episode with an instance of its +own. `r1` runs on the reconciler's host, which sees its pid. `r2` runs on another host. `r3` runs on another host, or, +with `SharedHostname`, reports the reconciler's host name from another pid namespace, as a container on the host's +network does. `r4` is a `LocalRunner` run of another task submitted with `r1`'s instance id, on the reconciler's host. +`submit()` records the id it is given before `_run` checks which task the instance belongs to, so `r4` fails once it +starts and never plays the instance. `r5` is an episode on another host recorded by an earlier version. It never marks +its run seen and its owner has no `renews` marker. Its instance is its own. With `Stalls`, a live process can stop marking its run seen past the lease and +later mark it again. + +The other constants switch the guards of the fix on or off, so a config can remove one guard and show the rule it +protects. No rule reads a switch. `DeadRunsEnd` reads which runs renew their lease, a fact about the run's version, not a +switch. + +| Config | Runs | What it checks | Expected | +| --- | --- | --- | --- | +| `resume.cfg` | r1, r2 | the code, with a resumed instance | every rule holds | +| `episode.cfg` | r1, r3 | the code, with an episode on another host | every rule holds | +| `shared-host.cfg` | r1, r3 | the code, with an episode that shares the host name | every rule holds | +| `stall.cfg` | r1, r2 | the code, with processes that stall and come back | every rule but `InstanceEndsWithItsRuns` holds | +| `stall-episode.cfg` | r3 | the same for an episode | every rule but `InstanceEndsWithItsRuns` holds | +| `other-task.cfg` | r1, r4 | the code, with a run of another task submitted for r1's instance | every rule holds | +| `old-episode.cfg` | r3, r5 | the code, with an episode from an earlier version beside a current one | every rule holds | +| `prefix-resume.cfg` | r1, r2 | before the fix: only `local` runs reaped, the instance left alone | breaks `InstanceEndsWithItsRuns` | +| `prefix-episode.cfg` | r3 | before the fix, with an episode | breaks `DeadRunsEnd` | +| `run-first.cfg` | r1, r2 | the fix, but the run is failed before its instance | breaks `InstanceEndsWithItsRuns` | +| `unchecked.cfg` | r1, r2 | the fix without the check for another live run | breaks `NoLiveAttemptEnded` | +| `task-scoped.cfg` | r1, r4 | the fix checking only the other runs of the dead run's task | breaks `NoLiveAttemptEnded` | +| `unrechecked.cfg` | r3 | the fix without re-reading the run's own liveness | breaks `NoLiveRunFailed` | +| `pid-only.cfg` | r3 | the fix trusting a pid that looks gone before the lease lapses | breaks `NoLiveRunFailed` | +| `unseen.cfg` | r3 | the fix without episodes marking their run seen | breaks `NoLiveRunFailed` | +| `unmarked.cfg` | r3, r5 | the fix reaping episodes without the `renews` marker | breaks `NoLiveRunFailed` | + +The stall configs leave out `InstanceEndsWithItsRuns` on purpose. A process that stalls past its lease before it +registers its instance is reaped, then registers the instance, then may die. Nothing tracks that instance any more. See +"What the model does not cover". + +## When to run it + +Run the check when a change touches a function in this table. Each action's comment in `RunOrphanReaping.tla` names the +file and line it stands for. + +| Code | Model action | +| --- | --- | +| `runner/local_runner.py` `LocalRunner._reconcile` (the `active_runs` loop, `_reaped`, `_owner_alive`) | `Pick` | +| `runner/local_runner.py` `_reaped`, `runner/store.py` `OWNER_RENEWS` | `Reaped` | +| `runner/local_runner.py` `_owner_alive` | `OwnerGone` | +| `runner/local_runner.py` `_may_still_run`, `runner/store.py` `in_flight_runs` | `Held`, `HeldByAnother` | +| `task/store.py` `TaskInstanceStore.fail_unless_held_sync`, `_end_write`; `store/document_store/document_store.py` `compare_and_swap` | `ReadInstance`, `WriteInstance` | +| `runner/store.py` `mark_terminal`, as the reconciler calls it | `MarkFailed` | +| `runner/local_runner.py` `LocalRunner.submit`, `_run`, `_finish`, `_watch_runs` | `Submit`, `Start`, `FailBeforeRegister`, `EndRun`, `Stall`, `Renew` | +| `task/episode/run.py` `Episode._drive`, `_keep_seen`, `_record_run` (its owner and marker), `_record_ended`, `_record_seen` | `Submit`, `EndRun`, `Stall`, `Renew`, `Reaped` | +| `runner/store.py` `see`, `OWNER_SEEN_SECONDS`, `OWNER_LEASE_SECONDS` | `Renew`, `LeaseRunsOut` | +| `task/task.py` `Task._run` (its `register_task_instance` call), `task/store.py` `upsert_instance` | `Register` | +| `task/store.py` `record_step_complete_sync`, `record_task_failure_sync`, `record_task_cancelled_sync`, `_owns` | `EndInstance` | + +The paths are under `src/agent_env/`. + +The model was last confirmed against the code at the commit that last changed this directory +(`git log -1 -- tst/formal/run_orphan_reaping`). To list the covered changes since then, run: + +```sh +git log "$(git log -1 --format=%H -- tst/formal/run_orphan_reaping)"..HEAD -- src/agent_env/runner/local_runner.py \ + src/agent_env/runner/store.py src/agent_env/task/store.py src/agent_env/task/episode/run.py \ + src/agent_env/store/document_store/document_store.py +``` + +After you confirm that the model still describes a change to the covered code, fix any line citation that moved and +touch this guide in the same commit. + +## Run the check + +```sh +tst/formal/run_orphan_reaping/check.sh # every config +tst/formal/run_orphan_reaping/check.sh one resume.cfg # one run, no expectation +``` + +The script needs Java 11 or later. The first run downloads `tla2tools.jar` v1.7.4 +(https://github.com/tlaplus/tlaplus/releases/tag/v1.7.4) and checks its sha256. To use a jar you already have, set +`TLA2TOOLS` to its path; `JAVA` picks the java binary. Each run gets a copy of the spec and its config, and `tlc.out`, +in a fresh directory under `$TMPDIR` (or `OUT`), which the script prints. The script exits nonzero when any config +differs from its expected outcome. The whole check takes about four minutes, three of them on `stall`. A passing check prints: + +``` +ok resume holds 8136 distinct states found +ok episode holds 2828 distinct states found +ok shared-host holds 2828 distinct states found +ok stall holds 222709 distinct states found +ok stall-episode holds 944 distinct states found +ok other-task holds 1074 distinct states found +ok old-episode holds 1566 distinct states found +ok prefix-resume violates InstanceEndsWithItsRuns 131 distinct states found +ok prefix-episode violates DeadRunsEnd 27 distinct states found +ok run-first violates InstanceEndsWithItsRuns 205 distinct states found +ok unchecked violates NoLiveAttemptEnded 724 distinct states found +ok task-scoped violates NoLiveAttemptEnded 356 distinct states found +ok unrechecked violates NoLiveRunFailed 121 distinct states found +ok pid-only violates NoLiveRunFailed 37 distinct states found +ok unseen violates NoLiveRunFailed 46 distinct states found +ok unmarked violates NoLiveRunFailed 144 distinct states found +TLC 1.7.4; configs and output in /tmp/run-orphan-reaping-tlc.XXXXXX +``` + +The distinct-state count of a config that holds is a drift signal. It changes only when the model or the config +changes, so a different count on an unchanged model means TLC did not check what you think. The check runs TLC with +one worker, so a config that breaks a rule always reports the same shortest counterexample. + +## Read a counterexample + +For a broken rule, `tlc.out` holds the shortest path to it, one state per step. Each state names the action that +produced it, such as `State 5: `, and lists every variable after that action. +Read the path from the first state, name the store call each action stands for with the table, and note which +variables changed. Then write the path as numbered steps in the code's words. For `DeadRunsEnd`, TLC prints +"Temporal properties were violated" and a path that ends in a loop ("Back to state ..."): the dead run stays in flight +on every step of that loop. + +The shortest paths at the commit that last changed this directory: + +- `prefix-resume`: r1 is submitted, gets a worker slot and registers the instance. Its process is killed, the + reconciler finds it gone and fails the run. The instance is still shown running with no run in flight. +- `prefix-episode`: the episode is submitted and its process is killed. Its seen mark goes past the lease, and it stays + `RUNNING` forever because the reconciler queries only `local` runs. +- `run-first`: the path of `prefix-resume`. The instance is still running right after the run is failed. +- `unchecked`: r2 starts and registers the instance. r1, submitted for the same instance, is killed before it starts. + Once r1's lease lapses, the reconciler finds it gone and ends the instance failed while r2 works. +- `task-scoped`: r1 starts and registers the instance. r4, of another task, is submitted for the same instance and + killed before it starts. Once r4's lease lapses, the reconciler finds it gone, looks only for live runs of r4's task, + and ends the instance failed while r1 works. +- `unrechecked`: the live episode stalls past its lease, and the reconciler lists it as gone. The episode marks its run + seen again, then the reconciler finds no instance yet and fails the run anyway. +- `pid-only`: the live episode shares the reconciler's host name, so its pid looks gone. The reconciler fails it right + after it is submitted, while its lease is fresh. +- `unseen`: the live episode's seen mark goes past the lease because it never marks it, and the reconciler fails it. +- `unmarked`: the earlier version's episode is submitted. Its seen mark goes past the lease because that version never + marks it, and the reconciler, ignoring the missing marker, fails it while it plays. + +## Tell a real bug from a modeling error + +A deadlock or a TLC error is a modeling error. `Settled` covers every correct end state. + +For a broken rule on a config expected to hold, check each step of the path against the code: + +- Each action must be exactly one store call, or a change in a process's life. A call the code makes as two calls must + be two actions. The one exception is named in `WriteInstance`: the re-check of `held()` and the update are one action. +- A guard the model checks must be the guard the code checks, on the same read. + +If the code cannot take one of the steps, the model is wrong: fix the action and cite the code that rules the step out. +If every step maps to the code, the bug is real. Replay the path in a test that drives the real reconciler and stores, +as these do: + +```sh +.venv/bin/python -m pytest tst/unit/runner/local_runner_test.py tst/unit/task/episode/run_test.py \ + -k "dead_processes_run or live_run_resumed or another_tasks_instance or keeps_marking or seen_after_the_reconciler or pid_is_not_visible or already_ended or never_renews or another_process_ended" +``` + +`test_a_dead_processes_run_and_its_instance_both_end_failed` replays `prefix-resume` and `prefix-episode`. +`test_an_instance_a_live_run_resumed_is_ended_only_once_that_run_ends_too` replays `unchecked`. +`test_a_dead_run_submitted_for_another_tasks_instance_leaves_that_instances_live_run_alone` replays `task-scoped`. +`test_a_run_whose_owner_marks_it_seen_after_the_reconciler_listed_it_is_left_running` replays `unrechecked`. +`test_a_run_on_this_host_name_whose_pid_is_not_visible_but_seen_lately_is_left_running` replays `pid-only`. +`test_a_live_episode_keeps_marking_its_run_seen` guards `unseen`, and checks that an episode writes the `renews` marker. +`test_a_dead_looking_episode_from_a_version_that_never_renews_its_lease_is_left_running` replays `unmarked`. +`test_an_instance_an_episode_from_a_version_that_never_renews_is_in_flight_on_is_left_running` checks the same marker in +`HeldByAnother`. +`test_an_episode_whose_run_another_process_ended_warns_once_and_plays_on` checks what an episode does once it was +reaped anyway, which the model leaves out. + +Do not weaken a rule, narrow a config, or drop an action to make a run pass. + +## Update the model for an intended change + +1. Map each hunk of the diff to its action with the table. +2. Edit the action so it does what the new code does, one store call per action, and cite the code in its comment. +3. If the change adds or moves a guard, add a constant that removes it, a config with it off, and a line in `check.sh` + that names the rule it must break. +4. Run `check.sh`. Each line must print `ok`. Update the expected output and the shortest paths in this guide. + +## Live runs the reconciler can still fail + +The reconciler cannot undo a reap. `mark_terminal` never moves a `FAILED` run, and the last step's completion never +marks a `failed` instance `completed`. The reconciler has no sign of life for a process on another host, or in another +pid namespace, other than the run's `seen` time. So it fails a live run in two cases, and the `renews` marker fixes +neither: + +- The process stops renewing for longer than `OWNER_LEASE_SECONDS` (120 seconds) while it lives, for example because + its event loop is blocked. The model's `Stalls` covers this, and `Live` counts such a process as gone, so + `NoLiveRunFailed` holds only by that definition. +- The reconciler's clock runs ahead of the owner's by close to the lease. The model leaves clock skew out. + +When it happens to an episode, its next renewal matches no in-flight run. The episode logs a warning that names the run, +stops renewing, and plays on, so training keeps its episode. Its run stays `FAILED` and its instance `failed`. + +## What the model does not cover + +- A lease renewed in the one round trip between the write's re-check of `held()` and its update. The reconciler then + fails a run whose process had been past its lease a moment before. The run index and the instance are separate + documents, so the compare-and-swap on the instance cannot see the renewal. +- A process that stalls past its lease before it registers its instance, is reaped, registers the instance, and then + dies. The instance stays `running` with no run in flight. The stall configs leave out `InstanceEndsWithItsRuns` for + this reason. +- The same stall when the process comes back and finishes. Its instance can end `completed` while its run record + says `FAILED`, and nothing reconciles the two. +- Clock skew across hosts. The lease compares the reconciler's clock with the owner's `seen` time. A skew near the lease + makes a live owner look gone, or a dead one look alive for longer. See "Live runs the reconciler can still fail". +- What an episode does after it was reaped anyway: its renewal matching nothing, and its own end writes landing on + nothing. The episode's warning is checked by a unit test. +- Pid namespaces beyond the lease gate. A pid on a shared host name that belongs to another, live process (pid reuse, + or another namespace) makes a dead owner look alive. That run is reaped only once that process exits. +- Runs of a runner other than `local` and `episode`. Their records name no owner, so the reconciler never fails them, + and one in flight on an instance holds it (the reconciler logs that it leaves the dead run in flight). An episode + without the `renews` marker holds an instance the same way. The model gives `r5` an instance of its own. +- `stop()` leaving its runs in flight on shutdown, and a cancel while a run waits for a worker slot. Both leave the + instance alone or end the run themselves. +- A store write that keeps failing. `record_task_failure` gives up after three tries and leaves the instance running + while the run is failed. +- Episodes of an `@local` task record their run in that namespace's local store. The model does not separate stores. +- The attempt epoch beyond "which run registered the instance last", the journal, and usage writes. They only change + the instance's revision, which causes more compare-and-swap retries. +- Bounds: the runs each config lists, one attempt each, at most two runs per instance. `r4` appears only beside + `r1`, never beside a resuming run. diff --git a/tst/formal/run_orphan_reaping/RunOrphanReaping.tla b/tst/formal/run_orphan_reaping/RunOrphanReaping.tla new file mode 100644 index 000000000..8e5f1ab09 --- /dev/null +++ b/tst/formal/run_orphan_reaping/RunOrphanReaping.tla @@ -0,0 +1,321 @@ +---------------------------- MODULE RunOrphanReaping ---------------------------- +(* How a run's record in the run index and its task instance end when the process running + the run dies, and how the reconciler a started LocalRunner runs settles them. + + r1 and r2 are LocalRunner runs of one instance: r2 resumes it, as `submit(instance_id=...)` + does. r3 is an episode, whose instance is its own. r1's process is on the reconciler's host, + which can see its pid. r2's is on another host. r3's is on another host too, unless + SharedHostname: then it reports the reconciler's host name from another pid namespace, so the + reconciler cannot see its pid. r4 is a LocalRunner run of another task submitted with r1's + instance id, on the reconciler's host: it fails once it starts and never plays the instance. + r5 is an episode on another host recorded by an earlier version, which never marks its run seen + and leaves the marker that says it does out of its owner. Its instance is its own. + With Stalls, a live process can stop marking its run seen for longer than the lease, then mark + it again. *) +EXTENDS Naturals + +CONSTANTS + Runs, \* the runs in play: a subset of {"r1", "r2", "r3", "r4", "r5"} + SharedHostname, \* r3's process shares the reconciler's host name, not its pids + Stalls, \* a live process can stall past the lease and come back + ReapedRunners, \* runner types the reconciler queries for orphans + EndsInstance, \* the reconciler ends a reaped run's instance + ChecksOtherRuns, \* ...unless another live run is in flight on it + ChecksEveryTask, \* ...whatever task that run names + RechecksOwnRun, \* ...or the run itself turns out to be live on a fresh read + InstanceFirst, \* ...and ends the instance before the run record + LeaseGatesPid, \* a pid that looks gone counts only once the lease has lapsed too + EpisodeSeen, \* a live episode keeps marking its run seen + ChecksMarker \* the reconciler fails an episode only when its owner carries the marker + +Runner == [r \in Runs |-> IF r \in {"r3", "r5"} THEN "episode" ELSE "local"] +InstanceOf == [r \in Runs |-> CASE r = "r3" -> "i2" [] r = "r5" -> "i3" [] OTHER -> "i1"] +TaskOf == [r \in Runs |-> IF r = "r4" THEN "t2" ELSE "t1"] +OnOtherHost == [r \in Runs |-> r \in {"r2", "r5"} \/ (r = "r3" /\ ~SharedHostname)] +Renews == [r \in Runs |-> r # "r5"] +PidVisible == [r \in Runs |-> r \in {"r1", "r4"}] +Instances == {InstanceOf[r] : r \in Runs} + +InFlight == {"QUEUED", "RUNNING"} +Terminal == {"COMPLETED", "FAILED", "CANCELED"} +RunStatusOf == [completed |-> "COMPLETED", failed |-> "FAILED", cancelled |-> "CANCELED"] + +VARIABLES + alive, \* the run's process is alive + stalled, \* the live process has stopped marking its run seen, for now + stale, \* the run's `seen` mark is older than the lease + owner, \* where the run's process is in the run + outcome, \* how the process ends the run, once chosen + run, \* the run record's status ("absent" before it is inserted) + instance, \* the task instance's status ("none" before it is registered) + attempt, \* the run whose attempt the instance is (its attempt epoch) + rev, \* the instance's compare-and-swap counter + reaper, \* where the reconciler is + target, \* the run it is reaping + seenRev, \* the instance rev its compare-and-swap read + seenStatus, \* the instance status its compare-and-swap read + lookedLive, \* the target's process was live when the reconciler last looked at it + endedLive, \* the reconciler ended an instance whose attempt a live run is making + reapedLive \* the reconciler failed a run whose process was live when it last looked + +vars == <> + +Init == + /\ alive = [r \in Runs |-> TRUE] + /\ stalled = [r \in Runs |-> FALSE] + /\ stale = [r \in Runs |-> FALSE] + /\ owner = [r \in Runs |-> "unsubmitted"] + /\ outcome = [r \in Runs |-> "none"] + /\ run = [r \in Runs |-> "absent"] + /\ instance = [i \in Instances |-> "none"] + /\ attempt = [i \in Instances |-> "none"] + /\ rev = [i \in Instances |-> 0] + /\ reaper = "idle" + /\ target = "none" + /\ seenRev = 0 + /\ seenStatus = "none" + /\ lookedLive = FALSE + /\ endedLive = FALSE + /\ reapedLive = FALSE + +ReaperVars == <> +LeaseVars == <> + +\* A run the reconciler must leave alone: its process is alive, and it either keeps marking the +\* run seen or runs where the reconciler can see its pid. A process that stalls past the lease +\* where its pid can't be seen counts as gone, by design of the lease. +Live(r) == alive[r] /\ (~stalled[r] \/ PidVisible[r]) + +(* ---- the process running a run ---- *) + +\* runner/local_runner.py:178 `insert_run` (QUEUED); task/episode/run.py:427 `_record_run` (RUNNING) +Submit(r) == + /\ owner[r] = "unsubmitted" + /\ run' = [run EXCEPT ![r] = IF Runner[r] = "local" THEN "QUEUED" ELSE "RUNNING"] + /\ owner' = [owner EXCEPT ![r] = IF Runner[r] = "local" THEN "queued" ELSE "started"] + /\ UNCHANGED <> + /\ UNCHANGED ReaperVars + +\* runner/local_runner.py:215 `set_running` +Start(r) == + /\ alive[r] /\ owner[r] = "queued" + /\ run' = [run EXCEPT ![r] = IF @ = "QUEUED" THEN "RUNNING" ELSE @] + /\ owner' = [owner EXCEPT ![r] = "started"] + /\ UNCHANGED <> + /\ UNCHANGED ReaperVars + +\* runner/local_runner.py:220, 224 then 259: a run of the wrong version, or of a missing task, +\* fails before Task.run registers the instance +FailBeforeRegister(r) == + /\ alive[r] /\ owner[r] = "started" /\ Runner[r] = "local" + /\ run' = [run EXCEPT ![r] = IF @ \in InFlight THEN "FAILED" ELSE @] + /\ owner' = [owner EXCEPT ![r] = "done"] + /\ UNCHANGED <> + /\ UNCHANGED ReaperVars + +\* task/task.py:599 `register_task_instance`: task/store.py:459 inserts the instance, or +\* task/store.py:466-473 re-registers it and bumps its attempt epoch +Register(r) == + /\ alive[r] /\ owner[r] = "started" /\ TaskOf[r] = "t1" + /\ instance' = [instance EXCEPT ![InstanceOf[r]] = "running"] + /\ attempt' = [attempt EXCEPT ![InstanceOf[r]] = r] + /\ rev' = [rev EXCEPT ![InstanceOf[r]] = @ + 1] + /\ owner' = [owner EXCEPT ![r] = "working"] + /\ UNCHANGED <> + /\ UNCHANGED ReaperVars + +\* task/store.py:843-844 the last step's completion; task/store.py:874 `record_task_failure_sync`; +\* task/store.py:899 `record_task_cancelled_sync`; each fenced by the attempt epoch (`_owns`, task/store.py:356) +EndInstance(r) == + /\ alive[r] /\ owner[r] = "working" + /\ \E o \in {"completed", "failed", "cancelled"}: + LET i == InstanceOf[r] + lands == /\ attempt[i] = r + /\ instance[i] # "completed" + /\ (o = "completed" => instance[i] \notin {"failed", "cancelled"}) + IN /\ outcome' = [outcome EXCEPT ![r] = o] + /\ instance' = IF lands THEN [instance EXCEPT ![i] = o] ELSE instance + /\ rev' = IF lands THEN [rev EXCEPT ![i] = @ + 1] ELSE rev + /\ owner' = [owner EXCEPT ![r] = "ending"] + /\ UNCHANGED <> + /\ UNCHANGED ReaperVars + +\* runner/local_runner.py:287 `_finish`, runner/local_runner.py:255 (cancelled); +\* task/episode/run.py:435 `_record_ended` +EndRun(r) == + /\ alive[r] /\ owner[r] = "ending" + /\ run' = [run EXCEPT ![r] = IF @ \in InFlight THEN RunStatusOf[outcome[r]] ELSE @] + /\ owner' = [owner EXCEPT ![r] = "done"] + /\ UNCHANGED <> + /\ UNCHANGED ReaperVars + +\* the process is killed at any point after it submitted the run +Crash(r) == + /\ alive[r] /\ owner[r] \notin {"unsubmitted", "done"} + /\ alive' = [alive EXCEPT ![r] = FALSE] + /\ UNCHANGED <> + /\ UNCHANGED ReaperVars + +\* A live LocalRunner marks its runs seen (runner/local_runner.py:84-85), and a live episode its +\* own (task/episode/run.py:268, 302), every OWNER_SEEN_SECONDS (runner/store.py:116 `see`, a +\* no-op on a terminal run). A process that dies, never marks, or stalls stops renewing it, and +\* its lease (runner/store.py:25) runs out. +Heartbeats(r) == Runner[r] = "local" \/ (EpisodeSeen /\ Renews[r]) + +Stall(r) == + /\ Stalls /\ alive[r] /\ ~stalled[r] /\ Heartbeats(r) /\ run[r] \in InFlight + /\ stalled' = [stalled EXCEPT ![r] = TRUE] + /\ UNCHANGED <> + /\ UNCHANGED ReaperVars + +Renew(r) == + /\ alive[r] /\ stalled[r] /\ run[r] \in InFlight + /\ stalled' = [stalled EXCEPT ![r] = FALSE] + /\ stale' = [stale EXCEPT ![r] = FALSE] + /\ UNCHANGED <> + /\ UNCHANGED ReaperVars + +LeaseRunsOut(r) == + /\ run[r] \in InFlight /\ ~stale[r] + /\ (~alive[r] \/ ~Heartbeats(r) \/ stalled[r]) + /\ stale' = [stale EXCEPT ![r] = TRUE] + /\ UNCHANGED <> + /\ UNCHANGED ReaperVars + +(* ---- the reconciler ---- *) + +\* runner/local_runner.py:339-358 `_owner_alive`, negated: a fresh lease keeps an owner alive, and +\* on this host so does a pid it can see +PidGone(r) == OnOtherHost[r] \/ ~(alive[r] /\ PidVisible[r]) +OwnerGone(r) == + IF LeaseGatesPid THEN stale[r] /\ PidGone(r) + ELSE IF OnOtherHost[r] THEN stale[r] ELSE PidGone(r) + +\* runner/local_runner.py:330 `_reaped`: the runner types the reconciler queries, and of +\* episodes only those whose owner carries the marker (task/episode/run.py:430) +Reaped(r) == + /\ Runner[r] \in ReapedRunners + /\ (Runner[r] # "episode" \/ Renews[r] \/ ~ChecksMarker) + +\* runner/local_runner.py:313-327 `_may_still_run`, on a fresh read of the run index +\* (runner/store.py:96 `in_flight_runs`): the run has ended or its owner is alive after all, or +\* another run in flight on the instance may still be running +HeldByAnother(r) == + \E o \in Runs: /\ o # r /\ InstanceOf[o] = InstanceOf[r] /\ run[o] \in InFlight + /\ (~OwnerGone(o) \/ ~Reaped(o)) + /\ (ChecksEveryTask \/ TaskOf[o] = TaskOf[r]) +Held(r) == + \/ RechecksOwnRun /\ (run[r] \notin InFlight \/ ~OwnerGone(r)) + \/ ChecksOtherRuns /\ HeldByAnother(r) + +\* runner/local_runner.py:96-97 `active_runs` per reaped runner type, then `_owner_alive` +Pick(r) == + /\ reaper = "idle" + /\ run[r] \in InFlight /\ Reaped(r) /\ OwnerGone(r) + /\ target' = r + /\ reaper' = IF EndsInstance /\ InstanceFirst THEN "read" ELSE "mark" + /\ lookedLive' = Live(r) + /\ UNCHANGED <> + /\ UNCHANGED <> + +\* runner/local_runner.py:99 `fail_unless_held_sync`: task/store.py:952 asks `held()` first, then +\* store/document_store/document_store.py:605 `compare_and_swap` reads the instance. With no +\* instance there is nothing to end, and that first answer decides. +ReadInstance == + /\ reaper = "read" + /\ LET i == InstanceOf[target] IN + /\ seenRev' = rev[i] + /\ seenStatus' = instance[i] + /\ IF instance[i] = "none" + THEN /\ reaper' = IF Held(target) \/ ~InstanceFirst THEN "idle" ELSE "mark" + /\ lookedLive' = Live(target) + ELSE /\ reaper' = "write" + /\ UNCHANGED lookedLive + /\ UNCHANGED <> + /\ UNCHANGED <> + +\* task/store.py:956-957 the mutate callback asks `held()` again and declines on a held or +\* ended instance, writing nothing (document_store.py:609-610); otherwise document_store.py:612 +\* updates only at the rev it read, and rereads when it lost the race. runner/local_runner.py:102 +\* leaves a held run in flight for a later pass. The re-check and the update are one action here: +\* a lease renewed in the round trip between them is left out (see AGENTS.md). +WriteInstance == + /\ reaper = "write" + /\ LET i == InstanceOf[target] + next == IF InstanceFirst THEN "mark" ELSE "idle" + IN IF Held(target) + THEN /\ reaper' = "idle" + /\ UNCHANGED <> + ELSE IF seenStatus # "running" + THEN /\ reaper' = next + /\ lookedLive' = Live(target) + /\ UNCHANGED <> + ELSE IF rev[i] # seenRev + THEN /\ reaper' = "read" + /\ UNCHANGED <> + ELSE /\ instance' = [instance EXCEPT ![i] = "failed"] + /\ rev' = [rev EXCEPT ![i] = @ + 1] + /\ endedLive' = (endedLive \/ (attempt[i] # "none" /\ run[attempt[i]] \in InFlight + /\ Live(attempt[i]))) + /\ lookedLive' = Live(target) + /\ reaper' = next + /\ UNCHANGED <> + /\ UNCHANGED <> + +\* runner/local_runner.py:104 `mark_terminal(FAILED)`, a no-op on a run already terminal +\* (runner/store.py:126) +MarkFailed == + /\ reaper = "mark" + /\ run' = [run EXCEPT ![target] = IF @ \in InFlight THEN "FAILED" ELSE @] + /\ reapedLive' = (reapedLive \/ (run[target] \in InFlight /\ lookedLive)) + /\ reaper' = IF EndsInstance /\ ~InstanceFirst THEN "read" ELSE "idle" + /\ UNCHANGED <> + /\ UNCHANGED <> + +\* the reconciling process dies mid-pass; the next `start()` reconciles again +ReaperRestarts == + /\ reaper # "idle" + /\ reaper' = "idle" + /\ UNCHANGED <> + /\ UNCHANGED <> + +Settled == + /\ reaper = "idle" + /\ \A r \in Runs: owner[r] = "done" \/ ~alive[r] + /\ UNCHANGED vars + +OwnerStep(r) == Submit(r) \/ Start(r) \/ FailBeforeRegister(r) \/ Register(r) \/ EndInstance(r) \/ EndRun(r) + +Next == + \/ \E r \in Runs: OwnerStep(r) \/ Crash(r) \/ Stall(r) \/ Renew(r) \/ LeaseRunsOut(r) \/ Pick(r) + \/ ReadInstance \/ WriteInstance \/ MarkFailed \/ ReaperRestarts \/ Settled + +\* A live process eventually finishes its run or dies; a lease eventually runs out; the +\* reconciler, every OWNER_SEEN_SECONDS, eventually takes each step it can, and a pass that keeps +\* getting cut short by restarts eventually finishes. +Fairness == + /\ \A r \in Runs: WF_vars(OwnerStep(r)) /\ WF_vars(LeaseRunsOut(r)) /\ WF_vars(Pick(r)) + /\ SF_vars(ReadInstance) /\ SF_vars(WriteInstance) /\ SF_vars(MarkFailed) + +Spec == Init /\ [][Next]_vars /\ Fairness + +(* ---- rules ---- *) + +\* An instance shown running always has a run in flight: once its runs have all ended, the +\* instance has ended too. +InstanceEndsWithItsRuns == + \A i \in Instances: instance[i] = "running" => + \E r \in Runs: InstanceOf[r] = i /\ run[r] \in InFlight + +\* The reconciler never ends an instance while a live run is making its attempt on it. +NoLiveAttemptEnded == ~endedLive + +\* The reconciler never fails a run whose process was live when it last looked at the run. +NoLiveRunFailed == ~reapedLive + +\* A run whose process died is eventually terminal, except an episode recorded by an earlier +\* version, which is left to its owner. +DeadRunsEnd == \A r \in Runs: Renews[r] => ((run[r] \in InFlight /\ ~alive[r]) ~> run[r] \in Terminal) + +============================================================================= diff --git a/tst/formal/run_orphan_reaping/check.sh b/tst/formal/run_orphan_reaping/check.sh new file mode 100755 index 000000000..f66544e33 --- /dev/null +++ b/tst/formal/run_orphan_reaping/check.sh @@ -0,0 +1,98 @@ +#!/usr/bin/env bash +# Model-check RunOrphanReaping.tla with TLC and compare every config with its recorded outcome. +# +# tst/formal/run_orphan_reaping/check.sh every config +# tst/formal/run_orphan_reaping/check.sh one CFG one run, no expectation +# +# Exits nonzero when any run differs from its expectation, or TLC errors (a deadlock is a modeling error). +# Needs Java 11+ and, on the first run, the network to fetch the pinned TLC jar. Set TLA2TOOLS to use a jar you +# already have (its sha256 must match) and JAVA to pick the java binary. +set -euo pipefail + +here=$(cd "$(dirname "$0")" && pwd) +TLA_VERSION=1.7.4 +TLA_SHA256=936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88 +TLA_URL=https://github.com/tlaplus/tlaplus/releases/download/v$TLA_VERSION/tla2tools.jar +cache=${AGENTENV_TLA_CACHE:-${XDG_CACHE_HOME:-$HOME/.cache}/agentenv-formal} +[[ $cache == /* ]] || cache=$PWD/$cache +jar=${TLA2TOOLS:-$cache/tla2tools-$TLA_VERSION.jar} +[[ $jar == /* ]] || jar=$PWD/$jar +java=${JAVA:-java} +out=${OUT:-$(mktemp -d "${TMPDIR:-/tmp}/run-orphan-reaping-tlc.XXXXXX")} + +sha256() { if command -v sha256sum >/dev/null; then sha256sum "$1"; else shasum -a 256 "$1"; fi | cut -d' ' -f1; } + +die() { echo "check.sh: $*" >&2; exit 2; } + +fetch_tlc() { + if [[ -f $jar && $(sha256 "$jar") == "$TLA_SHA256" ]]; then return; fi + [[ -z ${TLA2TOOLS:-} ]] || die "TLA2TOOLS=$TLA2TOOLS is not tla2tools.jar v$TLA_VERSION (sha256 $TLA_SHA256)" + mkdir -p "$cache" + local part got; part=$(mktemp "$cache/tla2tools.XXXXXX") + curl -fsSL -o "$part" "$TLA_URL" || { rm -f "$part"; exit 2; } + got=$(sha256 "$part") + if [[ $got != "$TLA_SHA256" ]]; then + rm -f "$part" + echo "tla2tools.jar sha256 $got, expected $TLA_SHA256" >&2 + exit 2 + fi + mv -f "$part" "$jar" +} + +run() { + local name=$1 cfg=$2 dir=$out/$1 + mkdir -p "$dir" + cp "$here/RunOrphanReaping.tla" "$here/$cfg" "$dir/" + (cd "$dir" && "$java" -XX:+UseParallelGC -cp "$jar" tlc2.TLC -workers 1 -metadir meta \ + -config "$cfg" RunOrphanReaping.tla > tlc.out 2>&1) || true + local states violated outcome + states=$(grep -Eo '[0-9,]+ distinct states found' "$dir/tlc.out" | tail -1 || true) + violated=$(grep -Eo 'Invariant [A-Za-z]+ is violated' "$dir/tlc.out" | head -1 | awk '{print $2}' || true) + if [[ -n $violated ]]; then outcome="violates $violated" + elif grep -q 'Temporal properties were violated' "$dir/tlc.out"; then outcome="violates DeadRunsEnd" + elif grep -q 'Model checking completed. No error has been found.' "$dir/tlc.out"; then outcome=holds + else outcome=error; fi + printf '%s\t%s\n' "$outcome" "${states:-no states}" +} + +failed=0 +expect() { + local cfg=$1 want=$2 name=${1%.cfg} outcome states mark=ok + IFS=$'\t' read -r outcome states < <(run "$name" "$cfg") + if [[ $outcome != "$want" ]]; then mark=UNEXPECTED; failed=1; fi + printf '%-11s %-16s %-34s %s\n' "$mark" "$name" "$outcome" "$states" + if [[ $mark != ok ]]; then echo " expected: $want; TLC output: $out/$name/tlc.out"; fi +} + +command -v "$java" >/dev/null || die "$java not found; TLC needs Java 11 or later" +fetch_tlc +case ${1:-all} in + all) + expect resume.cfg holds + expect episode.cfg holds + expect shared-host.cfg holds + expect stall.cfg holds + expect stall-episode.cfg holds + expect other-task.cfg holds + expect old-episode.cfg holds + expect prefix-resume.cfg "violates InstanceEndsWithItsRuns" + expect prefix-episode.cfg "violates DeadRunsEnd" + expect run-first.cfg "violates InstanceEndsWithItsRuns" + expect unchecked.cfg "violates NoLiveAttemptEnded" + expect task-scoped.cfg "violates NoLiveAttemptEnded" + expect unrechecked.cfg "violates NoLiveRunFailed" + expect pid-only.cfg "violates NoLiveRunFailed" + expect unseen.cfg "violates NoLiveRunFailed" + expect unmarked.cfg "violates NoLiveRunFailed" + ;; + one) + cfg=${2:?config file} + IFS=$'\t' read -r outcome states < <(run one "$cfg") + echo "$outcome, $states; TLC output: $out/one/tlc.out" + if [[ $outcome == error ]]; then exit 2; fi + exit 0 + ;; + *) echo "usage: $0 [all|one CFG]" >&2; exit 2 ;; +esac +echo "TLC $TLA_VERSION; configs and output in $out" +exit $failed diff --git a/tst/formal/run_orphan_reaping/episode.cfg b/tst/formal/run_orphan_reaping/episode.cfg new file mode 100644 index 000000000..c6bbfb8da --- /dev/null +++ b/tst/formal/run_orphan_reaping/episode.cfg @@ -0,0 +1,20 @@ +SPECIFICATION Spec +CONSTANTS + Runs = {"r1", "r3"} + SharedHostname = FALSE + Stalls = FALSE + ReapedRunners = {"local", "episode"} + EndsInstance = TRUE + ChecksOtherRuns = TRUE + ChecksEveryTask = TRUE + RechecksOwnRun = TRUE + InstanceFirst = TRUE + LeaseGatesPid = TRUE + EpisodeSeen = TRUE + ChecksMarker = TRUE +INVARIANTS + InstanceEndsWithItsRuns + NoLiveAttemptEnded + NoLiveRunFailed +PROPERTIES + DeadRunsEnd diff --git a/tst/formal/run_orphan_reaping/old-episode.cfg b/tst/formal/run_orphan_reaping/old-episode.cfg new file mode 100644 index 000000000..5e62d9ab6 --- /dev/null +++ b/tst/formal/run_orphan_reaping/old-episode.cfg @@ -0,0 +1,20 @@ +SPECIFICATION Spec +CONSTANTS + Runs = {"r3", "r5"} + SharedHostname = FALSE + Stalls = FALSE + ReapedRunners = {"local", "episode"} + EndsInstance = TRUE + ChecksOtherRuns = TRUE + ChecksEveryTask = TRUE + RechecksOwnRun = TRUE + InstanceFirst = TRUE + LeaseGatesPid = TRUE + EpisodeSeen = TRUE + ChecksMarker = TRUE +INVARIANTS + InstanceEndsWithItsRuns + NoLiveAttemptEnded + NoLiveRunFailed +PROPERTIES + DeadRunsEnd diff --git a/tst/formal/run_orphan_reaping/other-task.cfg b/tst/formal/run_orphan_reaping/other-task.cfg new file mode 100644 index 000000000..a1a3b1671 --- /dev/null +++ b/tst/formal/run_orphan_reaping/other-task.cfg @@ -0,0 +1,20 @@ +SPECIFICATION Spec +CONSTANTS + Runs = {"r1", "r4"} + SharedHostname = FALSE + Stalls = FALSE + ReapedRunners = {"local", "episode"} + EndsInstance = TRUE + ChecksOtherRuns = TRUE + ChecksEveryTask = TRUE + RechecksOwnRun = TRUE + InstanceFirst = TRUE + LeaseGatesPid = TRUE + EpisodeSeen = TRUE + ChecksMarker = TRUE +INVARIANTS + InstanceEndsWithItsRuns + NoLiveAttemptEnded + NoLiveRunFailed +PROPERTIES + DeadRunsEnd diff --git a/tst/formal/run_orphan_reaping/pid-only.cfg b/tst/formal/run_orphan_reaping/pid-only.cfg new file mode 100644 index 000000000..3e6f93c57 --- /dev/null +++ b/tst/formal/run_orphan_reaping/pid-only.cfg @@ -0,0 +1,20 @@ +SPECIFICATION Spec +CONSTANTS + Runs = {"r3"} + SharedHostname = TRUE + Stalls = FALSE + ReapedRunners = {"local", "episode"} + EndsInstance = TRUE + ChecksOtherRuns = TRUE + ChecksEveryTask = TRUE + RechecksOwnRun = TRUE + InstanceFirst = TRUE + LeaseGatesPid = FALSE + EpisodeSeen = TRUE + ChecksMarker = TRUE +INVARIANTS + InstanceEndsWithItsRuns + NoLiveAttemptEnded + NoLiveRunFailed +PROPERTIES + DeadRunsEnd diff --git a/tst/formal/run_orphan_reaping/prefix-episode.cfg b/tst/formal/run_orphan_reaping/prefix-episode.cfg new file mode 100644 index 000000000..c7f810165 --- /dev/null +++ b/tst/formal/run_orphan_reaping/prefix-episode.cfg @@ -0,0 +1,20 @@ +SPECIFICATION Spec +CONSTANTS + Runs = {"r3"} + SharedHostname = FALSE + Stalls = FALSE + ReapedRunners = {"local"} + EndsInstance = FALSE + ChecksOtherRuns = FALSE + ChecksEveryTask = TRUE + RechecksOwnRun = FALSE + InstanceFirst = TRUE + LeaseGatesPid = FALSE + EpisodeSeen = FALSE + ChecksMarker = FALSE +INVARIANTS + InstanceEndsWithItsRuns + NoLiveAttemptEnded + NoLiveRunFailed +PROPERTIES + DeadRunsEnd diff --git a/tst/formal/run_orphan_reaping/prefix-resume.cfg b/tst/formal/run_orphan_reaping/prefix-resume.cfg new file mode 100644 index 000000000..df2f35b52 --- /dev/null +++ b/tst/formal/run_orphan_reaping/prefix-resume.cfg @@ -0,0 +1,20 @@ +SPECIFICATION Spec +CONSTANTS + Runs = {"r1", "r2"} + SharedHostname = FALSE + Stalls = FALSE + ReapedRunners = {"local"} + EndsInstance = FALSE + ChecksOtherRuns = FALSE + ChecksEveryTask = TRUE + RechecksOwnRun = FALSE + InstanceFirst = TRUE + LeaseGatesPid = FALSE + EpisodeSeen = FALSE + ChecksMarker = FALSE +INVARIANTS + InstanceEndsWithItsRuns + NoLiveAttemptEnded + NoLiveRunFailed +PROPERTIES + DeadRunsEnd diff --git a/tst/formal/run_orphan_reaping/resume.cfg b/tst/formal/run_orphan_reaping/resume.cfg new file mode 100644 index 000000000..fee426853 --- /dev/null +++ b/tst/formal/run_orphan_reaping/resume.cfg @@ -0,0 +1,20 @@ +SPECIFICATION Spec +CONSTANTS + Runs = {"r1", "r2"} + SharedHostname = FALSE + Stalls = FALSE + ReapedRunners = {"local", "episode"} + EndsInstance = TRUE + ChecksOtherRuns = TRUE + ChecksEveryTask = TRUE + RechecksOwnRun = TRUE + InstanceFirst = TRUE + LeaseGatesPid = TRUE + EpisodeSeen = TRUE + ChecksMarker = TRUE +INVARIANTS + InstanceEndsWithItsRuns + NoLiveAttemptEnded + NoLiveRunFailed +PROPERTIES + DeadRunsEnd diff --git a/tst/formal/run_orphan_reaping/run-first.cfg b/tst/formal/run_orphan_reaping/run-first.cfg new file mode 100644 index 000000000..dbfa9f53d --- /dev/null +++ b/tst/formal/run_orphan_reaping/run-first.cfg @@ -0,0 +1,20 @@ +SPECIFICATION Spec +CONSTANTS + Runs = {"r1", "r2"} + SharedHostname = FALSE + Stalls = FALSE + ReapedRunners = {"local", "episode"} + EndsInstance = TRUE + ChecksOtherRuns = TRUE + ChecksEveryTask = TRUE + RechecksOwnRun = TRUE + InstanceFirst = FALSE + LeaseGatesPid = TRUE + EpisodeSeen = TRUE + ChecksMarker = TRUE +INVARIANTS + InstanceEndsWithItsRuns + NoLiveAttemptEnded + NoLiveRunFailed +PROPERTIES + DeadRunsEnd diff --git a/tst/formal/run_orphan_reaping/shared-host.cfg b/tst/formal/run_orphan_reaping/shared-host.cfg new file mode 100644 index 000000000..15a16c2a0 --- /dev/null +++ b/tst/formal/run_orphan_reaping/shared-host.cfg @@ -0,0 +1,20 @@ +SPECIFICATION Spec +CONSTANTS + Runs = {"r1", "r3"} + SharedHostname = TRUE + Stalls = FALSE + ReapedRunners = {"local", "episode"} + EndsInstance = TRUE + ChecksOtherRuns = TRUE + ChecksEveryTask = TRUE + RechecksOwnRun = TRUE + InstanceFirst = TRUE + LeaseGatesPid = TRUE + EpisodeSeen = TRUE + ChecksMarker = TRUE +INVARIANTS + InstanceEndsWithItsRuns + NoLiveAttemptEnded + NoLiveRunFailed +PROPERTIES + DeadRunsEnd diff --git a/tst/formal/run_orphan_reaping/stall-episode.cfg b/tst/formal/run_orphan_reaping/stall-episode.cfg new file mode 100644 index 000000000..a68230d98 --- /dev/null +++ b/tst/formal/run_orphan_reaping/stall-episode.cfg @@ -0,0 +1,19 @@ +SPECIFICATION Spec +CONSTANTS + Runs = {"r3"} + SharedHostname = FALSE + Stalls = TRUE + ReapedRunners = {"local", "episode"} + EndsInstance = TRUE + ChecksOtherRuns = TRUE + ChecksEveryTask = TRUE + RechecksOwnRun = TRUE + InstanceFirst = TRUE + LeaseGatesPid = TRUE + EpisodeSeen = TRUE + ChecksMarker = TRUE +INVARIANTS + NoLiveAttemptEnded + NoLiveRunFailed +PROPERTIES + DeadRunsEnd diff --git a/tst/formal/run_orphan_reaping/stall.cfg b/tst/formal/run_orphan_reaping/stall.cfg new file mode 100644 index 000000000..22d6f75af --- /dev/null +++ b/tst/formal/run_orphan_reaping/stall.cfg @@ -0,0 +1,19 @@ +SPECIFICATION Spec +CONSTANTS + Runs = {"r1", "r2"} + SharedHostname = FALSE + Stalls = TRUE + ReapedRunners = {"local", "episode"} + EndsInstance = TRUE + ChecksOtherRuns = TRUE + ChecksEveryTask = TRUE + RechecksOwnRun = TRUE + InstanceFirst = TRUE + LeaseGatesPid = TRUE + EpisodeSeen = TRUE + ChecksMarker = TRUE +INVARIANTS + NoLiveAttemptEnded + NoLiveRunFailed +PROPERTIES + DeadRunsEnd diff --git a/tst/formal/run_orphan_reaping/task-scoped.cfg b/tst/formal/run_orphan_reaping/task-scoped.cfg new file mode 100644 index 000000000..325feb39c --- /dev/null +++ b/tst/formal/run_orphan_reaping/task-scoped.cfg @@ -0,0 +1,20 @@ +SPECIFICATION Spec +CONSTANTS + Runs = {"r1", "r4"} + SharedHostname = FALSE + Stalls = FALSE + ReapedRunners = {"local", "episode"} + EndsInstance = TRUE + ChecksOtherRuns = TRUE + ChecksEveryTask = FALSE + RechecksOwnRun = TRUE + InstanceFirst = TRUE + LeaseGatesPid = TRUE + EpisodeSeen = TRUE + ChecksMarker = TRUE +INVARIANTS + InstanceEndsWithItsRuns + NoLiveAttemptEnded + NoLiveRunFailed +PROPERTIES + DeadRunsEnd diff --git a/tst/formal/run_orphan_reaping/unchecked.cfg b/tst/formal/run_orphan_reaping/unchecked.cfg new file mode 100644 index 000000000..878f5ac41 --- /dev/null +++ b/tst/formal/run_orphan_reaping/unchecked.cfg @@ -0,0 +1,20 @@ +SPECIFICATION Spec +CONSTANTS + Runs = {"r1", "r2"} + SharedHostname = FALSE + Stalls = FALSE + ReapedRunners = {"local", "episode"} + EndsInstance = TRUE + ChecksOtherRuns = FALSE + ChecksEveryTask = TRUE + RechecksOwnRun = TRUE + InstanceFirst = TRUE + LeaseGatesPid = TRUE + EpisodeSeen = TRUE + ChecksMarker = TRUE +INVARIANTS + InstanceEndsWithItsRuns + NoLiveAttemptEnded + NoLiveRunFailed +PROPERTIES + DeadRunsEnd diff --git a/tst/formal/run_orphan_reaping/unmarked.cfg b/tst/formal/run_orphan_reaping/unmarked.cfg new file mode 100644 index 000000000..d2879cf2d --- /dev/null +++ b/tst/formal/run_orphan_reaping/unmarked.cfg @@ -0,0 +1,20 @@ +SPECIFICATION Spec +CONSTANTS + Runs = {"r3", "r5"} + SharedHostname = FALSE + Stalls = FALSE + ReapedRunners = {"local", "episode"} + EndsInstance = TRUE + ChecksOtherRuns = TRUE + ChecksEveryTask = TRUE + RechecksOwnRun = TRUE + InstanceFirst = TRUE + LeaseGatesPid = TRUE + EpisodeSeen = TRUE + ChecksMarker = FALSE +INVARIANTS + InstanceEndsWithItsRuns + NoLiveAttemptEnded + NoLiveRunFailed +PROPERTIES + DeadRunsEnd diff --git a/tst/formal/run_orphan_reaping/unrechecked.cfg b/tst/formal/run_orphan_reaping/unrechecked.cfg new file mode 100644 index 000000000..1379f93d4 --- /dev/null +++ b/tst/formal/run_orphan_reaping/unrechecked.cfg @@ -0,0 +1,19 @@ +SPECIFICATION Spec +CONSTANTS + Runs = {"r3"} + SharedHostname = FALSE + Stalls = TRUE + ReapedRunners = {"local", "episode"} + EndsInstance = TRUE + ChecksOtherRuns = TRUE + ChecksEveryTask = TRUE + RechecksOwnRun = FALSE + InstanceFirst = TRUE + LeaseGatesPid = TRUE + EpisodeSeen = TRUE + ChecksMarker = TRUE +INVARIANTS + NoLiveAttemptEnded + NoLiveRunFailed +PROPERTIES + DeadRunsEnd diff --git a/tst/formal/run_orphan_reaping/unseen.cfg b/tst/formal/run_orphan_reaping/unseen.cfg new file mode 100644 index 000000000..42293b221 --- /dev/null +++ b/tst/formal/run_orphan_reaping/unseen.cfg @@ -0,0 +1,20 @@ +SPECIFICATION Spec +CONSTANTS + Runs = {"r3"} + SharedHostname = FALSE + Stalls = FALSE + ReapedRunners = {"local", "episode"} + EndsInstance = TRUE + ChecksOtherRuns = TRUE + ChecksEveryTask = TRUE + RechecksOwnRun = TRUE + InstanceFirst = TRUE + LeaseGatesPid = TRUE + EpisodeSeen = FALSE + ChecksMarker = TRUE +INVARIANTS + InstanceEndsWithItsRuns + NoLiveAttemptEnded + NoLiveRunFailed +PROPERTIES + DeadRunsEnd diff --git a/tst/unit/runner/local_runner_test.py b/tst/unit/runner/local_runner_test.py index 1b94fafe7..8bbdcff41 100644 --- a/tst/unit/runner/local_runner_test.py +++ b/tst/unit/runner/local_runner_test.py @@ -5,6 +5,7 @@ """ import asyncio +import os import socket import subprocess import sys @@ -259,6 +260,21 @@ async def work(_kw): assert ran == [1] # the work actually finished +def _exited_pid() -> int: + gone = subprocess.Popen([sys.executable, "-c", "pass"]) + gone.wait() + return gone.pid + + +def _insert_owned_run(docs, run_id, runner, instance_id, pid, host=None, seen=None, task_id="t", renews=None): + record = RunRecord(run_id=run_id, runner=runner, task_id=task_id, task_version=1, instance_id=instance_id, + status=RunStatus.RUNNING) + owner = {"host": host or socket.gethostname(), "pid": pid, **({"seen": seen.isoformat()} if seen else {})} + if renews if renews is not None else runner == run_store.EPISODE_RUNNER: + owner[run_store.OWNER_RENEWS] = True + docs.insert(run_store.RUNS_COLLECTION, {**record.to_dict(), "owner": owner}) + + @pytest.mark.asyncio async def test_start_fails_a_run_left_running_by_a_previous_process(docs): # A run the prior process left mid-flight: a fresh process can't be executing it. @@ -281,11 +297,7 @@ async def on_run(_): await asyncio.sleep(30) _install_task(monkeypatch, _FakeTask(on_run=on_run)) - gone = subprocess.Popen([sys.executable, "-c", "pass"]) - gone.wait() - orphan = RunRecord(run_id="orphan", runner="local", task_id="t", task_version=1, instance_id="i", - status=RunStatus.RUNNING) - docs.insert(run_store.RUNS_COLLECTION, {**orphan.to_dict(), "owner": {"host": socket.gethostname(), "pid": gone.pid}}) + _insert_owned_run(docs, "orphan", "local", "i", _exited_pid()) owner = LocalRunner(workers=1) handle = await owner.submit("t1", 1) await asyncio.wait_for(started.wait(), 5) @@ -694,3 +706,139 @@ async def test_conformance(case, local_stores, monkeypatch): await case(runner) finally: await runner.stop() + + +async def _reconcile_once(): + runner = LocalRunner(workers=1) + await runner.start() + await runner.stop() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("runner", ["local", "episode"]) +async def test_a_dead_processes_run_and_its_instance_both_end_failed(docs, runner): + from agent_env.task.store import find_task_instance, register_task_instance + + register_task_instance("t", 1, 2, instance_id="t-orphaned") + _insert_owned_run(docs, f"{runner}-orphaned", runner, "t-orphaned", _exited_pid()) + + await _reconcile_once() + + assert run_store.get_run(f"{runner}-orphaned").status is RunStatus.FAILED + assert find_task_instance("t-orphaned").status == "failed" + + +@pytest.mark.asyncio +async def test_an_instance_a_live_run_resumed_is_ended_only_once_that_run_ends_too(docs): + from agent_env.task.store import find_task_instance, register_task_instance + + register_task_instance("t", 1, 2, instance_id="t-resumed") + _insert_owned_run(docs, "first", "local", "t-resumed", _exited_pid()) + _insert_owned_run(docs, "resume", "local", "t-resumed", os.getpid()) + + await _reconcile_once() + assert find_task_instance("t-resumed").status == "running" + assert run_store.get_run("resume").status is RunStatus.RUNNING + + run_store.mark_terminal("resume", RunStatus.FAILED, error="ValueError: a run of another version") + await _reconcile_once() + assert run_store.get_run("first").status is RunStatus.FAILED + assert find_task_instance("t-resumed").status == "failed" + + +@pytest.mark.asyncio +async def test_a_dead_run_submitted_for_another_tasks_instance_leaves_that_instances_live_run_alone(docs): + from agent_env.task.store import find_task_instance, register_task_instance + + register_task_instance("t", 1, 2, instance_id="t-claimed") + _insert_owned_run(docs, "live", "local", "t-claimed", os.getpid()) + _insert_owned_run(docs, "wrong-task", "local", "t-claimed", _exited_pid(), task_id="other") + + await _reconcile_once() + + assert find_task_instance("t-claimed").status == "running" + assert run_store.get_run("live").status is RunStatus.RUNNING + + +@pytest.mark.asyncio +@pytest.mark.parametrize("runner", ["local", "episode"]) +async def test_a_run_whose_owner_marks_it_seen_after_the_reconciler_listed_it_is_left_running(docs, monkeypatch, + runner): + from agent_env.task.store import find_task_instance, register_task_instance + + register_task_instance("t", 1, 2, instance_id="t-stalled") + lapsed = datetime.now(timezone.utc) - timedelta(seconds=LocalRunner.OWNER_LEASE_SECONDS + 10) + _insert_owned_run(docs, "stalled", runner, "t-stalled", 1, host="elsewhere", seen=lapsed) + listed = run_store.active_runs + + def active_runs_then_the_owner_marks_seen(runner, *args, **kwargs): + records = listed(runner, *args, **kwargs) + if any(record.run_id == "stalled" for record in records): + run_store.see("stalled") + return records + + monkeypatch.setattr(run_store, "active_runs", active_runs_then_the_owner_marks_seen) + await _reconcile_once() + + assert run_store.get_run("stalled").status is RunStatus.RUNNING + assert find_task_instance("t-stalled").status == "running" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("runner", ["local", "episode"]) +async def test_a_run_on_this_host_name_whose_pid_is_not_visible_but_seen_lately_is_left_running(docs, runner): + from agent_env.task.store import find_task_instance, register_task_instance + + register_task_instance("t", 1, 2, instance_id="t-other-namespace") + _insert_owned_run(docs, "other-namespace", runner, "t-other-namespace", _exited_pid(), + seen=datetime.now(timezone.utc)) + + await _reconcile_once() + + assert run_store.get_run("other-namespace").status is RunStatus.RUNNING + assert find_task_instance("t-other-namespace").status == "running" + + +@pytest.mark.asyncio +async def test_a_dead_processes_run_is_failed_but_its_instance_that_already_ended_is_left_alone(docs): + from agent_env.store import Filter, UpdateSpec + from agent_env.task.store import TASK_INSTANCES_COLLECTION, find_task_instance, register_task_instance + + register_task_instance("t", 1, 2, instance_id="t-completed") + docs.update(TASK_INSTANCES_COLLECTION, Filter.of(instance_id="t-completed"), UpdateSpec(set={"status": "completed"})) + _insert_owned_run(docs, "ended", "local", "t-completed", _exited_pid()) + + await _reconcile_once() + + assert run_store.get_run("ended").status is RunStatus.FAILED + assert find_task_instance("t-completed").status == "completed" + + +@pytest.mark.asyncio +async def test_a_dead_looking_episode_from_a_version_that_never_renews_its_lease_is_left_running(docs): + from agent_env.task.store import find_task_instance, register_task_instance + + register_task_instance("t", 1, 2, instance_id="t-old-episode") + lapsed = datetime.now(timezone.utc) - timedelta(seconds=LocalRunner.OWNER_LEASE_SECONDS + 10) + _insert_owned_run(docs, "old-episode", "episode", "t-old-episode", 1, host="elsewhere", seen=lapsed, + renews=False) + + await _reconcile_once() + + assert run_store.get_run("old-episode").status is RunStatus.RUNNING + assert find_task_instance("t-old-episode").status == "running" + + +@pytest.mark.asyncio +async def test_an_instance_an_episode_from_a_version_that_never_renews_is_in_flight_on_is_left_running(docs): + from agent_env.task.store import find_task_instance, register_task_instance + + register_task_instance("t", 1, 2, instance_id="t-shared") + lapsed = datetime.now(timezone.utc) - timedelta(seconds=LocalRunner.OWNER_LEASE_SECONDS + 10) + _insert_owned_run(docs, "dead", "local", "t-shared", _exited_pid()) + _insert_owned_run(docs, "old-episode", "episode", "t-shared", 1, host="elsewhere", seen=lapsed, renews=False) + + await _reconcile_once() + + assert run_store.get_run("dead").status is RunStatus.RUNNING + assert find_task_instance("t-shared").status == "running" diff --git a/tst/unit/task/episode/run_test.py b/tst/unit/task/episode/run_test.py index 0db1d2923..48ff68f1e 100644 --- a/tst/unit/task/episode/run_test.py +++ b/tst/unit/task/episode/run_test.py @@ -26,6 +26,7 @@ import agent_env.task.episode.run as episode_run from agent_env.runner import store as run_store +from agent_env.runner.runner import RunStatus from agent_env.config import get_config from agent_env.config.runtime import Config from agent_env.env.env import DeployedEnv @@ -473,6 +474,31 @@ async def test_an_episode_is_in_the_run_index_running_then_ended_in_the_group_it assert ended[abandoned].overrides["metadata"].keys() == {"episode"} +@pytest.mark.asyncio +async def test_a_live_episode_keeps_marking_its_run_seen(teardowns, monkeypatch): + monkeypatch.setattr(run_store, "OWNER_SEEN_SECONDS", 0.01) + episode = await _spec(ITEMS, ALICE, TURN, REPLIES).start() + first_seen = run_store.get_run(f"episode-{episode.id}").owner["seen"] + + await _until(lambda: run_store.get_run(f"episode-{episode.id}").owner["seen"] > first_seen) + assert run_store.get_run(f"episode-{episode.id}").owner[run_store.OWNER_RENEWS] is True + + +@pytest.mark.asyncio +async def test_an_episode_whose_run_another_process_ended_warns_once_and_plays_on(teardowns, monkeypatch, caplog): + monkeypatch.setattr(run_store, "OWNER_SEEN_SECONDS", 0.01) + episode = await _spec(ITEMS, ALICE, TURN, REPLIES).start() + run_id = f"episode-{episode.id}" + run_store.mark_terminal(run_id, RunStatus.FAILED, error="the process running it is gone, as after a restart") + + await _until(lambda: any(run_id in record.getMessage() for record in caplog.records)) + await (await episode.next_turn()).end("Added a crate.") + + assert await episode.result() == {"replies": 1.0} + assert [record.levelname for record in caplog.records if run_id in record.getMessage()] == ["WARNING"] + assert run_store.get_run(run_id).status == RunStatus.FAILED + + @pytest.mark.asyncio async def test_an_episode_whose_step_fails_without_failing_the_task_is_recorded_failed_as_a_runner_would(teardowns): spare = {"id": "spare", "type": "episode_test_env", "env_id": "spare", "fail": True, "fail_task_on_error": False}