# castform.recovery: safe resume after a restore

The library that makes a trainer's resumed run correct after Castform compute restores its
container (with its checkpoint engine, pcx) when its rollouts run in sandboxes the customer
supplies (Modal, E2B, Daytona). What it covers today: RL rollouts and the sandboxes they create,
and nothing else. Other external state a lost run touched (an inference fleet it sent weights to,
say) isn't recovered. This file is the library's contract: change it only together with the code
that relies on it.

The rule: **never continue a rollout whose sandbox state is uncertain; redoing it is always
correct.** After a restore, the library:

1. notices it (Castform compute's instance id, `/.pcx/instance`);
2. discards every rollout that was in flight across it (cancelled, or finished but spanning it)
   and runs its prompt again as a new attempt;
3. ends ("sweeps") every sandbox of the run from before the restore, including those the lost
   timeline made after the checkpoint.

The framework never sees a discarded rollout. It gets exactly one result per call it made, as in
an uninterrupted run. A redone rollout always starts over: nothing from the lost attempt is kept
or replayed.

Customers on stock miles or verl with Modal, E2B or Daytona need no code. For any other framework or
provider, see "Using castform.recovery off the standard path".

## Layout

```
core/client-sdk/              castform: the SDK (import castform) and this library
  pyproject.toml              optional extras modal, e2b, daytona: pins of the SDK versions
                              the adapters support. A customer installs castform
                              with no extra (the job brings its own SDK). E2B needs Python
                              3.11+ (e2b 2.61 does). castform.recovery imports nothing of
                              the SDK's, so loading it never loads httpx or the SDK
  src/castform/recovery/
    __init__.py               import side effect: settings; if on, hooks.install().
                              The public API off the standard path
    config.py                 settings from the environment
    events.py                 the JSONL event log the drill reads
    restore.py                restore detection, life, the recovery thread
    rollouts.py               run_rollout, the rollout context, discards
                              rollout (public); stamp, trained (internal: the
                              trained record)
    sweep.py                  ending the run's sandboxes from other lives
    providers/__init__.py     the Adapter interface, tag names and registry
                              sandbox_tags, safe_name: a customer's provider's creates
    providers/_common.py      what the adapters share: tags, safe names, retries
    providers/modal.py        Modal: patch create and terminate; list; end
    providers/e2b.py          E2B: the same
    providers/daytona.py      Daytona: the same
    hooks/__init__.py         patching on import, version checks
    hooks/miles.py            miles 0.1.x: a rollout per generate_and_rm call
    hooks/verl.py             verl 0.9.1, main: a rollout per _run_agent_loop call
    hooks/ray_env.py          ray.init: the settings to every worker of the job
  src/castform_recovery.pth   at site-packages' root: loads us at startup when on
  src/castform_recovery_boot.py  what the .pth and verl's plugin entry point load
  tests/recovery/             pytest; no network unless marked `provider`
    drill/                    Castform's internal restore drill, not in the package (README.md)
```

## Settings (environment)

A customer sets `CASTFORM_RECOVERY` and `CASTFORM_RECOVERY_RUN` (and
`CASTFORM_RECOVERY_FRAMEWORKS=off` for an unsupported miles or verl). The other defaults fit
Castform compute, and `CASTFORM_RECOVERY_LOG` is for Castform's tests and support.

| Variable | Meaning |
|---|---|
| `CASTFORM_RECOVERY` | `resample` turns recovery on. Unset or `off`: importing the library changes nothing. Anything else is an error. |
| `CASTFORM_RECOVERY_RUN` | The run's name, unique per job: every sandbox's tags carry it, and the adapters list the sandboxes to sweep by it (a sweep ends only those of this run and this scope). Required when on. |
| `CASTFORM_RECOVERY_SIGNAL` | `auto` (default): `/.pcx/instance` if it exists, else `/etc/hosts` when `/.pcx` exists (a Castform compute without the instance id), else the clock. Or `marker:PATH`, or `clock`. A relative `PATH` is taken from the working directory at load. |
| `CASTFORM_RECOVERY_LOG` | Path of the event log (JSONL, appended), which the drill reads: for Castform's own testing and for support. A customer job doesn't need it. It must be outside the checkpoint (a host volume), so a restore doesn't roll it back. A relative path is taken from the working directory at load. Unset: no log. |
| `CASTFORM_RECOVERY_STATE_DIR` | Where the scope file lives. Default `/tmp/castform-recovery`. It must be in the container's own filesystem: in the checkpoint, shared by the container's processes, and by nothing else (not a host volume). A relative path is taken from the working directory at load. |
| `CASTFORM_RECOVERY_FRAMEWORKS` | `on` (default): hook miles and verl. `off`: skip the framework hooks and their version checks, and mark rollouts with `@cr.rollout` (an unsupported version of miles or verl: "Using castform.recovery off the standard path"). The provider hooks stay. Anything else is an error. |

`config.from_env(environ=None) -> Settings` reads them (`ConfigError`, a `ValueError`, on a bad
value). `Settings(recovery, run, signal, log, state_dir, frameworks)` is a frozen dataclass with
`.enabled`.
The library reads `config.get()`: the settings `import castform.recovery` read, or those given to
`config.configure(settings)` (Castform's tests; a job, whatever its trainer, loads the library
through the environment: "Using castform.recovery off the standard path").

## Is it on?

With recovery on, the first rollout of each process prints one line to stderr, once (a forked
child prints its own):

```
castform.recovery: tracking rollouts (run NAME)
```

`NAME` is `CASTFORM_RECOVERY_RUN`. The line comes however the first rollout runs: `@cr.rollout`,
`cr.run_rollout`, and the miles and verl hooks all go through `run_rollout`. On Castform the job's
stderr is in `castform logs CONTAINER`. If the line never appears, either no rollout ran under the
library (the decorator is on the wrong function) or the settings didn't reach the processes that
run rollouts. With recovery off nothing is printed. Loading the library prints nothing either: only
a rollout does.

## Identity and tags

Every sandbox created inside a rollout carries these tags (Modal `tags`, E2B `metadata`, Daytona
`labels`), merged with the customer's own:

| Tag | Value |
|---|---|
| `castform-run` | `CASTFORM_RECOVERY_RUN` |
| `castform-scope` | `restore.scope()`: the container (below) |
| `castform-life` | the rollout's life, `rollouts.current().life` (below) |
| `castform-lineage` | a random id made at process start; unchanged by a restore (it is in the checkpoint) |
| `castform-rollout` | `none` on a sandbox created outside any rollout (absent inside one) |
| `castform-prompt` | the rollout's prompt key (the framework's sample identity, a string): as it is when it's at most 63 letters, digits and `._;+-` (miles' `train.g3.i12.n5`), else a readable head and a hash of the whole (`_common.prompt_tag`; rLLM's task ids hold `/`, and none of the providers documents a limit on tag values). The event log's rollout lines keep the whole key |
| `castform-attempt` | the rollout's attempt number (0, 1, ...) |

**Life.** With a marker, the life is derived from what the marker holds (`/.pcx/instance`: a hash
of its content; `/etc/hosts`: of content and mtime), read afresh at each `life()` call. So every
process in the container computes the same life, it changes exactly at a restore (Castform
compute writes the marker before the trainer runs again), and a rollout that starts after a
restore is in the new life even before any process noticed the restore. With the clock, it is
random per process and renewed when the process detects a restore. **A rollout is from an older
life when `rollout.life != life()`**; everything that discards uses that test.

A marker read that fails is tried again, 6 reads over about 100 ms, before the error counts: a
transient one would flip the life twice (to the error and back), and each flip discards every
rollout in flight. An error that persists is reported once (`marker_read_error`) and then taken
for what the marker holds, so a marker that appears, goes or becomes readable is a restore (a
false one only costs redone rollouts).

A sandbox's `castform-life` is its rollout's life, not `life()` at the create: a doomed rollout's
sandbox is then always in the sweep's scope, even when the adapter's own end of it is cut short by
the rollout's cancellation (the second sweep catches it).

**Scope.** A random id made once per container: the first process to need it creates
`STATE_DIR/scope` (written aside and hard-linked into place, so exactly one id wins and none is
read half-written), and every other process reads it. It is in the checkpoint, so a restore keeps
it, and every node and job has its own. A reused run name therefore never sweeps another live job,
and a multi-node job's nodes never sweep each other.

**Sweep scope.** With a marker: every sandbox tagged `castform-run=RUN` and `castform-scope=` this
scope whose `castform-life` isn't the current life. With the clock: the same, restricted to
`castform-lineage=` this process's lineage (lives aren't shared, so one process must not end
another's sandboxes). Never a sandbox tagged `castform-rollout=none`.

A sandbox created outside any rollout is tagged too (run, scope, life, lineage, and
`castform-rollout=none`), so the drill can count it, but never swept: the restored process may
still hold it. The library logs an `unprotected_sandbox` event for it: onboarding requires every
sandbox to be created inside the rollout that uses it.

**Safe creates.** A create the library retries must not make a second sandbox. Unless the
customer named it, a sandbox gets a name or key (`_common.safe_name`): a short readable prefix
(run, prompt, attempt, n), then a 16-character hash of (run, scope, life, lineage, prompt, attempt,
the rollout's `seq`, n), where n counts the creates in the attempt; at most 47 characters of
lowercase letters, digits and hyphens, which all three providers allow:
- Modal: `name`. A retry that fails because the name exists gets the first sandbox through
  `Sandbox.from_name`.
- E2B: `idempotency_key`. A retry with the same key returns the first sandbox.
- Daytona: `name`. A retry whose name is taken (409) gets the first sandbox with `get(name)`
  ("Provider adapters").

The life is in the hash, so a restored run never collides with the lost run's names. The `seq` is
too, because a custom driver can repeat a prompt key within one life, and (prompt, attempt) alone
would then hand the second rollout the first one's sandbox.

## Core interface

```python
# __init__.py
def _load(environ=None) -> None            # the import's side effect: settings; when on,
                                           # hooks.install() (looked up at call time, so tests
                                           # can replace it) and, with the log on,
                                           # emit("loaded"). Nothing else: no thread, and with
                                           # the log off no file (it runs in every process)
# config.py
@dataclass(frozen=True) class Settings: recovery; run; signal; log; state_dir; frameworks;
                                        .enabled
def from_env(environ=None) -> Settings     # raises ConfigError
def get() -> Settings                      # the active settings
def configure(settings: Settings) -> None
def paths(settings=None) -> dict[str, str] # the path settings, absolute (from_env makes them
                                           # so), by variable: what a Ray worker is given
# restore.py
def life() -> str                          # the current life (marker: read afresh each call)
def lineage() -> str                       # this process's lineage
def scope() -> str                         # this container's id (made at first use; raises
                                           # ConfigError if STATE_DIR can't be written)
def signal() -> str                        # the signal in use: "marker:PATH" or "clock"
def check() -> bool                        # read the signal now; True if this call saw a restore
                                           # (it starts the recovery, once per restore), or if
                                           # the caller is in a rollout from an older life or
                                           # doomed by a RolloutDiscarded
def look() -> str                          # check()'s read, returning the current life: one
                                           # read where check() then life() would be two
def start() -> None                        # start the poller unless it runs; idempotent, cheap
def on_restore(fn: Callable[[str, str], None]) -> None
                                           # fn(old_life, new_life), on the recovery thread
# rollouts.py
class RolloutDiscarded(Exception)          # raised inside a rollout that must stop (e.g. a
                                           # create that finished across a restore). Making one
                                           # inside a rollout marks the attempt discarded, so a
                                           # framework that catches it can't save the attempt.
                                           # End the attempt's sandboxes first: with no restore
                                           # behind it, no sweep runs
@dataclass class Rollout: prompt: str; attempt: int; life: str; seq: int; creates: int;
                          sandboxes: list[SandboxRef]; discarded: bool
def current() -> Rollout | None            # the rollout the calling code runs in (contextvar)
async def run_rollout(prompt: str, run: Callable[[], Awaitable[T]]) -> T
                                           # inside a rollout: just awaits run() (no nesting)
def orphans() -> int                       # discarded attempts whose task still runs
def rollout(fn=None, /, *, key: str | Callable | None = None)
                                           # @cr.rollout or @cr.rollout(key=...):
                                           # an async function as one rollout (below); the
                                           # key is optional
def stamp() -> dict | None                 # the rollout's identity: prompt, attempt, life,
                                           # lineage, seq (plain, picklable); None outside one
def trained(items, step: int) -> None      # the `trained` event: what a batch trained (Events)
                                           # stamp and trained: internal, not in the package's
                                           # API; the hooks and our tests call them (the drill)
STAMP = "castform_recovery"                # a sample's metadata key for its stamp (miles)
# sweep.py
def sweep(claim=None) -> int               # end the run's sandboxes of this scope from other
                                           # lives; claim(provider) -> bool picks the providers
                                           # (recovery passes none: all of them). An async
                                           # adapter's calls run on a loop of the sweep's own
# providers/__init__.py
@dataclass class SandboxRef: provider: str; id: str; tags: dict[str, str]
RUN, SCOPE, LIFE, LINEAGE, ROLLOUT, PROMPT, ATTEMPT   # the tag names; NO_ROLLOUT = "none"
class Adapter(Protocol):                   # what register() takes
    name: str
    def list_run(self, run: str) -> list[SandboxRef] | Awaitable[list[SandboxRef]]
                                           # live (and paused) sandboxes of the run
    def end(self, ref: SandboxRef) -> None | Awaitable[None]
                                           # idempotent; an already-ended sandbox is fine
    # list_run and end retry an unknown outcome and bound each call's time themselves;
    # either may be `async def` (a customer's adapter)
    # Optional, looked up when used (so not in the type): install(self) -> None, patch the
    # SDK (idempotent); reset(self) -> None, drop the SDK's connections and channels (no I/O)
def register(adapter: Adapter, *, install: bool = True) -> None
                                           # install: run its install() if any, and sweep with
                                           # it from now on. The built-ins pass False at import
def installed() -> list[Adapter]           # the adapters sweeps use: built-ins whose SDK this
                                           # process imported, and the customer's registered
def sandbox_tags() -> dict[str, str]       # a customer's create's tags (off the standard path)
def safe_name() -> str | None              # its name or key; both refuse a doomed rollout
# events.py
def emit(ev: str, **fields) -> None        # one JSON line: t, pid, run, life, lineage, ev, fields
```

**`run_rollout(prompt, run)`** calls `run()` (which must build fresh inputs each time: the
framework hook deep-copies its sample) as a task in a context where `current()` is a new
`Rollout(prompt, attempt, life(), seq)`, and:
- returns its result if the attempt is not from an older life and wasn't discarded (`check()`
  again at the end, then `rollout.life != life()`);
- discards and calls `run()` again with `attempt + 1` if a restore happened while it ran, whether
  it was cancelled, returned, or raised meanwhile (a timer armed before the checkpoint fires at
  the restore, so a result or error from across a restore is never trusted). This never
  depends on an exception reaching `run_rollout`: verl's `_call_tool` turns every exception into
  an observation. Restores never count towards a cap: a restore discards each rollout at most
  once. A `RolloutDiscarded` with no restore behind it reruns the rollout too; at the 20th such
  discard (`MAX_REFUSALS`), `run_rollout` emits `attempt_cap` and raises that `RolloutDiscarded`
  (miles drops the rollout's group on it);
- never awaits a discarded attempt: it waits for "the attempt finished, or a recovery discarded
  it", starts the next attempt at once, and leaves the old task to end on its own, an orphan. A
  cancelled attempt's cleanup can hang on a dead connection (verl releases its tools in a
  `finally`, Harbor shields `env.stop()`), and so can a sync call in a pool thread. The task's
  done callback consumes its outcome (asyncio logs nothing) and emits `orphan_end` with the
  seconds since it was let go; `orphans()` counts those still running;
- passes any other exception through unchanged, and passes cancellation from outside (the
  framework aborting its own rollouts) through as cancellation: it cancels the attempt and waits
  for it as a plain `await` would, but not past a restore. Its `rollout_end` says
  `across_restore: true` if the life changed during the attempt (a framework timer firing at the
  restore);
- with recovery off, just awaits `run()`;
- inside a rollout, just awaits `run()` as part of it: rollouts never nest, and a restore reruns
  the outer one. (verl's hooks rely on this, and a customer's marked function may run inside a
  hooked framework's rollout.) Inside means in a rollout still running, or in a discarded one,
  whose leftover work stays part of it and is refused at a create. A task a rollout started and
  left running keeps the finished rollout in its context; a call from there is a new rollout.

**Recovery** (once per restore per process, on a recovery thread of its own, never on an event
loop; a second restore during it gets a recovery of its own, and both act on the current life):
1. the new life;
2. `reset()` on each installed adapter that has one: the SDKs' connections predate the restore
   and are dead. First, before the discard starts the redone attempts: their creates must not
   reach a dead channel (one would hang until its keepalive gives up). It does no I/O;
3. every registered rollout from an older life is marked discarded, and its task cancelled with
   `loop.call_soon_threadsafe`. Recovery never awaits it: a call that was out at the checkpoint
   hangs on a dead connection;
4. the `on_restore` callbacks;
5. `sweep()`, then a second sweep about 5 s later to catch a create that was still on its way.
   The lost run's sandboxes hold the provider's quota (a Daytona organization's CPU limit, E2B's
   concurrency) until this first sweep ends them, and the redone rollouts all create at once:
   so creates in the new life wait for this process's first sweep, at most `SWEEP_WAIT` (10 s)
   after the restore was detected, not per create (a drill on a Daytona organization capped at
   10 CPUs had creates refused in the second before the sweep, without the wait).
   Sweeps run on the recovery thread with the providers' sync APIs. The adapters retry and bound
   each list and end (30 s on a thread of its own, `_common.bounded`), and ends run 16 at a time.
   A customer's async adapter (`async def list_run` or `end`) runs on an event loop the sweep
   makes for itself on the recovery thread, never the customer's loop, its ends 16 at a time; a
   call still running after `sweep.ASYNC_LIMIT` (300 s, a backstop) is cancelled and not
   awaited.
   A failure is a `sweep_failed` event, and the second sweep tries again. Every process that
   recovers sweeps, all its adapters, even though with a marker they all sweep the same scope:
   each adapter lists and ends with the credentials that process's creates used, so one process
   can't sweep for another (verl's workers may hold different tokens, or none yet). Ends are
   idempotent and listings cheap. With the clock each process sweeps its own lineage.

Restores are detected by a daemon thread polling `check()` every 0.5 s. It starts at first use
(`restore.start()`, which `run_rollout` calls), never at import:
with the `.pth` route the import runs in every Python process of the job, and a thread there
would be in every process that forks later. Until it runs, the end-of-rollout check and the
adapters' checks before and after each create detect restores. With the clock, only a process
whose poller runs takes a gap for a restore. Any code may also call `check()` before using a
reply. Detection is thread-safe and starts recovery once per restore.

**Fork.** A forked child is another process: it gets a new lineage (and with the clock a new
life), new locks (the core's, the hooks', the adapters'), and none of the parent's poller,
recovery threads, registered rollouts or reaper jobs (the parent goes on reaping its own; an E2B
job sends the create again). It keeps the scope (same container). If it runs rollouts it starts
its own poller.

## Provider adapters

`providers/modal.py` (modal 1.5 and 1.6), `providers/e2b.py` (e2b 2.61 and later 2.x) and
`providers/daytona.py` (daytona 0.184 and later 0.x), with what they share in
`providers/_common.py`. Each module registers its adapter on import; its
`install(module)`, which hooks calls, patches the SDK once.

`install()` wraps the SDKs' sync and async creates (Modal `Sandbox.create` and its `.aio`; E2B
`Sandbox.create` and `AsyncSandbox.create`, which subclasses inherit; Daytona `Daytona.create` and
`AsyncDaytona.create`) and their ends (Modal `terminate`; E2B `kill` as instance and class method,
through `SandboxApi._cls_kill`; Daytona `Sandbox.delete` and `AsyncSandbox.delete`). Inside a
rollout the create wrapper:
1. calls `check()`: a doomed rollout makes no sandbox (`RolloutDiscarded`). Right after a
   restore it waits for the recovery's first sweep (step 5 above; an async create awaits it, so
   the event loop runs on), logs `sweep_wait`, and calls `check()` again;
