external sandboxes

keep rl rollouts in modal, e2b, daytona, etc. working across preemptions.

training jobs sometimes rely on external sandboxes (modal, e2b, daytona, etc.) to execute tool calls generated by the llm being trained. those connections have to survive preemptions too. when a machine is preempted, castform compute restores your container on another machine and the job resumes where it was, but its open sandbox sessions drop.

we provide a decorator to handle this: add @cr.rollout (from castform.recovery) to your rollout function. after a preemption, it replays any rollouts that were in flight in new sandboxes and cleans up the old ones. stock miles and verl jobs don’t even need the decorator.

rollouts that run inside your container need nothing extra: the sdk overview is all you need.

what happens after a preemption

your container comes back as it was, but the sandboxes it was using don’t. two things need fixing, and the decorator does both:

after a preemptionwhat castform does
the rollouts that were in flight lost their sandboxesreplays each one from the start, in a new sandbox, inside the same call
their old sandboxes may still be running in your provider accountfinds them by a tag it added when they were created, and cleans them up

your trainer gets one result per rollout, as if nothing had happened. the container keeps its network address, so model servers and routers inside it stay reachable from your sandboxes.

what you need to do

your jobwhat to do
stock miles 0.1.x, or verl 0.9.1+, on modal, e2b, or daytonainstall the package and launch with recovery on. no code
any other framework, on modal, e2b, or daytonathe same, plus one decorator on your rollout function
another provider (a cloudflare bridge, aws, etc.)the same, plus a small adapter so castform can find and clean up its sandboxes

your coding agent can do all of it for you: see set up with your coding agent.

install

the decorator ships in castform, the same package as the sdk, so you install one package in two places:

pip install castform    # on the machine you launch from
uv add castform         # in your training repo: a dependency of the job
wherewhy
the machine you launch fromthe sdk: it builds the image and starts the container
your training job’s environmentcastform.recovery, so every process that runs rollouts has it

in your job, the package works on python 3.10 and up, and the decorator does nothing until recovery is on. if your job builds its own environment when it starts (uv run --isolated, a venv its script creates), add it there too, e.g. uv run --with castform ....

mark your rollout function

put @cr.rollout on the async function that runs one rollout, in the process that creates the sandboxes. that’s the whole code change:

import castform.recovery as cr

@cr.rollout
async def modal_rollout(prompt):    # your existing function, unchanged
    sandbox = await modal.Sandbox.create.aio(...)
    ...
  • one rollout per call. if the function also publishes or queues its result, mark the call at its caller instead: await cr.run_rollout(name, attempt), where attempt is a small async function that runs one rollout.
  • fresh names on each attempt. sandbox, trial and session names must be made inside the function, so that a replay gets new ones. most code already does this.
  • no key needed. castform names each call itself.

stock miles and verl need no decorator: castform finds their rollout function itself. on miles 0.1.2 or later, a job with an agent function also needs --custom-agent-function-mode inline.

launch on castform compute

you launch the same way as in the sdk overview: an image, a container and run(). a job with external sandboxes adds three things, marked 1 to 3:

import os, uuid
import castform

run = f"grpo-{uuid.uuid4().hex[:6]}"           # a new name for each launch

image = (
    castform.Image.from_registry("your-registry/trainer:tag")
    .pip_install("castform")           # 1. the package, for the job
    .add_local_dir(".", "/workspace/repo")
)

container = castform.Container(
    name=run,
    image=image,
    gpu="H100:1",
    working_dir="/workspace/repo",
    env={                                       # 2. recovery on
        "CASTFORM_RECOVERY": "resample",
        "CASTFORM_RECOVERY_RUN": run,
    },
    secrets=[castform.Secret.from_dict({        # 3. your provider's keys
        "MODAL_TOKEN_ID": os.environ["MODAL_TOKEN_ID"],
        "MODAL_TOKEN_SECRET": os.environ["MODAL_TOKEN_SECRET"],
    })],
)
container.run(["bash", "-lc", "bash train.sh"])

