diff --git a/docs/agent.md b/docs/agent.md index cd24d999b4..04b07b3753 100644 --- a/docs/agent.md +++ b/docs/agent.md @@ -129,3 +129,5 @@ keep = "last" # snapshots kept while the rollout runs: "last", or every k-th pl ``` An owner that outlives its process, such as a training run that stops and resumes, saves its running rollouts instead of waiting for a failure. `verifiers.v1.restore.save_all()` takes a memory snapshot of every running rollout of the process now and returns the trace of each as plain data the owner stores. The trace holds everything a restore needs, on the entry of its checkpoint. A later process continues a rollout from its saved trace with `RunSlot(task, id=..., restore=trace)` (or `Agent.run(task, restore=trace)`): same trace, a new box, and the harness program still running. With `hold=True`, a save can take ownership of a recent periodic snapshot within the configured interval. A resume then repeats work since that capture. Each snapshot transfers to one owner. Fresh captures reset the periodic timer. The owner holds these snapshots; it deletes them with `PrimeBackend.discard` once nothing will restore them. A saved trace continues one rollout. For an episode with more than one agent run, `episode_restore_point(slot, saved)` builds the episode's restore point from what `save_all` returned, and `RunSlot(task, id=..., restore=point)` continues it: the env's program runs again, a finished agent call returns its saved trace, a running one continues from its snapshot, and one that had not started runs fresh. An agentic judge that the save took during its run continues in the box it borrowed, and the run it scores restores that box and scores again. A call asked for another task than at the save starts the episode over. An episode has no restore point when one of its running calls has none, for example an interaction. + +An owner can also pause a running episode (`RunSlot.pause`), for example to shed inference load. A paused episode sends no new model call. Each rollout that takes snapshots also stops its box, and its tool server VMs, at a memory checkpoint, so they hold no compute until the episode resumes. The time paused does not count against the agent's time budget. A save of a paused rollout returns the checkpoint its box stopped at. If the box does not run again, a retry restores from that checkpoint. diff --git a/tests/integration/test_rollout_checkpoint.py b/tests/integration/test_rollout_checkpoint.py index cf87dd31f6..670451a85e 100644 --- a/tests/integration/test_rollout_checkpoint.py +++ b/tests/integration/test_rollout_checkpoint.py @@ -46,13 +46,13 @@ async def taken(monkeypatch) -> AsyncIterator[list[str]]: snapshots: list[str] = [] snapshot_network = PrimeBackend.snapshot_network - async def recording(self, peers, named=None): + async def recording(self, peers, named=None, **kwargs): def record(results): snapshots.extend(result.id for result in results) if named is not None: named(results) - return await snapshot_network(self, peers, record) + return await snapshot_network(self, peers, record, **kwargs) monkeypatch.setattr(PrimeBackend, "snapshot_network", recording) yield snapshots diff --git a/tests/unit/runtimes/test_prime_fork.py b/tests/unit/runtimes/test_prime_fork.py index 9f0fe3b380..2f75b8dcad 100644 --- a/tests/unit/runtimes/test_prime_fork.py +++ b/tests/unit/runtimes/test_prime_fork.py @@ -190,3 +190,76 @@ async def scenario(): assert backend._awake.is_set() asyncio.run(scenario()) + + +@pytest.mark.parametrize("settles", [True, False]) +def test_a_box_kept_stopped_runs_again_only_on_wake(monkeypatch, settles): + """A snapshot that keeps the box stopped leaves calls into it waiting until + `wake`. A box whose stop was not seen to finish runs again at once.""" + calls: list[str] = [] + + class Client: + async def pause(self, sandbox_id): + calls.append("pause") + return SimpleNamespace(checkpoint_id="ck1") + + async def wait_for_pause(self, sandbox_id, timeout_seconds): + if not settles: + raise TimeoutError("still pausing") + calls.append("paused") + + async def resume(self, peers, network_checkpoint): + calls.append("resume") + + async def scenario(): + monkeypatch.setattr(prime, "ensure_prime_auth", lambda: None) + monkeypatch.setattr(PrimeBackend, "_resume", resume) + backend = PrimeBackend(PrimeConfig()) + backend._client = Client() + backend.info.id = "sb1" + if not settles: + with pytest.raises(SandboxError, match="still pausing"): + await backend.snapshot(stay_stopped=True) + assert calls == ["pause", "resume"] and backend._awake.is_set() + return + assert (await backend.snapshot(stay_stopped=True)).id == "ck1" + assert calls == ["pause", "paused"] and not backend._awake.is_set() + await backend.wake() + assert calls == ["pause", "paused", "resume"] and backend._awake.is_set() + + asyncio.run(scenario()) + + +def test_a_cancelled_snapshot_that_keeps_the_box_stopped_wakes_it(monkeypatch): + """The caller of a cancelled snapshot never gets it, so nothing else would wake the + box: the snapshot wakes it before the cancellation goes on.""" + calls: list[str] = [] + stopping = asyncio.Event() + + class Client: + async def pause(self, sandbox_id): + calls.append("pause") + return SimpleNamespace(checkpoint_id="ck1") + + async def wait_for_pause(self, sandbox_id, timeout_seconds): + stopping.set() + await asyncio.sleep(0.05) + calls.append("paused") + + async def resume(self, peers, network_checkpoint): + calls.append("resume") + + async def scenario(): + monkeypatch.setattr(prime, "ensure_prime_auth", lambda: None) + monkeypatch.setattr(PrimeBackend, "_resume", resume) + backend = PrimeBackend(PrimeConfig()) + backend._client = Client() + backend.info.id = "sb1" + task = asyncio.create_task(backend.snapshot(stay_stopped=True)) + await stopping.wait() + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + assert calls == ["pause", "paused", "resume"] and backend._awake.is_set() + + asyncio.run(scenario()) diff --git a/tests/unit/test_checkpoint.py b/tests/unit/test_checkpoint.py index 859ce96dc4..19afde979d 100644 --- a/tests/unit/test_checkpoint.py +++ b/tests/unit/test_checkpoint.py @@ -8,12 +8,15 @@ from types import SimpleNamespace from typing import Literal +import pytest + import verifiers.v1 as vf import verifiers.v1.agent as agent_module from verifiers.v1.clients import ModelContext, ModelRoute from verifiers.v1.configs.agent import RolloutCheckpointConfig from verifiers.v1.configs.client import EvalClientConfig from verifiers.v1.graph import MessageNode +from verifiers.v1.pause import Pause from verifiers.v1.restore import open_restore, restorable, restore_entry, unsaveable from verifiers.v1.rollout import Rollout, kept from verifiers.v1.runtimes.backends.prime import PrimeBackend @@ -172,13 +175,15 @@ def __init__(self) -> None: self.stop_fails = False """The box never stops: the snapshot fails after it was named.""" self.taken = 0 + self.woken = 0 + """Boxes a snapshot left stopped that ran again (`wake`).""" self.deleted: list[str] = [] self.stray_snapshots: list[vf.Snapshot] = [] def snapshot_pace(self, vms=1): return contextlib.nullcontext() - async def snapshot(self, taken=None) -> vf.Snapshot: + async def snapshot(self, taken=None, *, stay_stopped=False) -> vf.Snapshot: self.taken += 1 snapshot = vf.Snapshot(id=f"ck{self.taken}") # Like a Prime box: the snapshot is named before the box stops, and teardown @@ -187,11 +192,15 @@ async def snapshot(self, taken=None) -> vf.Snapshot: if taken is not None: taken(snapshot) self.stopped.set() - await self.running.wait() + if not stay_stopped: + await self.running.wait() if self.stop_fails: raise RuntimeError("pause failed") return snapshot + async def wake(self) -> None: + self.woken += 1 + async def wait_snapshot(self, snapshot: vf.Snapshot) -> int | None: await self.durable.wait() if self.fail: @@ -264,6 +273,7 @@ def make_rollout( run._segment_start = None run._deadline = None run._hold_started = None + run._holds = set() run._hold_deadline = None run._held_time = 0.0 run._capturing = asyncio.Lock() @@ -272,6 +282,12 @@ def make_rollout( run.deployment = SimpleNamespace(tool_vms={}) # type: ignore[assignment] run._urls = {} run._tool_relays = {} + run._unpaused = asyncio.Event() + run._unpaused.set() + run._suspension = None + run._suspension_named = None + run._suspension_until = None + run._suspended = None run._pruning = asyncio.Lock() run.deleted_snapshots = set() run.rewound_snapshots = [] @@ -279,6 +295,152 @@ def make_rollout( return run, backend, session +async def test_a_pause_stops_the_box_until_the_episode_resumes(): + """A paused episode's box stays stopped at a memory checkpoint, so a long pause + holds no compute. It runs again, with its replies, once the episode resumes.""" + run, backend, session = make_rollout() + pause = Pause() + pause.attach(run) # type: ignore[arg-type] + pause.pause() + await asyncio.wait_for(backend.stopped.wait(), 1) + await asyncio.sleep(0) + assert run._suspended is not None and backend.woken == 0 + assert not session.flowing.is_set() + pause.resume() + await asyncio.wait_for(run._suspension, 1) + assert backend.taken == 1 and backend.woken == 1 + assert run._suspended is None and session.flowing.is_set() + assert run._relay.rerouted and [c.id for c in run.trace.checkpoints] == ["ck1"] + backend.durable.set() + await run._settle_checkpoints(wait=True) + + +async def test_a_pause_that_ends_before_its_snapshot_stops_nothing(): + run, backend, session = make_rollout() + pause = Pause() + pause.attach(run) # type: ignore[arg-type] + pause.pause() + pause.resume() + await asyncio.wait_for(run._suspension, 1) + assert backend.taken == 0 and session.flowing.is_set() + + +async def test_a_save_of_a_paused_rollout_returns_its_stopped_box(): + """An owner saving a paused rollout gets the checkpoint its box stopped at, + without stopping the box again, and the box answers nothing until release.""" + run, backend, session = make_rollout() + pause = Pause() + pause.attach(run) # type: ignore[arg-type] + pause.pause() + await asyncio.wait_for(backend.stopped.wait(), 1) + await asyncio.sleep(0) + saved = await asyncio.wait_for(run.save(hold=True), 1) + assert saved is not None and restore_entry(saved)["id"] == "ck1" + assert backend.taken == 1 and run._suspended.pinned + pause.resume() + await asyncio.wait_for(run._suspension, 1) + assert backend.woken == 1 and not session.flowing.is_set() + run.release() + assert session.flowing.is_set() + backend.durable.set() + await run._settle_checkpoints(wait=False) + + +async def test_a_save_that_races_a_suspension_joins_it(): + """A save that arrives before the suspension named its snapshot waits for that + snapshot instead of taking its own, which would wait for the pause to end.""" + run, backend, _ = make_rollout() + pause = Pause() + pause.attach(run) # type: ignore[arg-type] + pause.pause() + saved = await asyncio.wait_for(run.save(hold=True), 1) + assert saved is not None and restore_entry(saved)["id"] == "ck1" + assert backend.taken == 1 + pause.resume() + await asyncio.wait_for(run._suspension, 1) + run.release() + backend.durable.set() + await run._settle_checkpoints(wait=False) + + +async def test_a_paused_rollout_whose_snapshot_never_uploads_saves_nothing(): + run, backend, session = make_rollout() + backend.fail = True + pause = Pause() + pause.attach(run) # type: ignore[arg-type] + pause.pause() + await asyncio.wait_for(backend.stopped.wait(), 1) + backend.durable.set() + await asyncio.gather(*run._durable.values(), return_exceptions=True) + assert await run.save(hold=True) is None + assert run.save_skipped == "its memory snapshot failed" and run._hold_id is None + pause.resume() + await asyncio.wait_for(run._suspension, 1) + assert session.flowing.is_set() + + +async def test_a_paused_rollout_puts_off_its_periodic_snapshot(): + """A due periodic snapshot of a paused rollout is put off by an interval, so its + timer does not fire again at once.""" + run, backend, _ = make_rollout() + run._unpaused.clear() + assert await run._checkpoint() is None + assert backend.taken == 0 + assert run._last_capture == pytest.approx(asyncio.get_running_loop().time(), abs=1) + + +async def test_a_second_save_of_a_paused_rollout_takes_no_owned_checkpoint(): + """The checkpoint a box stopped at goes to one owner: a later save while the box + is still stopped saves nothing instead of sharing it.""" + run, backend, _ = make_rollout() + pause = Pause() + pause.attach(run) # type: ignore[arg-type] + pause.pause() + await asyncio.wait_for(backend.stopped.wait(), 1) + assert await run.save() is not None + assert await run.save() is None + assert run.save_skipped == "it is paused at a checkpoint an earlier save holds" + pause.resume() + await asyncio.wait_for(run._suspension, 1) + backend.durable.set() + await run._settle_checkpoints(wait=False) + + +async def test_a_pause_right_after_a_resume_stops_the_box_again(): + """A new pause while the last suspension still wakes the box gets a suspension of + its own, which stops the box once the earlier one is done.""" + run, backend, _ = make_rollout() + pause = Pause() + pause.attach(run) # type: ignore[arg-type] + pause.pause() + await asyncio.wait_for(backend.stopped.wait(), 1) + first = run._suspension + pause.resume() + pause.pause() + assert run._suspension is not first + await asyncio.wait_for(first, 1) + for _ in range(10): + await asyncio.sleep(0) + assert backend.taken == 2 and backend.woken == 1 and run._suspended is not None + pause.resume() + await asyncio.wait_for(run._suspension, 1) + assert backend.woken == 2 + backend.durable.set() + await run._settle_checkpoints(wait=False) + + +async def test_a_closing_rollout_wakes_its_paused_box(): + """Teardown reaches into the box, so a rollout that closes while paused runs its + box again instead of waiting for the pause to end.""" + run, backend, _ = make_rollout() + pause = Pause() + pause.attach(run) # type: ignore[arg-type] + pause.pause() + await asyncio.wait_for(backend.stopped.wait(), 1) + await asyncio.wait_for(run._settle_checkpoints(wait=False), 1) + assert backend.woken == 1 and pause.paused + + async def test_timer_captures_without_a_model_call_and_owner_reuses_it(): run, backend, session = make_rollout() backend.durable.set() @@ -599,7 +761,7 @@ async def test_no_memory_snapshot_without_a_running_segment(): async def test_a_failed_memory_snapshot_lets_replies_flow_again(): run, backend, session = make_rollout() - async def failing(taken=None): + async def failing(taken=None, *, stay_stopped=False): raise vf.SandboxError("pause refused") backend.snapshot = failing # type: ignore[method-assign] @@ -866,7 +1028,7 @@ async def test_a_snapshot_dropped_before_the_save_resumes_is_no_restore_point(): then returns no restore point, and the box's teardown frees the snapshot.""" run, backend, session = make_rollout() - async def named_then_failed(taken=None): + async def named_then_failed(taken=None, *, stay_stopped=False): snapshot = vf.Snapshot(id="ck1") backend.stray_snapshots.append(snapshot) taken(snapshot) @@ -914,7 +1076,7 @@ async def test_an_owners_snapshot_outlives_the_end_of_its_program(): async def test_a_failed_held_save_does_not_hold_the_box(): run, backend, session = make_rollout() - async def failing(taken=None): + async def failing(taken=None, *, stay_stopped=False): raise vf.SandboxError("pause refused") backend.snapshot = failing # type: ignore[method-assign] diff --git a/tests/unit/test_pause.py b/tests/unit/test_pause.py new file mode 100644 index 0000000000..33930867d6 --- /dev/null +++ b/tests/unit/test_pause.py @@ -0,0 +1,132 @@ +"""Pausing an episode: its model calls wait, and the paused time is not the agent's.""" + +import asyncio + +from verifiers.v1.clients import EvalClientConfig, ModelContext, ModelRoute +from verifiers.v1.env import RunSlot +from verifiers.v1.pause import Pause, pausing +from verifiers.v1.rollout import OWNER_HOLD, Rollout +from verifiers.v1.session import RolloutSession + + +class HeldRollout: + set_paused = Rollout.set_paused + _begin_hold = Rollout._begin_hold + _end_hold = Rollout._end_hold + _segment_agent_time = Rollout._segment_agent_time + _suspend_box = Rollout._suspend_box + _reschedule = Rollout._reschedule + + def __init__(self) -> None: + # No memory snapshots: a pause stops only the agent deadline. + self._memory = False + self._closed = False + self._harness_session = None + self._suspension = None + self._unpaused = asyncio.Event() + self._unpaused.set() + self._holds: set[str] = set() + self._hold_started = None + self._hold_deadline = None + self._held_time = 0.0 + self._segment_start = asyncio.get_running_loop().time() + self._deadline = None + self.deadline_at = None + + +def test_a_slot_has_its_own_pause(): + first, second = RunSlot(task=None), RunSlot(task=None) # type: ignore[arg-type] + first.pause.pause() + assert first.pause.paused and not second.pause.paused + + +def test_a_session_follows_its_episodes_pause(): + pause = Pause() + session = RolloutSession( + ModelRoute(ModelContext(model="m", client=EvalClientConfig())), + trace=None, # type: ignore[arg-type] + running=pause.running, + ) + pause.pause() + assert not session.running.is_set() + pause.resume() + assert session.running.is_set() + # A session outside any episode always runs. + assert RolloutSession( + ModelRoute(ModelContext(model="m", client=EvalClientConfig())), + trace=None, # type: ignore[arg-type] + ).running.is_set() + + +async def test_rollouts_built_in_an_episode_see_its_pause(): + async def read() -> Pause | None: + return pausing.get() + + pause = Pause() + token = pausing.set(pause) + try: + seen = await asyncio.create_task(read()) + finally: + pausing.reset(token) + assert seen is pause and pausing.get() is None + + +async def test_a_pause_stops_the_agent_deadline(): + run = HeldRollout() + pause = Pause() + pause.attach(run) # type: ignore[arg-type] + loop = asyncio.get_running_loop() + async with asyncio.timeout_at(loop.time() + 0.2) as deadline: + run._deadline = deadline + run.deadline_at = deadline.when() + pause.pause() + assert deadline.when() is None + await asyncio.sleep(0.3) + pause.resume() + when = deadline.when() + assert when is not None and when >= loop.time() + 0.15 + assert run._segment_agent_time() < 0.1 + + +async def test_a_rollout_attached_while_paused_holds_at_once(): + run = HeldRollout() + pause = Pause() + pause.pause() + pause.attach(run) # type: ignore[arg-type] + assert run._hold_started is not None + pause.resume() + assert run._hold_started is None + + +async def test_an_owner_release_does_not_end_a_pause(): + run = HeldRollout() + pause = Pause() + pause.attach(run) # type: ignore[arg-type] + loop = asyncio.get_running_loop() + async with asyncio.timeout_at(loop.time() + 10) as deadline: + run._deadline = deadline + run.deadline_at = deadline.when() + run._begin_hold(OWNER_HOLD) + pause.pause() + run._end_hold(OWNER_HOLD) + await asyncio.sleep(0) + assert deadline.when() is None + pause.resume() + assert deadline.when() is not None + + +async def test_a_pause_after_the_segment_timed_out_reaches_every_rollout(): + """A pause can race the end of a segment whose deadline already left its block: + the deadline is past moving, and the other rollouts still get the pause.""" + first, second = HeldRollout(), HeldRollout() + pause = Pause() + pause.attach(first) # type: ignore[arg-type] + pause.attach(second) # type: ignore[arg-type] + loop = asyncio.get_running_loop() + async with asyncio.timeout_at(loop.time() + 10) as deadline: + first._deadline = deadline + await asyncio.sleep(0) + pause.pause() + assert second._hold_started is not None + pause.resume() + assert first._hold_started is None and second._hold_started is None diff --git a/tests/unit/test_tool_vm_snapshot.py b/tests/unit/test_tool_vm_snapshot.py index 059ebfd542..d3baa5337f 100644 --- a/tests/unit/test_tool_vm_snapshot.py +++ b/tests/unit/test_tool_vm_snapshot.py @@ -88,6 +88,21 @@ async def test_a_network_snapshot_names_every_member_and_resumes_them(monkeypatc assert box._awake.is_set() and vm._awake.is_set() +async def test_a_network_snapshot_kept_stopped_resumes_every_member_on_wake( + monkeypatch, +): + client = Network() + box, vm = members(monkeypatch, client) + await box.snapshot_network([vm], stay_stopped=True) + assert client.calls == ["pause", "FROZEN"] + assert client.running == {"a": False, "b": False} + assert not box._awake.is_set() and not vm._awake.is_set() + await box.wake() + assert client.calls == ["pause", "FROZEN", "FROZEN", "resume:n1"] + assert client.running == {"a": True, "b": True} + assert box._awake.is_set() and vm._awake.is_set() + + async def test_a_failed_network_pause_still_resumes_every_member(monkeypatch): client = Network(status="FAILED") box, vm = members(monkeypatch, client) diff --git a/verifiers/v1/env.py b/verifiers/v1/env.py index c737774dae..2fb96ff042 100644 --- a/verifiers/v1/env.py +++ b/verifiers/v1/env.py @@ -31,6 +31,7 @@ requires_tunnel, ) from verifiers.v1.mcp import SharedToolServer, serve_shared +from verifiers.v1.pause import Pause, pausing from verifiers.v1.restore import EpisodeCalls from verifiers.v1.runtimes import SubprocessConfig, runtime_is_local from verifiers.v1.task import Task @@ -76,6 +77,8 @@ class RunSlot: calls: EpisodeCalls | None = None """The agent calls of the attempt in flight, for an owner that saves the episode (`episode_restore_point`).""" + pause: Pause = field(default_factory=Pause) + """Holds back the episode's model calls while paused (`Pause`).""" ConfigT = TypeVar("ConfigT", bound=EnvConfig) @@ -388,7 +391,11 @@ def discard(trace: Trace) -> None: started: float | None = None with scope(episode=short_id(slot.id)): - episode = await run_episode_with_retry(attempt, self.config.retries) + token = pausing.set(slot.pause) + try: + episode = await run_episode_with_retry(attempt, self.config.retries) + finally: + pausing.reset(token) elapsed = format_time( time.perf_counter() - (started or time.perf_counter()) ) diff --git a/verifiers/v1/interception/server.py b/verifiers/v1/interception/server.py index ffe333bf96..474ee77967 100644 --- a/verifiers/v1/interception/server.py +++ b/verifiers/v1/interception/server.py @@ -1177,6 +1177,14 @@ async def sample() -> web.Response: error: Exception | None = None started = time.time() try: + if not session.running.is_set(): + # A paused episode sends nothing upstream until it resumes. A waiter + # can wake after a resume that a new pause already undid. + while not session.running.is_set(): + if session.on_paused_call is not None: + session.on_paused_call() + await session.running.wait() + started = time.time() try: # What actually goes upstream: the native body with the rollout's model + # sampling imposed — recorded raw on the trace, per call. diff --git a/verifiers/v1/pause.py b/verifiers/v1/pause.py new file mode 100644 index 0000000000..c6abf917a8 --- /dev/null +++ b/verifiers/v1/pause.py @@ -0,0 +1,55 @@ +"""Pausing a running episode, so an owner that sheds inference load keeps its progress. + +A paused episode sends no new model call upstream: each call of its rollouts waits at +the interception server until the episode resumes. A call already upstream finishes. +The boxes keep running, and the time paused does not count against the agents' +deadlines. +""" + +from __future__ import annotations + +import asyncio +import weakref +from contextvars import ContextVar +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from verifiers.v1.rollout import Rollout + + +class Pause: + """One episode's pause switch (`RunSlot.pause`). Every rollout of the episode, + retries included, follows it.""" + + def __init__(self) -> None: + self.running = asyncio.Event() + """Set while the episode runs; its model calls wait for it.""" + self.running.set() + self._rollouts: weakref.WeakSet[Rollout] = weakref.WeakSet() + + @property + def paused(self) -> bool: + return not self.running.is_set() + + def pause(self) -> None: + if self.paused: + return + self.running.clear() + for rollout in list(self._rollouts): + rollout.set_paused(True) + + def resume(self) -> None: + if not self.paused: + return + self.running.set() + for rollout in list(self._rollouts): + rollout.set_paused(False) + + def attach(self, rollout: Rollout) -> None: + self._rollouts.add(rollout) + if self.paused: + rollout.set_paused(True) + + +pausing: ContextVar[Pause | None] = ContextVar("vf_pausing", default=None) +"""The pause switch of the episode this task runs (`Env.run_slot`).""" diff --git a/verifiers/v1/rollout.py b/verifiers/v1/rollout.py index 58add055b4..7721eaa254 100644 --- a/verifiers/v1/rollout.py +++ b/verifiers/v1/rollout.py @@ -34,6 +34,7 @@ from verifiers.v1.interception import Interception, serve_interception from verifiers.v1.interception.relay import RELEASE_ATTEMPTS, Relay from verifiers.v1.mcp import SharedToolServer, serve_tools +from verifiers.v1.pause import pausing from verifiers.v1.restore import LIVE, restorable, restore_entry, unsaveable from verifiers.v1.runtimes import ( PrimeBackend, @@ -98,6 +99,9 @@ class RolloutTimeouts: """How long a snapshot of a box with tool server VMs waits for the box to ask for a model turn or a tool verdict, when no tool call is under way between them.""" +OWNER_HOLD = "owner" +PAUSE_HOLD = "pause" + def _origin(url: str) -> str: parts = urlsplit(url) @@ -316,6 +320,21 @@ def __init__( response_stops=[fn for boundary, fn in stops if boundary is Response], gates_tools=harness.SUPPORTS_TOOL_INTERCEPTION, ) + self._pause = pausing.get() + if self._pause is not None: + self._session.running = self._pause.running + self._session.on_paused_call = self._suspend_box + self._unpaused = asyncio.Event() + """Cleared while the episode is paused (`set_paused`).""" + self._unpaused.set() + self._suspension: asyncio.Task[None] | None = None + """Stops the box for the pause (`_suspend_box`).""" + self._suspension_named: asyncio.Future[Checkpoint] | None = None + """Set once the suspension's snapshot is named.""" + self._suspension_until: asyncio.Event | None = None + """The pause the suspension is for (its `_unpaused`).""" + self._suspended: Checkpoint | None = None + """The memory checkpoint the box stopped at, while it stays stopped.""" self._memory = False """Whether this run can take memory snapshots: decided at `open`, once the box, its relay and the task's tool servers are known. Its checkpoints at model turns @@ -338,6 +357,9 @@ def __init__( self._deadline: asyncio.Timeout | None = None """The running segment's agent deadline, which a hold stops.""" self._hold_started: float | None = None + self._holds: set[str] = set() + """Why the agent deadline is stopped: an owner's save (`OWNER_HOLD`), a pause + (`PAUSE_HOLD`), or both.""" self._hold_deadline: float | None = None """When the agent deadline was due as the hold stopped it.""" self._held_time = 0.0 @@ -419,6 +441,8 @@ async def open(self) -> bool: proceed; a setup failure is captured onto the trace.""" self._opened = True LIVE.add(self) + if self._pause is not None: + self._pause.attach(self) self.trace.timing.boot.start = time.time() self.trace.notify() if self._borrowed_runtime is None: @@ -952,8 +976,14 @@ async def step( if self._agent_time_remaining is None else segment_start + max(0.0, self._agent_time_remaining) ) + # A hold under way (a pause) stops the deadline from the segment's start. + self._hold_deadline = ( + self.deadline_at if self._hold_started is not None else None + ) # Prefer an intercepted model/tool error to the harness exit it caused. - deadline = self._deadline = asyncio.timeout_at(self.deadline_at) + deadline = self._deadline = asyncio.timeout_at( + None if self._hold_deadline is not None else self.deadline_at + ) try: async with deadline: assert self._harness_session is not None @@ -1058,7 +1088,7 @@ async def _turn(self, messages: Messages | None) -> bool: def _segment_agent_time(self) -> float: """The agent time the running segment used so far: its time, less the time - an owner held it.""" + it was held (`_begin_hold`).""" if self._segment_start is None: return 0.0 now = asyncio.get_running_loop().time() @@ -1067,32 +1097,45 @@ def _segment_agent_time(self) -> float: held += now - max(self._hold_started, self._segment_start) return max(0.0, now - self._segment_start - held) - def _begin_hold(self) -> None: - """Hold the rollout for its owner. The hold is the owner's time: the agent - deadline stops until `release`.""" + def _begin_hold(self, reason: str = OWNER_HOLD) -> None: + """Stop the agent deadline for `reason`: an owner's hold or a pause is not the + agent's time. It runs again once every reason ended (`_end_hold`).""" + self._holds.add(reason) if self._hold_started is not None: return self._hold_started = asyncio.get_running_loop().time() if self._segment_start is not None and self._deadline is not None: when = self._deadline.when() - if when is not None: + if when is not None and self._reschedule(None): self._hold_deadline = when - self._deadline.reschedule(None) - def _end_hold(self) -> None: - if self._hold_started is None: + def _end_hold(self, reason: str = OWNER_HOLD) -> None: + self._holds.discard(reason) + if self._hold_started is None or self._holds: return - held = asyncio.get_running_loop().time() - self._hold_started - self._hold_started = None + hold_started, self._hold_started = self._hold_started, None if self._segment_start is None: return + held = asyncio.get_running_loop().time() - max( + hold_started, self._segment_start + ) self._held_time += held if self._hold_deadline is not None and self._deadline is not None: - self._deadline.reschedule(self._hold_deadline + held) - if self.deadline_at is not None: + moved = self._reschedule(self._hold_deadline + held) + if moved and self.deadline_at is not None: self.deadline_at += held self._hold_deadline = None + def _reschedule(self, when: float | None) -> bool: + """Move the segment's agent deadline. False once the segment's timeout is past + moving: it expired or its block exited, which a hold can race with.""" + assert self._deadline is not None + try: + self._deadline.reschedule(when) + except RuntimeError: + return False + return True + async def restore(self) -> bool: """Run the restored attempt's first segment: the box restored from the checkpoint still runs the harness program, so this waits for it @@ -1145,6 +1188,11 @@ async def _checkpoint(self) -> Checkpoint | None: now = asyncio.get_running_loop().time() if now - self._last_capture < self._checkpointing.interval: return None + if not self._unpaused.is_set(): + # A paused rollout makes no progress to snapshot, and its box may be + # stopped: the next snapshot is due an interval later. + self._last_capture = now + return None # Pace failed attempts too, including a program that exited before capture. self._last_capture = now return await self._take_snapshot() @@ -1210,6 +1258,39 @@ async def save( self.save_skipped = "its harness program is not running (setup or scoring)" if self.save_skipped is not None: return None + if ( + self._suspended is None + and self._suspension is not None + and not self._suspension.done() + ): + # A suspension under way names its checkpoint soon. A snapshot of this + # save's own would wait for the pause to end. + assert self._suspension_named is not None + await asyncio.wait( + {self._suspension, self._suspension_named}, + return_when=asyncio.FIRST_COMPLETED, + ) + suspended = self._suspended + if suspended is not None: + if suspended.deleted or suspended not in self.trace.checkpoints: + # Its upload failed: no restore can continue it. + self.save_skipped = "its memory snapshot failed" + return None + if suspended.pinned: + # Each snapshot has one owner, who deletes it once nothing restores + # from it, and a stopped box takes no new one. + self.save_skipped = "it is paused at a checkpoint an earlier save holds" + return None + # The box stays stopped at this checkpoint until the pause ends, and its + # replies stay held until then. + suspended.pinned = True + if hold: + self._hold_id = suspended.id + self._unheld.clear() + self._begin_hold() + if watchdog: + self.arm_hold_watchdog() + return restorable(self.trace, suspended) # Before the hold, which stops the agent deadline: the tool call runs on it. loop = asyncio.get_running_loop() if not await self._tools_rest(loop.time() + TOOLS_REST_SECONDS): @@ -1269,6 +1350,57 @@ async def save( self.arm_hold_watchdog() return saved + def set_paused(self, paused: bool) -> None: + """The episode paused or resumed (`Pause`): the agent deadline stops while it + is paused, and so does the box (`_suspend_box`).""" + if paused: + self._begin_hold(PAUSE_HOLD) + if self._unpaused.is_set(): + self._unpaused = asyncio.Event() + self._suspend_box() + else: + self._end_hold(PAUSE_HOLD) + self._unpaused.set() + + def _suspend_box(self) -> None: + """Stop the box until the pause ends: a memory checkpoint whose box stays + stopped, so a long pause holds no compute. Tried again when a model call + waits for the pause (`RolloutSession.on_paused_call`): a box still booting or + between segments has nothing to snapshot yet.""" + if ( + not self._memory + or self._closed + or self._harness_session is None + or self._unpaused.is_set() + # One suspension per pause. One of an earlier pause may still be waking + # the box: this one stops it again after (`_capturing`). + or ( + self._suspension is not None + and not self._suspension.done() + and self._suspension_until is self._unpaused + ) + ): + return + self._suspension_named = asyncio.get_running_loop().create_future() + self._suspension_until = self._unpaused + self._suspension = asyncio.create_task( + self._suspend(self._suspension_named, self._unpaused) + ) + self._captures.add(self._suspension) + self._suspension.add_done_callback(self._captures.discard) + + async def _suspend( + self, taken: asyncio.Future[Checkpoint], until: asyncio.Event + ) -> None: + try: + await self._capture(taken, pinned=False, until=until) + except Exception: + logger.warning( + "box did not run again after its pause (rollout %s)", + self.trace.id, + exc_info=True, + ) + def arm_hold_watchdog(self) -> None: """Release the hold by itself after `HOLD_SECONDS`, unless the owner does first: an owner that never releases must not stall the rollout for good.""" @@ -1340,12 +1472,16 @@ async def _take_snapshot(self, *, pinned: bool = False) -> Checkpoint | None: return taken.result() async def _capture( - self, taken: asyncio.Future[Checkpoint], pinned: bool + self, + taken: asyncio.Future[Checkpoint], + pinned: bool, + until: asyncio.Event | None = None, ) -> Checkpoint | None: """Take the snapshot `_take_snapshot` hands out through `taken`, and hold the - box's replies until it runs again. A snapshot that fails after it was handed - out is dropped (`_drop_capture`). So is a snapshot that no owner holds and - whose program ended while the box stopped.""" + box's replies until it runs again. With `until`, the box stays stopped until + it is set (`_suspend_box`). A snapshot that fails after it was handed out is + dropped (`_drop_capture`). So is a snapshot that no owner holds and whose + program ended while the box stopped.""" assert self.runtime is not None and self._relay is not None assert self._harness_session is not None session = self._session @@ -1359,17 +1495,20 @@ async def _capture( if not await self._tools_rest(deadline): self._tools_busy = not self._closed return None + # Apart from the hold: a box that stays stopped gives its pace slot back. + pace = AsyncExitStack() held = AsyncExitStack() try: - await held.enter_async_context( + await pace.enter_async_context( self.runtime.backend.snapshot_pace(1 + len(self.deployment.tool_vms)) ) await held.enter_async_context(self._capturing) except BaseException: await held.aclose() + await pace.aclose() raise - async with held: - if self._closed: + async with pace, held: + if self._closed or (until is not None and until.is_set()): return None relays = [relay for relay, _ in self._tool_relays.values()] if relays: @@ -1470,12 +1609,17 @@ def on_taken(snapshots: dict[str, Snapshot]) -> None: pinned=pinned, ) self.trace.checkpoints.append(checkpoint) + if until is not None: + self._suspended = checkpoint if not taken.done(): taken.set_result(checkpoint) try: - snapshots = await self._snapshot(on_taken) + snapshots = await self._snapshot( + on_taken, stay_stopped=until is not None + ) except Exception: + self._suspended = None logger.warning( "memory snapshot failed (rollout %s)", self.trace.id, @@ -1486,6 +1630,19 @@ def on_taken(snapshots: dict[str, Snapshot]) -> None: if checkpoint is None: on_taken(snapshots) assert checkpoint is not None + if until is not None: + # Restorable while the box stays stopped: an owner may save it + # (`save`), and a retry continues it if the box never runs again. + self._durable[checkpoint.id] = asyncio.create_task( + self._make_durable(checkpoint) + ) + # A stopped box takes no turn of the snapshot pace. + await pace.aclose() + try: + await until.wait() + finally: + self._suspended = None + await self.runtime.backend.wake() if not checkpoint.pinned and ( self._harness_session is None or self._harness_session.memory_state() is None @@ -1511,9 +1668,10 @@ def on_taken(snapshots: dict[str, Snapshot]) -> None: self._end_hold() session.resume() checkpoint.held = time.time() - started - self._durable[checkpoint.id] = asyncio.create_task( - self._make_durable(checkpoint) - ) + if until is None: + self._durable[checkpoint.id] = asyncio.create_task( + self._make_durable(checkpoint) + ) logger.debug( "memory checkpoint %s taken in %s: id=%s node=%s", checkpoint.id, @@ -1551,15 +1709,19 @@ async def _tools_rest(self, deadline: float) -> bool: return True async def _snapshot( - self, taken: Callable[[dict[str, Snapshot]], None] + self, + taken: Callable[[dict[str, Snapshot]], None], + *, + stay_stopped: bool = False, ) -> dict[str, Snapshot]: """Snapshot the box, and its tool server VMs in the same network pause, by role (`Checkpoint.snapshots`). `taken` gets them once the provider named every one, before the stop ends. Every part stays with the box's strays until it is - durable.""" + durable. With `stay_stopped`, they stay stopped until the backend's `wake`.""" backend = self.runtime.backend + stop = {"stay_stopped": True} if stay_stopped else {} if not self.deployment.tool_vms: - snapshot = await backend.snapshot(lambda s: taken({WORKSPACE: s})) + snapshot = await backend.snapshot(lambda s: taken({WORKSPACE: s}), **stop) return {WORKSPACE: snapshot} vms = { tool_snapshot_key(name): self.deployment.target_backends[name] @@ -1569,6 +1731,7 @@ async def _snapshot( snapshots = await cast(PrimeBackend, backend).snapshot_network( cast(list[PrimeBackend], list(vms.values())), lambda named: taken(dict(zip(roles, named))), + **stop, ) return dict(zip(roles, snapshots)) @@ -1666,7 +1829,9 @@ async def _settle_checkpoints(self, *, wait: bool) -> None: """Before the box goes: wait for the snapshots still uploading, so a retry can restore them (its teardown would fail them), or, with nothing to retry, stop waiting and leave them to be freed.""" - # A snapshot still being taken would start its upload after this returned. + # A box stopped for a pause runs again, so its teardown can reach it. A + # snapshot still being taken would start its upload after this returned. + self._unpaused.set() await asyncio.gather(*self._captures, return_exceptions=True) tasks = list(self._durable.values()) if not wait: @@ -1839,6 +2004,8 @@ async def close(self) -> Trace: return self.trace self._closed = True self._closing.set() + # A box stopped for a pause runs again: finalizing and teardown reach into it. + self._unpaused.set() LIVE.discard(self) trace = self.trace skip = self._scoring_skip() diff --git a/verifiers/v1/runtimes/backends/prime.py b/verifiers/v1/runtimes/backends/prime.py index 0b1d230e40..dbc980cb22 100644 --- a/verifiers/v1/runtimes/backends/prime.py +++ b/verifiers/v1/runtimes/backends/prime.py @@ -205,6 +205,9 @@ def __init__(self, config: PrimeConfig, name: str | None = None) -> None: """Memory snapshots taken of this box. Each one ended the open streams into it.""" self._network_pauses: set[str] = set() """Network checkpoints of this box's pauses: a lost pause answer is a newer one.""" + self._stopped: tuple[list[PrimeBackend], str | None] | None = None + """The peers and network checkpoint of a stop that `snapshot_network(..., + stay_stopped=True)` left in place, for `wake`.""" @property def published_port(self) -> int: @@ -370,10 +373,15 @@ async def create_and_capture_id(): raise SandboxError(f"prime sandbox provisioning failed: {e}") from e async def snapshot( - self, taken: Callable[[Snapshot], None] | None = None + self, + taken: Callable[[Snapshot], None] | None = None, + *, + stay_stopped: bool = False, ) -> Snapshot: [snapshot] = await self.snapshot_network( - [], None if taken is None else lambda named: taken(named[0]) + [], + None if taken is None else lambda named: taken(named[0]), + stay_stopped=stay_stopped, ) return snapshot @@ -381,11 +389,13 @@ async def snapshot_network( self, peers: list[PrimeBackend], taken: Callable[[list[Snapshot]], None] | None = None, + *, + stay_stopped: bool = False, ) -> list[Snapshot]: """Snapshot this box and its LAN peers in one stop, in the order `[self, *peers]`. With peers, the stop is a network pause: the platform pauses every member or none, and its network resume brings each one back with its - LAN routes.""" + LAN routes. With `stay_stopped`, every member stays stopped until `wake`.""" # A pause is the platform's memory snapshot: it stops the box, and the resume # continues it. The platform uploads the snapshot after the pause. Until it is # durable the snapshot is stray: the platform refuses to delete it while this @@ -400,6 +410,7 @@ async def create() -> list[Snapshot]: member._awake.clear() member._snapshots += 1 resume: str | None = None + stopped = False try: try: if network is None: @@ -434,17 +445,27 @@ async def create() -> list[Snapshot]: ) else: await self._wait_network_pause(network, paused.id) + if stay_stopped: + self._stopped = (peers, resume) + stopped = True finally: # The pause was accepted, so every member stops or has stopped. # Each must run again also when the wait for it failed. - await self._resume(peers, resume) + if not stopped: + await self._resume(peers, resume) finally: - for member in members: - member._awake.set() + if not stopped: + for member in members: + member._awake.set() return snapshots try: return await run_shielded(create()) + except asyncio.CancelledError: + # The caller never learns of a box left stopped, so nothing would wake it. + if not self._awake.is_set(): + await self.wake() + raise except Exception as e: raise SandboxError(f"prime checkpoint failed: {e}") from e @@ -495,6 +516,16 @@ async def snapshot_pace(self, vms: int = 1) -> AsyncIterator[None]: async with slots: yield + async def wake(self) -> None: + peers, network_checkpoint = self._stopped or ([], None) + self._stopped = None + try: + await run_shielded(self._resume(peers, network_checkpoint)) + finally: + # A box that did not resume fails the calls that waited for it. + for member in [self, *peers]: + member._awake.set() + async def _resume( self, peers: list[PrimeBackend], network_checkpoint: str | None ) -> None: diff --git a/verifiers/v1/runtimes/base.py b/verifiers/v1/runtimes/base.py index 572dd12aae..2d6d90ec77 100644 --- a/verifiers/v1/runtimes/base.py +++ b/verifiers/v1/runtimes/base.py @@ -282,13 +282,22 @@ async def start(self) -> None: pass async def snapshot( - self, taken: Callable[[Snapshot], None] | None = None + self, + taken: Callable[[Snapshot], None] | None = None, + *, + stay_stopped: bool = False, ) -> Snapshot: """Snapshot the box's files and memory. The box stops while the snapshot is taken and runs again when this returns; its connections to the outside may be - dead by then. `taken` gets the snapshot as soon as the provider names it, - before the box has stopped; a snapshot that fails after that still raises - here. The snapshot becomes restorable only later (`wait_snapshot`).""" + dead by then. With `stay_stopped`, the box stays stopped until `wake`, and + frees its compute meanwhile. `taken` gets the snapshot as soon as the provider + names it, before the box has stopped; a snapshot that fails after that still + raises here (and the box runs again). The snapshot becomes restorable only + later (`wait_snapshot`).""" + raise NotImplementedError(f"{type(self).__name__} does not support snapshots") + + async def wake(self) -> None: + """Run the box a `snapshot(stay_stopped=True)` left stopped.""" raise NotImplementedError(f"{type(self).__name__} does not support snapshots") def snapshot_pace(self, vms: int = 1) -> AbstractAsyncContextManager[Any]: diff --git a/verifiers/v1/session.py b/verifiers/v1/session.py index 3d64a03778..ca9ca6d567 100644 --- a/verifiers/v1/session.py +++ b/verifiers/v1/session.py @@ -39,6 +39,7 @@ from verifiers.v1.dialects.base import CAPABILITY_NOTICE from verifiers.v1.errors import HarnessError, RolloutError, TaskError from verifiers.v1.harnesses.utils.compaction import bound_tool_message +from verifiers.v1.pause import Pause from verifiers.v1.trace import InterceptRecord, ModelCall, Trace from verifiers.v1.types import ( AssistantMessage, @@ -445,6 +446,13 @@ class RolloutSession: asked for is answered or written until it is set again, so the box the snapshot stops has seen exactly what the trace held when the hold began.""" + running: asyncio.Event = field(default_factory=lambda: Pause().running, repr=False) + """Cleared while the episode is paused (`Pause.running`): no new model call goes + upstream until it is set again.""" + + on_paused_call: Callable[[], None] | None = field(default=None, repr=False) + """Called when a model call starts to wait for a paused episode (`running`).""" + settled: asyncio.Event = field(default_factory=asyncio.Event, repr=False) """Cleared while a turn is between its commit and its reply being ready to send again (`committing`). A snapshot records the trace only when it is set: every