2. adds the tags (Daytona: labels) and, unless the customer gave one, the safe name or key.
   Daytona's go on a copy of the create's params: Harbor sends the same params object again
   when it retries a create;
3. retries a failure whose outcome is unknown (network, timeout, 5xx) idempotently, up to 5 times
   1 s apart, with a `check()` before each retry. A retry whose name is taken gets that sandbox
   only if it's this create's: always under the safe name, and under the customer's own name
   only if it carries this create's tags (after a restore the rerun reuses the discarded
   attempt's name, and that sandbox is the sweep's to end). Modal looks names up in the app's
   environment;
4. emits `sandbox_create` (Modal: with the app id) and records the sandbox on the rollout;
5. calls `check()`. If a restore happened during the create, it ends the sandbox and raises
   `RolloutDiscarded`.

A create that was cancelled, or failed with an unknown outcome and wasn't retried, may still make
its sandbox, possibly after both sweeps (a Modal create can build an image first). Its safe name
or key goes to a reaper thread, which ends the sandbox once it exists, trying 16 lost creates at a
time (on daemon threads, so a try that hangs never holds the job's exit): Modal by `from_name` (in
the app's environment) until the create's `timeout` plus 10 minutes; E2B by sending the same create
(same key) again and killing what it returns; Daytona by getting the name from the REST API until
the create's `timeout` plus 10 minutes (an hour with `timeout=0`), and deleting it. The customer's
own name or key only once their rollout spans a restore (before that their code may retry under it
and use the sandbox; Harbor names every sandbox), and then it ends only a sandbox that carries this
create's tags (metadata): a name or key the customer reused since belongs to their newer sandbox.

Outside a rollout a create gets `castform-run`, `castform-scope`, the current life, the lineage
and `castform-rollout=none` (no name, no retries), and the `unprotected_sandbox` event.

Ends emit `sandbox_end` (`by`: `client`; `restore` for a create across one; `reaper`), after a
`check()`, so a restore is noticed before the customer's code goes on.

**Credentials.** Sweeps don't use whatever credentials the process holds when they run: some
customers put the provider's token in the environment only while rollouts run (setting
`MODAL_TOKEN_ID` around each rollout, say), and a trainer VM may have no `~/.modal.toml`. Each
create records the credentials it resolves to, one entry per distinct set, in memory (so in the
checkpoint):
- Modal: the token (or OAuth) credentials and server URL of the client the create uses (its
  `client`, else its app's, else the environment client's, else the config's). Sweeps and the
  reaper use a client of their own per set, built from them.
- E2B: the API key, domain and API URL the create resolves to (from its params, an `e2b.E2B`
  client, or the environment).
- Daytona: the API URL and API key (or JWT and organization) of the `Daytona` or `AsyncDaytona`
  client the create uses, as it resolved them (config, environment or `.env`). Sweeps and the
  reaper call the REST API (`daytona_api_client`) with a client of their own per set: a new
  `Daytona()` would also open the SDK's event websocket.

Events never carry a secret: `sandbox_create` has `creds`, the first 8 hex digits of a sha256 of
the set, to tell sets apart. A process that created nothing lists with the provider's defaults
(E2B and Daytona: the environment's key; Modal: nothing, since it lists only by app, unless the
drill gives it apps).

For sweeps, sync, each call bounded (30 s: a call on a dead connection is abandoned and retried):
- `reset()` makes the next calls open new connections: the sweep's, and the customer's, whose first
  creates after a restore would otherwise hang on the dead channels too. Modal: the sweep clients
  are dropped, not closed (closing would touch the dead channels), and rebuilt from the recorded
  credentials. The customer's clients (each one a create used, and the environment client) each
  get a fresh connection manager, swapped in with one assignment: Modal's stubs take a channel
  from it at every call, so each client's next call opens a new connection with its own stored
  credentials, and the clients are otherwise unchanged (the environment client stays the
  singleton). Not Modal's after-fork path (marking the clients as from another pid): it clears
  the client's connection manager and control-plane stub, then awaits a reopen, and a call
  meanwhile fails an assertion, while after a restore an asyncio trainer's redone rollouts all
  create at once.
  E2B: its pooled transports are dropped. Daytona: every client a create used (Harbor's
  `AsyncDaytona` is a process-wide singleton; verl-recipe ReTool keeps one per worker) forgets
  its connections: an `AsyncDaytona`'s shared aiohttp session is dropped, unclosed, and the next
  call makes a new one on its own loop; a `Daytona`'s urllib3 pools are cleared. The SDK's event
  websocket reconnects by itself, and a create's wait for its sandbox to start also polls.
- `list_run` returns the sandboxes tagged with the run, running (E2B: and paused; Daytona: any
  not destroyed, since stopped and archived ones still cost storage), with their tags, checking
  the tag again client-side. Modal: by tag in every app a create used (its `app`, or in a Modal
  container the container's), with each credential set that created there; never across the
  environment, which Modal deprecated in 2026-08. The lost run may have created in an app after
  the checkpoint that the restored process's memory doesn't have: the first create there after
  a restore sweeps that app at once, on a thread of its own. E2B and Daytona: every page, with
  each credential set.
- `end` is idempotent, and uses the credentials the sandbox was created or listed with.

Not covered, so neither tagged nor reported: Modal's private creates (`_create`,
`_experimental_create`, `_experimental_from_snapshot`); E2B `fork`, which takes no metadata;
Daytona's private `_create` and a sandbox claimed from a warm pool (not created by the rollout);
a subclass's own `create` that doesn't call ours; a reference to `create` taken before install.

Daytona's creates are idempotent by name: a name is unique in an organization, so a retried
create whose name is taken (409) gets the first sandbox back with `get(name)`, once its labels
show it is this create's (and waits for it to start, as the create would have).

Seen against the real APIs (`tests/recovery/providers/test_providers_real.py`): E2B's listing can
lag a create or a kill by about a second; the second sweep covers that. Daytona (API v0.229, SDK
0.227) refuses a delete while the sandbox changes state: 409 "Sandbox state change in progress",
also for a second delete of one already destroying. `end` counts destroying as done, and waits up
to a minute for a sandbox still starting or stopping before deleting it; the reaper tries again
later instead.

## Framework hooks and loading

- **miles 0.1.0 to 0.1.3, and main:** a rollout is one `generate_and_rm` call
  (`miles/rollout/inference_rollout/inference_rollout_common.py`, and `sglang_rollout.py`'s on the
  legacy and multi-LoRA paths), with a deep copy of the sample and sampling parameters for each
  attempt. Every call site goes through the wrapper, including names bound by `from ... import`;
  `hooks/miles.py` lists them and what isn't covered (`--group-rm`'s reward model, customer
  rollout functions). The prompt key is the sample's identity plus a call number,
  `train.g<group_index>.i<index>.n<k>` or `eval.i<index>.n<k>`. miles reuses an index (eval
  datasets each count from 0 and run concurrently; fully async recycling and partial rollout
  generate a sample again), and two rollouts with one key and attempt in one life would get one
  safe name. With the event log on, the kept sample carries its stamp,
  `metadata["castform_recovery"] = {prompt, attempt, life, lineage, seq}` (`rollouts.stamp()`), for
  the drill. The trained record: `RolloutManager._get_rollout_data(rollout_id)`
  (`miles/ray/rollout/rollout_manager.py`; from 0.1.1, which split the RolloutManager,
  `RolloutExecutor._get_rollout_data` in `rollout_executor.py`, called by `get`) returns the samples
  handed to training, after miles' filters and the batch trim, for every training loop and never
  for eval; its wrapper calls `trained(samples, step=rollout_id)` (samples with `remove_sample`
  left out; 0.1.2 adds `trainer_model_id`, and 0.1.3 calls it from `_generate_rollout_data`). In
  0.1.0 and 0.1.1 the class is a Ray actor class, and the patch is on the class Ray makes and
  pickles into the actor; from 0.1.2 miles starts it by name in its own worker process, whose
  import of it is patched. **From 0.1.2 a job with an agent function must pass
  `--custom-agent-function-mode inline`**: miles' default, `subproc`, runs each agent call in a
  child process of its own, where its sandboxes would be made outside the rollout, untagged and
  never swept; the hook refuses it at the first call. miles' main still calls itself 0.1.3, so
  every 0.1.x is taken and the shape checks refuse code that moved.