for text in container.logs(follow=True):
    print(text, end="")

then python launch.py, as in the overview.

addedwhy
1. castform in the imageso the job’s python has castform.recovery (see install)
2. two variables in envthey turn recovery on for this launch (below)
3. your provider’s keys in secretsyour sandboxes need them anyway. secrets keeps them encrypted

the two variables:

variablevalue
CASTFORM_RECOVERYresample turns recovery on. unset, the decorator does nothing
CASTFORM_RECOVERY_RUNa name unique to this launch, e.g. grpo-3f2a9c

every process in the container picks them up, ray workers included. already launch your job some other way (a yaml your team submits, a ci job)? set the two variables there instead.

good to know: the sdk refuses symbolic links in an uploaded folder. a CLAUDE.md that links to AGENTS.md is a common one: leave it out with add_local_dir(".", "/workspace/repo", exclude=["CLAUDE.md"]).

check it’s on

once the first rollouts start, look for this line in castform logs <container>:

castform.recovery: tracking rollouts (run grpo-3f2a9c)

if it never shows up, the decorator is on the wrong function, or the variables didn’t reach the processes that run rollouts.

optional extras

none of these are needed to survive preemptions: the decorator alone does that. leave them out unless you want what they give you.

extrawhat you getwhen you’d want it
readable rollout names (key=)sandbox names and tags in your provider’s dashboard show your own ids, e.g. prompt 1234rarely
clean retry metricscounters your rollout function writes into don’t mix a cut-off attempt’s counts with the replay’sif you track those counters on runs that were preempted

to add one, ask your coding agent for it by name. the details are in the recovery reference.

limits

  • provider quota: right after a preemption, the replays wait (up to 10 seconds) for castform to end the old sandboxes before they create new ones. a provider can still take a moment to free the old ones’ quota, and a few stragglers are ended a little later, so leave headroom: about twice your usual number of concurrent sandboxes is safe.
  • providers that can’t list sandboxes by tag (the cloudflare bridge, for one): after a preemption, the cut-off sandboxes keep running until their own timeout, so keep that timeout short.
  • sandboxes your job leaves running when it ends (a shutdown that kills rollouts in flight) are yours to clean up: castform only cleans up the ones a preemption cut off.
  • modal’s private create paths aren’t covered: a sandbox made through them is never tagged or ended. harbor uses one when its modal_sandbox_v2 option is on (miles’ harbor example turns it on with MODAL_SANDBOX_V2=1), so turn that off. harbor versions without that option (0.13.1, for example) are fine.
  • sandboxes made by forking or from a snapshot (e2b’s fork, for one) aren’t covered either: castform can’t tag them, so a preemption leaves the cut-off ones running until their own timeout. create each rollout’s sandboxes with the provider’s normal create call.

supported versions

packageversions
modal1.5 to 1.6
e2b2.61 and up
daytona0.184 and up
miles0.1.x
verl0.9.1 and main

other providers work through an adapter. a job that imports one of these packages at another version stops at that import with unsupported_version. one that has it installed but never imports it is unaffected.

on another version of miles or verl (a fork, say), set CASTFORM_RECOVERY_FRAMEWORKS=off with the other variables and mark your rollout function with @cr.rollout, as for any other framework.

set up with your coding agent

open your coding agent in your training repo, say what you want, and point it at this page:

set up scripts/train_grpo.sh to run on castform compute, one H100, with its
rollouts in modal sandboxes. follow
https://castform.dev/docs/external-sandboxes.md

it follows the instructions below, which you can also copy as a prompt. it ends with at most three commands for you to run, the last of them the launch.

