Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/agent.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
4 changes: 2 additions & 2 deletions tests/integration/test_rollout_checkpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
73 changes: 73 additions & 0 deletions tests/unit/runtimes/test_prime_fork.py
Original file line number Diff line number Diff line change
Expand Up @@ -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())
172 changes: 167 additions & 5 deletions tests/unit/test_checkpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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:
Expand Down Expand Up @@ -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()
Expand All @@ -272,13 +282,165 @@ 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 = []
run.restored_turns = None
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()
Expand Down Expand Up @@ -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]
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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]
Expand Down
Loading