- **verl 0.9.1 and main (0.10.0.dev, unchanged where the hooks patch):** a rollout is one
  `AgentLoopWorker._run_agent_loop` call
  (`verl/experimental/agent_loop/agent_loop.py:661-695`). With the event log on, each output an
  agent loop's `run` returns inside a rollout gets the stamp in `extra_fields["castform_recovery"]`, so it reaches
  the batch (`non_tensor_batch`) and TransferQueue (v1) with the output. The trained record, with
  the trainer's `global_steps`: the v1 trainer's `PPOTrainer.step()` (the default; one line per
  step, stamps read from TransferQueue, padding left out), and the legacy
  `RayPPOTrainer._update_actor(batch)` with its subclasses (fully async, one-step-off; a
  critic-warmup step isn't reported).
- **The stamp and the trained record only with the event log on.** They only feed the drill,
  which reads the log, so with `CASTFORM_RECOVERY_LOG` unset (a customer's job) the hooks don't
  stamp miles' samples or verl's outputs, and leave miles' rollout actor and verl's trainers
  alone without checking their shape: a framework that changed them can't stop a job that doesn't
  record. Recovery itself never reads a stamp. The rollouts' patches and checks are the same either
  way, and so are the version checks. Our restore tests set the log, so they still refuse a
  changed trainer at startup.
- **Loading.** The customer installs `castform` (no extra) and sets
  `CASTFORM_RECOVERY=resample` and `CASTFORM_RECOVERY_RUN`; no code.
  `castform_recovery.pth`, at the root of site-packages, imports `castform_recovery_boot` at the
  startup of every Python process of the environment, Ray workers included, when
  `CASTFORM_RECOVERY` is on. Its one line tests the variable before importing anything, so with
  recovery off it costs an environment lookup. The variables must reach the workers. On Ray the
  library does that itself (hooks/ray_env.py): it adds the driver's `CASTFORM_RECOVERY*` variables
  to `ray.init`'s `runtime_env` `env_vars` (the job's own values win; paths made absolute, as the
  driver resolved them), so a framework's list of forwarded variables needs no edit, and workers
  of a cluster started elsewhere (`ray start`, KubeRay), which don't inherit the driver's
  environment, get them too. A driver started by `ray job submit` needs them in its own
  environment (`--runtime-env-json`, with absolute paths: Ray passes those as given): miles' launcher
  starts the driver that way, so with it pass them in its `extra_env_vars`. verl also loads
  `castform_recovery_boot` through its `verl.plugins` entry point, on `import verl`.
- **The import line** `import castform.recovery` is the fallback for a process where neither
  runs (`python -S`, the package outside site-packages, `VERL_USE_EXTERNAL_PLUGINS=none`). It
  must run before the first rollout. On miles, the module named by
  `--custom-generate-function-path` is in time: GenerateState imports it when the RolloutManager
  starts. The one named by `--custom-agent-function-path` isn't: miles imports it inside the first
  rollout, after the first wave of `generate_and_rm` calls has started unwrapped. On the agentic
  path the agent module therefore also re-exports
  `from miles.rollout.generate_hub.agentic_tool_call import generate`, and the job passes
  `--custom-generate-function-path <agent module>.generate`. A hook installed while calls are
  already running logs a warning that says how many.
- **`hooks.install()`** puts a `sys.meta_path` finder first. Each TARGETS module is patched once
  it has finished executing, with the module passed to its patch function. Modules already
  imported are patched at once. Each rollout puts the finder first again if another library's
  import hook went ahead of it since (`hooks.keep_first()`, one comparison otherwise), and patches
  a target that hook imported meanwhile. Thread pools (`ThreadPoolExecutor.submit`, so also
  `loop.run_in_executor`) run what a rollout submits in a copy of its context, as
  `asyncio.to_thread` already does. miles' tb2 Modal example needs this: it creates its sandbox
  from a one-worker pool inside `to_thread`. `threading.Thread` doesn't carry the rollout: a
  long-lived thread started lazily inside a rollout (Modal's synchronicity loop) would keep it for
  good. A thread started inside a rollout is logged, once per thread function.
- **Failures with recovery on stop the job before any rollout.**
  - An unsupported or unknown version of a hooked package fails its import. `SUPPORTED`: miles 0.1.x
    (from 0.1.2 with `--custom-agent-function-mode inline`), verl 0.9.1 or main (0.10.0.dev), modal
    1.5 or 1.6, e2b 2.61 or any later 2.x (E2B ships a minor release every few days; the adapter
    checks at install that the e2b has idempotent creates and the transport pools it resets, and
    refuses one without), daytona 0.184 or any later 0.x (checked at install the same way). The
    refusal names the ways out: a supported version; for miles and verl,
    `CASTFORM_RECOVERY_FRAMEWORKS=off` with the rollouts marked; or recovery off. The version
    comes from the package's `__version__`, else its distribution's metadata. A miles source
    checkout without metadata is unknown, so install it with pip. With
    `CASTFORM_RECOVERY_FRAMEWORKS=off`, miles and verl aren't hooked, so neither is checked. Only
    an import is refused: an SDK installed at another version (a dependency's pin)
    that the job never imports is harmless, and only reported (`loaded`'s `unsupported`).
  - The refusal, `hooks.UnsupportedVersion`, is a `BaseException`, as `KeyboardInterrupt` is, and
    is printed and logged (`unsupported_version`) before it's raised. A provider SDK is often
    imported lazily inside the first rollout, where an `except Exception` (a retry loop, an error
    turned into a zero reward) would catch an `Exception` and run the job on, unprotected (miles,
    for one, would refill its batches for ever).
  - A load that fails at startup (a bad setting, say) can't stop anything there: `site` prints a
    failing `.pth` line and carries on, and verl logs a failing plugin at debug level. So
    `castform_recovery_boot` prints the error, keeps it, and makes the rollout modules (miles'
    `inference_rollout_common` and `sglang_rollout`, verl's `agent_loop`) refuse to import,
    raising a RuntimeError with the error. With `CASTFORM_RECOVERY_FRAMEWORKS=off` it refuses
    nothing (those modules don't run the rollouts then): the `@cr.rollout` module's own
    `import castform.recovery` raises the error.
  - An error from a late import line inside a miles rollout is swallowed: `generate_rollout_async`
    logs the failed group and submits more, indefinitely. That's one more reason the import line
    can't be the agentic path's route.

## Using castform.recovery off the standard path

On stock miles 0.1.x (inline agent calls from 0.1.2) or verl 0.9.1 or main, with Modal, E2B or
Daytona, the customer installs the package and sets the environment, and writes no code. This
section is for everyone else: another framework or their own trainer (SkyRL, rLLM, a custom
asyncio loop), or another provider (a Cloudflare bridge, AWS, their own service), or an
unsupported version of miles or verl (with `CASTFORM_RECOVERY_FRAMEWORKS=off`, below). Loading is
the same: install `castform` and set `CASTFORM_RECOVERY=resample` and
`CASTFORM_RECOVERY_RUN` (and, for an unsupported miles or verl, `CASTFORM_RECOVERY_FRAMEWORKS=off`),
then check the job's logs for the line in "Is it on?". Load the library through the environment:
loading installs the hooks, so Modal, E2B and Daytona creates are tagged and thread pools carry
the rollout. `config.configure()` alone doesn't. The public names are in `castform.recovery`;
`cr.` below means `import castform.recovery as cr`. With recovery off, each one changes nothing
(see each).

### Rollouts: `@cr.rollout`

```python
import castform.recovery as cr


@cr.rollout
async def run_group(step, task, n): ...
```


The library calls each call of a marked function a rollout.

- **Mark the unit your code runs, retries and publishes as one.** That's a trajectory, or a group
  when the code makes the group as one unit (one call producing n samples, a GRPO group, say). A
  restore then reruns the whole group. Mark it wide enough to enclose the code that turns
  failures into training data (timeouts, masking, reward defaults).
- **The rerun happens inside the marked call.** When a restore discards an attempt, the library
  cancels it (`CancelledError` inside the function, so `finally` blocks run) and calls the
  function again, with the same arguments, as the next attempt, before the call returns. An
  attempt that returned or raised across a restore is discarded the same way (a timer armed
  before the checkpoint fires at the restore: a restore advances the clock by the time the job
  was frozen). The caller gets exactly one result, as in an uninterrupted run. **The
  caller never sees a discard.** There is no exception to catch, nothing to put before a retry
  handler, `TaskGroup` or `gather`, and no resample to write. Don't count a restore against a
  retry budget: it never reaches one. What does reach the caller: the function's own exceptions
  when no restore is behind them, unchanged; cancellation from outside; and `RolloutDiscarded`
  once a call has had 20 discards with no restore behind them (`MAX_REFUSALS`: a bug, not a
  restore).
- **The key names one draw of the prompt or group** in the sandboxes' `castform-prompt` tag. It
  is computed once per call, before the first attempt, so every attempt of a call has the same
  one. Without `key=`, it is the function's name, the process's lineage and a call number
  (`"Runner.run_group.3fa9c2d1.17"`): unique per call in the run, which is all a restore needs.
  `key=` is optional and recovery doesn't need it: built from your own ids (include the step or
  epoch), it makes the tags readable. It is a format string over the function's parameters
  (`"{step}.{task.id}"`, `"{batch[0]}"`, `**kwargs` entries by name; checked when decorating), or
  a function called with the call's own arguments (`self` too, for a method) that returns it.
- Async functions only: an attempt must be a task the library can cancel. Run sync code with
  `asyncio.to_thread` inside the function. A thread can't be cancelled: it runs on after a
  discard, its result is dropped, and its sandbox creates are refused (below).
- Each attempt gets the same arguments: copy what the function writes into, at its top. Or use
  `await cr.run_rollout(prompt, run)`, with the key as `prompt` and as `run` a no-argument async
  function (a closure) that builds fresh inputs.
- Rollouts never nest: a marked call inside a running rollout (a hooked framework's too) is a
  plain call, part of the outer rollout.
- With recovery off, a marked call is a plain call, and the key isn't computed.

### Fresh ids for a rerun: `cr.current()`

`cr.current()` is the calling code's rollout, with `.prompt`, `.attempt` (0, 1, ...), `.life` and
`.seq`; None outside any rollout, and always with recovery off. Treat it as read-only.

A rerun must not reuse an id that keys state outside its own process: a sandbox or trial name,
a tool's registry entry, a model gateway session. Otherwise it gets the lost attempt's state back,
or a sandbox the sweep is ending. Harbor names its Modal sandbox `<trial>__env`, and verl's
SWE-bench tool keys its sandbox registry on `request_id`. Keep the ids the trainer groups and
orders samples by (prompt id, group id, sample index). The simplest fresh id is a random one made
inside the marked function (`uuid.uuid4()`), or `cr.safe_name()`. A deterministic id needs the
life as well as the attempt (`r = cr.current()`, then `f"{trial}-a{r.attempt}-{r.life}"`): the
restored run's attempts count from the same numbers as the lost run's.

### Another provider: `cr.providers.register(adapter)`

The library patches Modal's, E2B's and Daytona's creates. For any other provider, the customer:

1. gives each create inside a rollout `cr.sandbox_tags()`, merged into its labels or metadata,
   and `cr.safe_name()` as its name or idempotency key;
2. writes an adapter the sweep uses to list the run's sandboxes by tag and end them, and
   registers it with `cr.providers.register(adapter)` in every process that creates the
   provider's sandboxes (each process sweeps with the credentials it saw), before its first
   create.

There's no per-sandbox registration. The sweep has to find what the lost run created after the
checkpoint, and only listing the provider by tag can: a registration made in that timeline no
longer exists. A registry also has no "ended" signal, and verl's ToolAgentLoop with per-call
tools creates a sandbox per code cell.

`sandbox_tags()` returns, inside a rollout, the run, scope, the rollout's life, lineage, prompt
and attempt ("Identity and tags"). The adapter's `list_run` must return them as each
`SandboxRef`'s tags: the sweep picks the sandboxes it ends by them. `castform-prompt` is the
rollout's key, made a safe tag value when it isn't one ("Identity and tags"). Outside any rollout
it returns
the run, scope, current life, lineage and `castform-rollout=none`, which the sweep never ends;
with recovery off, `{}`. `safe_name()` returns the next create's name, as the built-in adapters
make them: at most 47 characters of lowercase letters, digits and hyphens, unique per create,
attempt, life and run. Call it once per create, and send the same value on that create's
retries, so a retry never makes a second sandbox. It returns None outside any rollout and with
recovery off (keep your own name then). Both raise `RolloutDiscarded` in a rollout from before a
restore: a doomed attempt must make no sandbox, since the sweeps may be over. The attempt is
rerun. Right after a restore both also wait for the recovery's first sweep, as the built-in
creates do (10 s at most after the restore): it frees the provider quota the lost run's
sandboxes hold. The wait blocks, so on an event loop it holds the loop for that time.

**The adapter's contract** (`providers.Adapter`):
- `name`, `list_run(run)` and `end(ref)` are required; `install()` (run at `register`) and
  `reset()` (run before a recovery's sweep; no I/O) are optional.
- `reset()` is also where the customer's own long-lived clients of the provider go stale: a
  client kept across the restore (verl-recipe ReTool keeps a Daytona client per worker) holds
  dead connections, so the redone rollouts' calls fail, and a framework that turns tool errors
  into observations trains on them. Have `reset()` drop or rebuild such clients (no I/O), or make
  a new client per rollout.
- `list_run(run)` returns the run's live and paused sandboxes as `SandboxRef(provider, id,
  tags)` (`provider` is the adapter's `name`), listing by the `castform-run` tag (and checking it
  again client-side), every page.
- `end(ref)` ends one. **"Not found" or already stopped counts as done**: return normally.
- **Both may run after a restore**, on the recovery thread. Every connection from before the
  restore is dead and may hang without an error, so each call opens fresh connections (no
  client kept from before), bounds its time (30 s, say), and retries an unknown outcome. They
  **carry their own credentials, captured at create**: the customer's code may have set the
  token only while its rollouts ran (setting `MODAL_TOKEN_ID` around each rollout, say), and a
  sweep runs outside that.
- **Either may be `async def`.** Coroutines run on an event loop the sweep makes for itself on the
  recovery thread, never the customer's loop. A call still running after 300 s is cancelled and
  abandoned (`sweep.ASYNC_LIMIT`, a backstop). A sync call has no backstop: bound it yourself.
- A provider that can't list by label (a Cloudflare bridge, say) can't be
  swept: the lost run's sandboxes end only at their own timeout (`sleepAfter`). Say so at
  onboarding, and keep that timeout short.

### An unsupported version of miles or verl: `CASTFORM_RECOVERY_FRAMEWORKS=off`

With recovery on, the hooks refuse a miles or verl they weren't written for (`UnsupportedVersion`),
and verl's trainer imports the hooked agent loop module (`ray_trainer.py`) whether or not the job
uses it. A job on another version (a verl 0.7 fork, say) sets
`CASTFORM_RECOVERY_FRAMEWORKS=off` and marks its rollouts with `@cr.rollout` itself:

- The framework hooks are skipped in every process, with their version and shape checks: the
  `.pth`, verl's plugin entry point and an import line all load the library the same way. A
  module the framework hooks target, imported anyway, logs one warning naming it: its rollouts
  are protected only where they are marked.
- Everything else stays: the Modal, E2B and Daytona hooks, thread pools carrying the rollout, restore
  detection, sweeps. The `loaded` event says `frameworks: "off"`.
- What the framework hooks did for each rollout is now the marked function's to do: copy its
  inputs before writing into them, and make fresh external ids from `cr.current()`. (verl's
  hook appends `-a{attempt}` to request ids; the SWE-bench tool keys its sandbox registry on the
  request id, so the marked function must give each attempt a fresh one.)
- With the framework hooks off, a failed load (a bad setting) doesn't make miles' and verl's
  modules refuse to import: the `@cr.rollout` module's own `import castform.recovery` raises the
  error instead, before any rollout.

### Worked example: a custom asyncio trainer

```python
import asyncio
import uuid

import castform.recovery as cr


@cr.rollout(key="{step}.{task.id}")  # optional (a bare @cr.rollout works)
async def run_group(step, task, n):
    # A fresh trial id per attempt: a rerun never gets the swept sandbox back by name.
    trial = f"{task.id}-{uuid.uuid4().hex[:8]}"
    return await asyncio.gather(*(run_one(task, f"{trial}-{i}") for i in range(n)))


async def train(trainer, tasks, n):
    while trainer.step < trainer.max_steps:  # trainer.step is in the checkpoint
        step = trainer.step
        # One result per group. A restore's rerun happens inside run_group: nothing to catch.
        groups = await asyncio.gather(*(run_group(step, t, n) for t in tasks.batch(step)))
        trainer.update(groups)
        trainer.step = step + 1
```

`run_one()` creates its sandbox inside the rollout. With Modal, E2B or Daytona that's all; with another
provider, its create looks like the next example's.

### Worked example: a custom provider

A sandbox service over HTTP (an illustration, not a real SDK) with labels, names, listing by label
and delete:

```python
import os

import httpx

import castform.recovery as cr
from castform.recovery.providers import RUN, SandboxRef

API = "https://sandboxes.example.com/v1"


def client(key):
    # A new client per call: after a restore, every connection from before it is dead.
    return httpx.AsyncClient(base_url=API, headers={"Authorization": f"Bearer {key}"}, timeout=30)


class AcmeAdapter:
    name = "acme"

    def __init__(self):
        self.keys = set()  # every API key a create used: in memory, so in the checkpoint
        self.key_of = {}  # sandbox id -> its key

    async def list_run(self, run):
        refs = []
        # A create may add a key meanwhile. A process that created nothing lists with the
        # environment's key, if it has one (a check run outside the job, say).
        keys = list(self.keys) or [k for k in [os.environ.get("ACME_API_KEY")] if k]
        for key in keys:
            async with client(key) as c:
                r = await c.get("/sandboxes", params={"label": f"{RUN}={run}"})
                r.raise_for_status()
            for sb in r.json()["sandboxes"]:
                if sb["labels"].get(RUN) == run:
                    self.key_of[sb["id"]] = key
                    refs.append(SandboxRef(self.name, sb["id"], sb["labels"]))
        return refs

    async def end(self, ref):
        async with client(self.key_of[ref.id]) as c:
            r = await c.delete(f"/sandboxes/{ref.id}")
        if r.status_code != 404:  # already gone counts as done
            r.raise_for_status()


ACME = AcmeAdapter()
cr.providers.register(ACME)  # in every process that creates acme sandboxes


async def create_sandbox(key, image):
    labels = {"team": "rl", **cr.sandbox_tags()}  # raises in a rollout from before a restore
    name = cr.safe_name()  # the same name on a retry: no second sandbox
    ACME.keys.add(key)  # before the create: a sweep may need it whatever happens next
    async with client(key) as c:
        r = await c.post("/sandboxes", json={"image": image, "name": name, "labels": labels})
        r.raise_for_status()
    sid = r.json()["id"]
    ACME.key_of[sid] = key
    return sid
```

Retries of unknown outcomes are left out for brevity: the built-in adapters retry 5 times, 1 s
apart, with the same name (`providers/_common.py`).

### What it doesn't cover

- Work in a raw `threading.Thread` doesn't carry the rollout (thread pools and
  `asyncio.to_thread` do), so its creates are outside any rollout: tagged
  `castform-rollout=none` and never swept.
- A create that returns after both sweeps, from an attempt the restore doomed between the
  create's check and its request, is tagged with the old life but not ended (the built-in
  adapters' reaper covers this for Modal, E2B and Daytona).
- A sweep finds only what the adapter lists: a provider without listing by label leaks the lost
  run's sandboxes until their own timeout.
- A rollout can't ask the library to drop or resample it. Code that means to drop a
  failed sample does so itself.

## Events (for the drill)

The event log (`CASTFORM_RECOVERY_LOG`) is for Castform's own testing and for support, like the
drill that reads it. A customer job doesn't need it.

`loaded` (signal; `frameworks`: `on` or `off`; `unsupported`: hooked packages installed at a
version the hooks don't support, as "e2b 2.25.0"), `unsupported_version` (a refused import:
package, version, error), `custom_create` (a call of `sandbox_tags()` or `safe_name()`, `via`;
in a rollout its prompt, attempt and `rollout_life`), `restore_detected` (old and new life, by
marker or clock; `frozen_s`: the wall-clock seconds from this process's last look before the
checkpoint to the look that saw the restore. Once its poller runs (from the process's first
rollout) that last look is at most 0.5 s before the checkpoint; a process that only calls `look()`
or `check()` may have last looked long before it; `mono_gap_s`: the same span by the
monotonic clock, about 0 on pcx, whose runsc hides a checkpoint's time from it),
`rollout_start`, `rollout_end` (`kept`, `discarded`, `error` or `cancelled`; `across_restore` on a
discard or cancellation; `orphan` when the discarded attempt still runs; `rollout_life`),
`sandbox_create` (provider, id, name, tags, `seq`, `creds`; `timeout`: the sandbox's lifetime in
seconds; Modal: `app_id`), `sandbox_end` (`by`), `unprotected_sandbox`, `reap_queued` (provider,
the safe name, seconds the reaper will look: a lost create handed to the reaper; its end, if
any, is a `sandbox_end` with `by=reaper`), `sweep_wait` (provider, `waited_s`: a create that
waited for the first sweep after a restore), `provider_error` (provider, `op`: `list` or `create`,
the error's type; a create's has the rollout's prompt, attempt, seq and `rollout_life`),
`swept` (provider, ids), `orphan_end` (prompt, attempt, seq, seconds since discard, orphans
left), `attempt_cap` (prompt, attempt, refusals, error), `marker_read_error` (path, error; with
the last life seen), and the recovery's own: `recovered` (old
and new life, rollouts discarded, sandboxes swept by this process, `reset`: the adapters reset
without error), `sweep_failed`, `reset_failed`, `on_restore_failed`; and `trained`, the
trainer's record of what it trained (below), and `trained_failed` (where, error: a hook's
trained record raised; the trainer's step went on, and the record is incomplete).
Every line has the run, life (the current one when written), lineage and pid; rollout lines have
the prompt, attempt and seq. The drill checks the log, the
provider's listing and the trainer's record of what it trained:
- no sandbox of the run left running;
- no prompt trained twice;
- no discarded attempt trained.

**The trained record.** A rollout's identity is its stamp, `rollouts.stamp()`: a plain,
picklable dict `{"prompt", "attempt", "life", "lineage", "seq"}`. It is kept with the rollout's
result until the result is trained: with the event log on, miles' hook puts it in the kept
sample's `metadata["castform_recovery"]` and verl's in the output's `extra_fields`.
`trained(items, step)`, called where the trainer consumes a batch, in any process, writes one
line per call. Neither is
in the package's API: the hooks call them, and so does a test of ours that drills a trainer off
the standard path (`from castform.recovery import rollouts`; without it the drill can't tell
whether a prompt was trained twice or a discarded attempt was trained):

```
{"ev": "trained", <t, pid, run, life, lineage>, "step": 12,
 "rollouts": [{"prompt": "12.g3", "attempt": 1, "life": "9c41e0aa", "lineage": "5d2b7f10",
               "seq": 815, "samples": 8}, ...],
 "unstamped": 0}
```

- `items`: stamps, Rollouts, or objects whose `.metadata["castform_recovery"]` holds a stamp,
  possibly nested in lists or tuples (groups). `rollouts` has one entry per distinct stamp, in
  the batch's order; `samples` counts the items with it (n for a group rollout). An entry's
  `life` and `lineage` are the rollout's; the line's own are the writing process's.
- `reward` (when the items carry one): the entry's samples' mean numeric `.reward` (a miles
  Sample's), so what redone rollouts (attempt > 0) scored can be set against first attempts.
- `unstamped`: items without a stamp (made outside any rollout, or with recovery off).
- `step` (required, an int): the training step or rollout id, increasing in an uninterrupted run.
  It is part of the trainer's checkpointed state, so after a restore it starts again from the
  checkpoint's value. The log isn't rolled back: the lost timeline's `trained` lines (written
  after the checkpoint) stay in it. The drill resolves the final timeline per step: the lives
  form a chain through `restore_detected` (old to new), and for each step the line from the
  latest life wins. A restored run trains every step after its checkpoint again, so the lost
  timeline's steps are always superseded.
- The drill's checks on the winning lines: no prompt key in two entries (trained twice); every
  entry has a `rollout_end` with the same lineage, seq, prompt, attempt and `rollout_life`, and
  all such lines are `kept` (else a discarded attempt was trained). The full key matters: seq is
  a per-process counter in the checkpoint, so timelines reuse it, and an attempt in flight at a
  leave-running checkpoint is `kept` in the lost timeline and `discarded` in the restored one
  under the same key. `unstamped > 0` fails the drill unless `--allow-unstamped`: items the
  library never saw, whose rollouts the checks can't cover.
- Who calls it: the miles and verl hooks, where the trainer consumes a batch ("Framework
  hooks"), with the event log on, and Castform's own tests. `trained()` takes miles' samples as
  they are.

## The restore drill

Castform's internal restore drill (`tests/recovery/drill/README.md`) reads the event log and the
providers' listing after forced restores; a customer job doesn't need it.

## Known limits

- Each node of a multi-node job has its own scope and sweeps only its own sandboxes. Whether a
  job's nodes are restored together is up to Castform compute, not this library.
- Without Castform compute's marker (`/.pcx`), a restore is detected only as a jump of more than
  5 s in the monotonic clock (`CASTFORM_RECOVERY_SIGNAL=clock`): a shorter gap is missed
  altogether, and so is every gap under pcx, whose runsc hides a checkpoint's time from the
  monotonic clock by default (`--checkpoint-clock-gap=hide`). On Castform compute the marker is
  always there.
- `restore_detected`'s `frozen_s` changed meaning in 0.3.0.dev0 (not released yet). It was the
  monotonic gap, which on pcx is about 0. It is now the wall-clock gap, and `mono_gap_s` holds
  what `frozen_s` used to.
- Modal is listed by app only. An app the lost run first used after the checkpoint isn't in the
  restored process's memory: it's swept only when the restored run creates in that app again
  (that first create sweeps it). If it never does, those sandboxes run until their own timeout.
  Harbor's Modal environment uses one app for every trial (`__harbor__` by default, through
  `App.lookup`), so Harbor jobs aren't affected; a job that makes a new app per task would be.
- The wait for the first sweep after a restore helps only if that sweep finishes within
  `SWEEP_WAIT` (10 s). If it takes longer, creates go ahead, and a job near its provider quota
  can have creates refused, which a framework may train on as error observations.
- A tool with effects outside its sandbox repeats them when its rollout is redone (onboarding asks
  the customer to name such tools).
- A remote trainer (Tinker, and Modal's Tinker-compatible API) keeps the weights and optimizer
  state on its own servers: a restore of the client's VM can't roll them back, so the restored run
  trains on from state the lost timeline changed. Out of scope (rLLM's CLI uses Tinker by
  default).