instructions for coding agents
Set up this repo's RL training job to survive preemptions on Castform compute, with
`@cr.rollout`. Read the "external sandboxes" page first
(https://castform.dev/docs/external-sandboxes.md; these instructions are its
last section, and the sections named below are on it), then the recovery reference's "off the
standard path" and "Known limits" sections
(https://castform.dev/docs/castform-recovery.md). `cr.` means
`import castform.recovery as cr`, here and there. Make the smallest change that makes the job
correct. Don't run the repo's code or install anything.

1. Find only what the next steps need: the rollout function, which runs one rollout (or one
   group, if the code runs or retries the group as a unit), the process it runs in, the
   sandbox provider, how the job is launched, and, if it runs on miles or verl, their version
   in the lockfile. Don't check other versions: an unsupported one stops the job when it's
   imported, and a package that's installed but never imported doesn't matter.
2. Stock miles 0.1.x, or verl 0.9.1 or main, on Modal, E2B, or Daytona: no code ("mark your
   rollout function").
3. Otherwise put `@cr.rollout` (`import castform.recovery as cr`), with no key, on that
   function, as in "mark your rollout function". On miles or verl outside those versions (a
   fork, say), also set `CASTFORM_RECOVERY_FRAMEWORKS=off` with the other variables (step 9).
   - Don't change the function or its signature. If it also publishes or enqueues results,
     use `await cr.run_rollout(name, attempt)` at its caller instead, with a small async
     closure `attempt` that runs one rollout.
   - Check that ids keying state outside the process (sandbox, trial or session names) are
     made inside it, so each attempt gets new ones. Keep the ids samples are grouped by.
4. Add `castform` to the job's dependencies and import it unconditionally: it's on
   PyPI, and the decorator does nothing while CASTFORM_RECOVERY is unset. With a lockfile
   (uv.lock, poetry.lock), make re-locking (e.g. `uv lock`) the user's first next step. If the
   job builds its own environment at start (`uv run --isolated`, a venv its script creates),
   add it there too: `uv run --with "${CASTFORM_PACKAGE:-castform}" ...`.
   Don't edit the framework's list of forwarded environment variables: the library passes
   its settings to Ray's workers itself, also when the job never calls ray.init.
5. A provider other than Modal, E2B, or Daytona that can list sandboxes by label: write an
   adapter as in the reference's worked example. One that can't (the Cloudflare bridge, for
   one): no adapter; put it under "needs your decision" (see "limits").
6. Don't edit the framework's core files; use its extension points (subclasses, callbacks,
   plugins). Change nothing the user didn't ask for (model, batch sizes, GPU counts), except
   what running on the GPUs they asked for requires, and say so.
7. If you come across any of these, report it as a blocker rather than patching around it
   (don't go looking): a remote trainer (Tinker or similar); a warm pool of pre-created
   sandboxes; sandboxes made by forking another sandbox or from a snapshot (E2B's `fork`,
   for one); sandboxes shared across rollouts; sandbox lifetimes shorter than a rollout;
   tools with effects outside the sandbox; addresses the sandboxes use to reach the trainer
   that only exist on this machine.
8. Don't add the "optional extras" unless the user asks for them. Offer them in your final
   message instead.
9. Launch. If the job already has a launcher (its own platform, a yaml its team submits, CI),
   add the two variables from "launch on castform compute" to the environment it sets, with a
   CASTFORM_RECOVERY_RUN unique per launch, and write no new one. If it can't set environment
   variables, that's a blocker. Otherwise write launch_castform.py next to the job from this
   template, filling in the <...> parts:

   import importlib.metadata, json, os, secrets
   from pathlib import Path
   try:
       import tomllib
   except ModuleNotFoundError:                          # Python 3.10: castform installs tomli
       import tomli as tomllib
   from urllib.parse import unquote, urlsplit
   import castform

   REPO = Path(__file__).resolve().parents[<levels up to the repo root>]

   def castform_package(image):
       """castform as installed here: a local build goes into the image."""
       try:
           dist = importlib.metadata.distribution("castform")
       except importlib.metadata.PackageNotFoundError:   # not installed here: use PyPI
           return image, "castform"
       url = json.loads(dist.read_text("direct_url.json") or "{}").get("url", "")
       if not url.startswith("file://"):
           return image, "castform"
       path = Path(unquote(urlsplit(url).path))
       add = image.add_local_dir if path.is_dir() else image.add_local_file
       return add(path, f"/opt/{path.name}", copy=True), f"/opt/{path.name}"

   def modal_credentials():
       """From the environment, else the active profile in ~/.modal.toml (`modal setup` writes it)."""
       if os.environ.get("MODAL_TOKEN_ID"):
           return {k: os.environ[k] for k in ("MODAL_TOKEN_ID", "MODAL_TOKEN_SECRET")}
       profiles = tomllib.loads((Path.home() / ".modal.toml").read_text())
       p = next((v for v in profiles.values() if v.get("active")), next(iter(profiles.values())))
       return {"MODAL_TOKEN_ID": p["token_id"], "MODAL_TOKEN_SECRET": p["token_secret"]}

   run = f"<job>-{secrets.token_hex(3)}"                   # unique per launch
   image, package = castform_package(castform.Image.from_registry("<the job's image>"))
   image = (image
            .pip_install(package)                         # build steps first ...
            .add_local_dir(REPO, "/workspace/repo",       # ... then the repo, which is synced
                           exclude=[<every symlink in the repo>]))
   container = castform.Container(
       name=run, image=image, gpu="<the GPU the user asked for, e.g. H100:1>",
       working_dir="/workspace/repo",
       env={"CASTFORM_RECOVERY": "resample", "CASTFORM_RECOVERY_RUN": run,
            "CASTFORM_PACKAGE": package},                 # for a job that builds its own env (4)
       secrets=[castform.Secret.from_dict(modal_credentials())],
   )
   container.run(["bash", "-lc", "<the job's setup and command>"])
   print(f"container {run}", flush=True)
   for text in container.logs(follow=True):
       print(text, end="")

   - Build steps (pip_install, apt_install, run_commands, files with copy=True) must come
     before plain add_local_dir/add_local_file, or the SDK raises a ValidationError.
   - The SDK refuses any symlink in an uploaded directory. List them with
     `find <repo> -type l -not -path '*/.git/*'` and put each in `exclude`.
   - Credentials go in `secrets`, from the user's environment or the provider's own config
     file, never into the repo. For E2B, E2B_API_KEY; for Daytona, DAYTONA_API_KEY (and
     DAYTONA_API_URL and DAYTONA_TARGET if the user sets them), in place of
     modal_credentials(). Other secrets the job needs (WANDB_API_KEY, HF_TOKEN) go in the
     same Secret. Secret names can't start with CASTFORM_.
   - Job setup that needs network or a GPU (dataset preparation, downloads) goes in the
     container command, before the job, not on the user's machine.
   - If the user didn't name a GPU, use H100:1 and say so.
10. Your final message is for the user, not a reviewer, at most 15 lines:
   - one line: done, or what stops it;
   - "Next steps": at most 3 commands, the last of them the launch
     (`python <path>/launch_castform.py`, or the job's own launcher). Never have the
     user type a key: the template reads Modal's from ~/.modal.toml; for E2B or Daytona, name
     the variable to keep exported (E2B_API_KEY, DAYTONA_API_KEY);
   - "What changed": one line per file, in plain words, and why, e.g. "harbor_generator.py:
     each trajectory now runs as one rollout, so a preemption replays it". Say so if a
     function's signature changed;
   - "Available if you want them": the optional extras, one line each, in the user's terms;
   - "Needs your decision": only blockers the user must act on. Don't ask the user to
     confirm what the page says is handled.
   Write the detail to CASTFORM_RECOVERY.md next to the job, at most 40 lines: what you
   marked and why (file:line), what stays uncovered, how to check it's on ("check it's
   on"), and how to turn recovery off.