# Remote Compute Modal

> Run GPU jobs on the user's own Modal account via host.compute.create('modal', provider_params={...}) — the create→submit→wait_for_notification flow, the compute_provider kernel for env setup, image/volume resolution, and the two approval cards. Load once you've decided to dispatch to Modal.

- Skill: `jimliu/remote-compute-modal` (Agent Skill, multi-file: 15 files)
- Install (CLI): `npx get-skill add jimliu/remote-compute-modal`
- Raw SKILL.md: https://api.skillmd.com/api/skills/jimliu/remote-compute-modal/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Coding & Dev Tools
- License: Apache-2.0
- Author: Jim Liu (baoyu) (https://skillmd.com/u/jimliu)
- Updated: 2026-11-18
- Page: https://skillmd.com/skills/jimliu/remote-compute-modal

---


You're dispatching to the user's Modal account: containers spin up in Modal's
cloud, on hardware you name in plain terms (gpu/cpu/memory), under
their workspace, on their bill. That's the reason there are
two approval cards rather than one, and the reason the env-setup surface is
a separate kernel rather than something you can call inline from the
control-plane kernel: each card is the user consenting to a specific,
bounded use of their credential, and the architecture keeps those grants
legible by keeping the surfaces apart.

`host.compute.create('modal', ...)` resolves the target the moment you call
it: if Modal isn't enabled in this install it raises `host.compute.NotFound`
listing the targets that do exist — ask the user to enable it under
*Settings → Compute → Modal* (or surface the prompt; you can't enable it for
them). A bad `provider_params` key or value raises
`host.compute.InvalidResource` naming the field, before anything is staged
or billed.


For first-time environment setup, see `env-setup.md` in this skill
directory — it walks through driving the `compute_provider` kernel to
build and record images.

## Clocks and container lifetime

You set exactly one clock: `run_timeout_s` on `submit_job`, the job's own
wall-clock guard, in integer seconds. Everything else is either derived or
a platform constant you're told about, not a knob you turn.

1. Container life starts at sandbox creation, on the first `submit_job()`
   on a handle — staging the inputs counts against it, so a big upload
   spends container time before the job runs. The container's wall clock
   is Modal's `Sandbox.create(timeout=)`, filled from the Settings default
   for this provider (*Settings → Compute → Modal*) unless you pin it via
   the `timeout` key in `provider_params` (ceiling: Modal's 24 h platform
   lifetime minus the staging margins — 85,500 s).
2. The job runs. If it exceeds `run_timeout_s` it is TERMed there.
   Omitted, `run_timeout_s` defaults to the container's remaining life
   minus the harvest margin, and `job.notes` records the value that was
   filled — read it back as `job.deadline` / `job.time_left_s()`. Name one
   when you know the job's budget: a hung job then costs that budget, not
   the whole container, and the warm container survives for the next
   submit.
3. Near end of container life — one harvest margin before the provider
   destroys the sandbox — the in-sandbox **harvest watchdog** TERMs
   whatever is still running. It runs on the sandbox's own clock, so a
   wrong desktop clock or a slow upload can't make it fire late.
4. After any TERM there is a grace window for checkpoint-on-TERM handlers
   to flush, then the process group is stopped.
5. Whatever is under `./out/` (plus the logs) is tarred and staged
   UNCONDITIONALLY — on success, timeout, failure, and crash alike — and
   harvested back into the workspace. Staging is unconditional; delivery
   isn't. If the stream is refused or gives up (`result_rejected`,
   `harvest_failed`), the staged copy waits on the sandbox — see "When the
   job fails".

After a job finishes, the sandbox idles **warm for 15 minutes** waiting for
your next submit on the same handle, then its PID-1 **idle watchdog**
self-terminates it. That window is a platform constant, disclosed in
`job.notes` / `res.notes` and in `host.compute.ledger()`'s sandbox rows
(`auto_terminate_in_s`) — never a kwarg. Your two lifetime actions are
"submit again on the same handle" (stays warm) and `c.close(intent=...)`
(terminate now).

A deadline-ended job lands as `state == 'timed_out'` — not a generic
failure — with its partial outputs already harvested, plus a note saying
the deadline (not the workload) ended the run and suggesting the remedy:
a larger `run_timeout_s`, or resuming from a harvested checkpoint. A
deadline ends the run, never the results.

## Two surfaces, one provider

You reach Modal two ways. They share confinement and credentials but answer
different questions, and confusing them is the most common way to waste a
turn.

`host.compute.create('modal', provider_params={...})` is the **job
surface**. It runs in the `repl` tool — same as `remote-compute-ssh` — and
is what you use for anything with inputs/outputs you want harvested into
the workspace, anything on a GPU, and anything long enough that you'd want
to reattach if the daemon restarts. `create()` validates the target and the
`provider_params` immediately, but the **tier card** (provider, image,
`1× A100-40GB · 8 CPU · 32 GB`, container timeout, volumes) and the actual
Sandbox creation both happen on the first `submit_job()`.
`submit_job` / `attach_job` / `job.result()` / `close` work as for SSH;
the ssh-only verbs (`call_command`, `download`, `upload`) raise
`host.compute.NotSupported` on this handle. `job.result()` never waits —
waiting is the daemon poller's job: it probes the sandbox, harvests
`out.tar.gz` into `hpc/<jobId>/`, and posts a `compute_done` notification
when done. A cell that blocked on the job instead would tie up your
control-plane kernel for a GPU run's whole duration, so calling `.result()`
before the notification raises `host.compute.JobPending`, whose `next_step`
is the park protocol. To wait, exit the cell after `submit_job` and use the
`wait_for_notification` brain-tool. What reaches the remote is
what was in the workspace files you named, and what comes back lands under
`hpc/<jobId>/` through the same hardened extractor.

`compute_provider({'provider': 'modal', 'code': '…'})` is the **environment
surface** — a Python shell with the user's Modal SDK already authenticated,
running in its own confined process. Use it to *prepare* compute: build
container images JIT in the user's workspace, populate model-weight volumes
by running the downloads on Modal's own infrastructure (so wide-internet
fetches never traverse the local allowlist), check what assets already
exist, run a short CPU smoke probe. Its first cell in a session fires the
**kernel card** — *"environment setup — build images, populate volumes, CPU
probes ≤30 min; GPU jobs ask separately"* — and once granted, subsequent
cells in this kernel's lifetime (idle-timeout ~15 min) run without further
prompts. The kernel rejects `gpu=` on `Sandbox.create`, and rejects any
`timeout` above 1800 s (30 min) — loudly, at create time; nothing is
silently clamped. That cap is the kernel's own probe budget, separate
from the job surface's container timeout, and it is a real wall: a
sandbox you create here and are still using dies at its `timeout`
(outputs inside it are then unrecoverable), so size each staging/probe
step to fit, checkpoint to a Volume, or move long work to the job
surface. An unset `timeout` keeps the SDK default (300 s). It's a
redirect to the job surface, not a fence; you've already been handed
the credential. **Terminate every sandbox you create here** —
`sb.terminate()` in the same cell, in a `try/finally` if you `exec` in
between (`build_env`'s hydrate models this). Nothing reaps it
mid-session: the idle timeout kills the *kernel*, never your sandboxes —
the ≤30-min cap only bounds how long a forgotten one bills.

A Modal workspace is commonly shared across many Claude Science
installs. `modal.Sandbox.list()` without `app_id=` returns every
live sandbox in the workspace — other users' running GPU jobs
alongside yours — so hundreds of unfamiliar sandboxes is normal
load, not a leak, and terminating one destroys another team's work.
Terminate only sandbox ids this session's own `Sandbox.create()`
returned; never enumerate-then-terminate.

The shape of a good run is: read what's already known about this workspace,
decide whether the env you need exists, build it via the `compute_provider`
kernel if it doesn't, then run the actual job through `compute.create()`.
The two cards appear at most once each per session — and on a warm second
session with a project-level grant, neither.


## Workflow

Every `host.compute.*` call here runs via the **`repl` tool**; the
`compute_provider` kernel is reached via the **`compute_provider` tool**.
Neither is the `python` tool. All three share your workspace directory but
not memory — pass data through files.

Start with `compute_details({provider: 'modal', mode: 'read'})`. Below
the orientation line is the per-workspace ledger — `### env:<name>@<spec_sha>`
blocks recording images that already exist in this user's Modal workspace,
the volumes they pair with, and any free-text notes a previous session left.
The `spec_sha` is the content hash of the env's source file in this binary,
so a ledger entry whose hash matches is one you can use without rebuilding:
pass its image ref straight to `compute.create()` and the kernel card never
appears. A mismatch means the env definition changed in this release — the
old image still works but isn't what the current env file describes, so
treat it as absent.

If what you need isn't in the ledger, build it in a `compute_provider`
cell. Two helpers are pre-bound there alongside `modal` and `app`:

- `list_envs()` → `{name: META, …, '_envs_dir': path}` for every bundled
  env (packages, GPU tier, secrets it needs)
- `build_env(name, *, hydrate=False)` → builds the image, returns
  `{'image': 'im-…', 'spec_sha', 'volumes', 'env', 'hydrate'}`

To inspect what an env actually installs (the `modal.Image` chain) before
building, read the source from the **control-plane kernel** (a `repl`
cell) — it's a skill asset:

```python
# repl tool
print(host.skills.read('remote-compute-modal', 'envs/proteomics_jax_gpu.py')['content'])
```

Don't `find` for it from bash — the path differs across builds.

```python
# compute_provider tool, provider='modal'
need = {'transformers', 'torch'}
envs = list_envs()
print({n: m for n, m in envs.items()
       if not n.startswith('_') and need <= set(m.get('packages', []))})
# → {'proteomics_gpu': {'packages': [...], 'gpu_default': 'A100-80GB', ...}}

r = build_env('proteomics_gpu', hydrate=True)
print(r['image'], r['spec_sha'], r['volumes'])
```

Carry `r['image']` (the `im-…` reference, NOT the env name) back to the
control-plane kernel (a `repl` cell) and pass it as
`provider_params['image']` — and, for a bundled env, its NAME as
`provider_params['env']`: the host then reads the env's
`META["egress_domains"]` from the SHIPPED file at every submit, so the
declaration survives rebuilds (a pointer into the shipped catalog, not a
power). The two kernels share a working directory but not memory, so the
simplest handoff is a workspace JSON file:

```python
# compute_provider tool — last line of the build cell
import json; json.dump(r, open('built_env.json', 'w'))
```

Append a `### env:<name>@<spec_sha>` block to `compute_details` so the
next session reads the `im-…` ref straight from there and skips the
`compute_provider` cell entirely. **Pass `r['image']` (the `im-…` ref) as
`provider_params['image']`.** The adapter will resolve a bare env name
from the ledger as a fallback, but that's brittle — the ledger entry can
be stale or absent. Treat the build as its own task with its own validation;
don't fold it into a job submission. See `env-setup.md` for ad-hoc patches
and gated weights.

`provider_params` is ONE flat dict in Modal's own vocabulary — the accepted
keys are `image`, `env`, `gpu`, `cpu`, `memory`, `volumes`, `timeout` — and
it is validated when `create()` runs, so a typo raises there rather than
after the inputs are staged. For a quick inline call (no inputs, output is
just stdout), use `submit_job` with no `inputs`. The `compute_done`
notification payload carries `state` / `exit_code` / `notes` /
`output_files`, plus `error_kind`, `system_hint`, and `deadline_fired`
when set — read those disclosures from the notification itself. For
`stdout_tail`, re-enter the kernel and read it off `.result()` after the
notification arrives:

```python
# repl tool — cell ① submits and RETURNS
import json
r = json.load(open('built_env.json'))
c = host.compute.create('modal', provider_params={
    'image': r['image'],          # the im-… ref (bare name fallback brittle)
    'env': 'proteomics_gpu',      # bundled-env NAME → its shipped egress declaration applies
    'gpu': 'A100',                # timeout omitted → container gets the Settings default
    'volumes': r['volumes'],
})
j = c.submit_job(
    intent='load esm2_t6 on GPU',
    command='python -c "from transformers import EsmModel; import torch; '
            'm = EsmModel.from_pretrained(\\"facebook/esm2_t6_8M_UR50D\\").cuda(); '
            'print(torch.cuda.get_device_name())"',
    run_timeout_s=300,             # this probe finishes in 5 min or it's hung
)
# the Job repr just printed itself: id, notes (cold start, deadline), the
# re-attach line — the cell ends here, the kernel never waits on the job
```

Then exit the cell and use `wait_for_notification`. When the
`compute_done` notification arrives, its payload has `state` /
`exit_code` / `notes` / `output_files`, plus `error_kind` /
`system_hint` / `deadline_fired` when set. For `stdout_tail`, re-enter the
kernel:

```python
# repl tool — cell ② after the compute_done notification
res = c.attach_job('<JOB_ID>').result()   # a read, not a wait — the poller already collected ./out/
print(res.stdout_tail)
c.close(intent='probe done — stop the sandbox')
```

For a full job with inputs and harvested outputs:

```python
# repl tool — cell ① submits and RETURNS
c = host.compute.create('modal', provider_params={
    'image':   r['image'],               # 'im-…' from build_env(); bare-name fallback exists but is brittle
    'env':     'proteomics_jax_gpu',     # bundled-env NAME → its shipped egress declaration applies
    'gpu':     'A100-40GB',
    'cpu':     8,
    'memory':  32768,                    # MiB — Modal's unit, not GiB
    'volumes': {'/cache': 'af2-params'}, # mount path → Modal Volume name
    'timeout': 3600,                     # container wall clock, seconds — optional; omitted → Settings default; ceiling: Modal's 24 h platform limit
})
# → the tier card renders on the first submit_job → Sandbox.create() under the user's workspace

job = c.submit_job(
    intent='colabfold on target.fasta — 1× A100, ~40 min',
    command='colabfold_batch target.fasta out/ --num-recycle 3 --model-type alphafold2_ptm',
    inputs=['target.fasta'],                     # bare string ≡ {'src': 'target.fasta'} → ./target.fasta
    outputs=['ranked_0.pdb', '*.json'],   # only these come back from ./out/ → output_files; a *.log your tool writes under out/ is NOT kept unless you name it (the run's own stdout.log/stderr.log always land, as logs)
    run_timeout_s=2700,                  # job guard — optional; default = remaining container life − harvest margin
)
# repr printed itself (id, notes, deadline, egress); cell ends here
```

Then `wait_for_notification` — the `compute_done` payload includes
`output_files`, so you can `save_artifacts(payload['output_files'])`
directly without re-entering the kernel. If you want the full record
(`stdout_tail` / `stderr_tail` / `wall_s` / `notes`):

```python
# repl tool — cell ② after the compute_done notification
res = c.attach_job('<JOB_ID>').result()   # read of the persisted result — never a wait
save_artifacts(res.files)
c.close(intent='task done — stop the sandbox')
```

`res.wall_s` (also `res["job_wall_s"]`) is the seconds `run.sh` ran on
the remote — the actual GPU/compute duration.

`inputs=` entries are `{src, dst}` (a bare `'path'` string is `{'src': 'path'}`)
and stage **flat** into the workdir root: `src` is a workspace-relative path
(or `artifact://<version_or_artifact_id>` for an artifact-store file — `dst`
required then); `dst` is a bare filename — `'inputs/gfp.fasta'` is rejected
at submit (the file would land at `/work/gfp.fasta`, not where the command
expects). `src` can be a path; `dst` can't. Omit `dst` to default to
`basename(src)`. Need a dir layout? `mkdir -p` it inside `command=`.

**Sizing `inputs=` — and when to use a Volume instead.** Inputs are
stdin-streamed through a confined path at ~0.65–0.81 MiB/s effective
(measured) — budget staging time from that: 1 GiB ≈ 20–26 minutes of
upload before the job starts, spent from container life. The host
budgets staging from input size with a planning rate it cannot verify
(upload speed isn't controllable), so a slower-than-planned upload never
endangers the harvest — the watchdog's absolute-clock backstop still
protects the staging window; the job just gets less runtime than
nominal. If an upload dies outright, the submit fails LOUDLY with a
transport error and no phantom job. Practical sizing: code, configs, and
small data are what `inputs=` is for; it is workable up to its **1 GiB
per-submit cap** (a `TransferTooLarge` refusal above it) and its **64
files per-submit cap** (every input is held open at once for the
streaming upload; a 65th is refused before anything stages — tar many
small files into one archive and unpack it in `command=`) — so beyond
either a Volume is the only path, and the better one well before that. Volumes
(Files-tab import, or a `compute_provider` cell; mount via
`provider_params['volumes']`) persist on Modal disks across jobs and
cost zero upload per submit.

**Checkpoint long jobs as they run.** Write progress to `./out/` (or a
Volume) periodically: at either deadline the workload gets TERM, then a
grace window for checkpoint-on-TERM handlers, and whatever is under
`out/` is staged and harvested unconditionally. A job that checkpoints
loses at most one interval to a deadline — never the run. Keep `./out/`
checkpoints SMALL (≈ ≤100 MB compressed): the harvest stream back to the
host runs in a bounded (~2 min) window, so a multi-GB `./out/` risks
`harvest_failed` even though staging succeeded — large checkpoints
belong on a Volume, with only small summaries under `./out/`.

**Only `./out/` (+ the logs) comes back — and that's the whole point of the
convention.** A Modal sandbox is destroyed with its filesystem, so unlike
ssh there is no persistent workdir to leave things in or chain from; the
one durable move is the harvest, and the wrapper makes it a single bounded
stream by tarring exactly `out/` + `stdout.log` + `stderr.log`. Everything
else in the sandbox is gone at teardown. `outputs=` globs select within
that scope — name `['ranked_0.pdb', '*.json']` and only those files under
`./out/` come back (`output_files`); omit `outputs` and all of `./out/`
comes back — and `exclude=[...]` subtracts globs the same way (a checkpoint
dir you don't want back). The run's own `stdout.log`/`stderr.log` are not
in `output_files` — they're the run's logs, not files you named; they land
beside the deliverables in `hpc/<job_id>/` and feed `stdout_tail`. Because the tarball is built sandbox-side before
either list applies, on byoc they shape `output_files`, not the bytes on the
wire; for the same reason there are no per-file `transfer_limits` here (it
raises `NotSupported`) — one fixed whole-stream cap governs the tarball, so
you bound what comes back by what you write under `./out/`. If your tool
writes to cwd, a Volume mount (e.g. `/atlas`), or `$HOME`, end `command=`
with `cp -r <results> out/` (or point the tool's `-o`/`--output` at
`out/`). A successful job with an empty `out/` returns no output files
plus a note telling you so (the logs still land beside them).

`command=` is interpolated into a `run.sh` and run via `bash run.sh`.
For anything beyond a single program-with-args — nested quotes, inline
`python -c "…"`, heredocs, pipelines — write the script to a workspace
file and ship it via `inputs=`, then `command='bash script.sh'` or
`command='python script.py'`. Multi-layer shell escaping inside
`command=` is the most common cause of `syntax error near unexpected
token` failures; when you must interpolate a value, `shlex.quote()` it.

`provider_params` uses **Modal's own kwarg names** — Modal's docs are the
docs. The adapter resolves the strings to SDK objects (env name → its
`im-*` from the `compute_details` ledger; volume name → `Volume.from_name`)
and passes the rest through to `Sandbox.create(**params)`. An absent
`timeout` fills from the Settings default before the tier card renders,
so the card shows the real lifetime. A `timeout` above Modal's 24 h
platform cap, out-of-range hardware, or an unknown key is rejected at
`create()` with `InvalidResource` — nothing is silently clamped, and the
family-nested `{'modal': {...}}` wrapper from older transcripts is
accepted only as a mute alias for the flat dict.

## The image-reference rule

`image` is **always a string**. A `modal.Image` object built in a
`compute_provider` cell cannot cross to the control-plane kernel — they are
separate Python processes under separate confinement invocations, and a live
SDK handle is meaningless on the other side. So the pattern is:

```python
# compute_provider tool — env setup (`modal` and `app` are pre-bound)
img = (modal.Image.from_registry('nvidia/cuda:12.4.1-runtime-ubuntu22.04',
                                 add_python='3.11')
       .pip_install('chai_lab==0.6.1'))
img.build(app)
print(img.object_id)          # → 'im-7f3a2e…' — read this string
```

```python
# repl tool — job
c = host.compute.create('modal', provider_params={
    'image': 'im-7f3a2e...',    # the string, not the object
    'gpu': 'A100',
})
```

The adapter validates an `im-*` literal via `Image.from_id()`, which fails
closed on a foreign or fabricated id, so a typo surfaces as `NotFound`
before any GPU spins. An env name is looked up in the ledger first
and resolved to the recorded `im-*`; on a miss the adapter returns
`image_build_failed` with copy pointing at
`compute-env-setup` rather than triggering a build inline.

## What latency to expect

Measured against real Modal during validation — set clocks and user-status
messages from these, not guesses:

| phase | typical | notes |
|---|---|---|
| `Image.from_registry(..., add_python=...).pip_install(...).build(app)` | 130–360s | one-time per `im-*`; runs on Modal's CPU build infra, not your tier |
| `compute.create()` (target lookup + params check) | one host round-trip | no container, no card |
| first `submit_job()` on a handle, A100 | ~18–30s cold start + job runtime | creates the container (image pull + boot); raises the tier card |
| first `submit_job()` on a handle, H100 | ~20–25s + job runtime | similar; queue wait can add when capacity is tight |
| subsequent `submit_job()` on same handle | ~5–10s + job runtime | reuses the warm container — weights/caches stay hot |

So budget ~3–6 min for a fresh env's first GPU result, and ~5–10s per
subsequent `submit_job()` on the same handle. If a first cold start is
past ~90s, that's queue wait, not a hang — surface it rather than retrying.
Cold starts and reuse both announce themselves in `job.notes`.

## When the user gives you a budget

A user who says "stay under eight GPUs" or "keep it to a hundred at a
time" is giving you a number that the prompt alone can't enforce. You'll
write it into the orchestrator's instructions, but the sub-agents you
delegate to start with fresh context — they never see that line, and
each one will reasonably try to use as much compute as its own task
seems to warrant. Across a wide fan-out that drifts well past whatever
the user had in mind, and the first sign is usually the bill.

`host.compute.set_concurrency_limit(k)` exists so the user's number
becomes a property of the session rather than a sentence in a prompt.
Call it once before delegating; the daemon stores it against the session
root and counts every sub-agent's live job against the same `k`. A submit
that would put the session over the cap raises
`host.compute.ConcurrencyFull(live, limit)` in whichever frame made it,
and the right response depends on who holds the slots — a `compute_done`
is only ever delivered to the frame that submitted that job. So a frame
with its own running job ends the cell and parks on `wait_for_notification`
(one of its own jobs finishing frees a slot and wakes it), then resubmits.
A sub-agent refused because *siblings* hold the cap (`e.owns_live_jobs` is
False) will never receive their notifications; parking would sleep
forever, so it hands back to the orchestrator instead. The exception's
`next_step` says which case you're in. Size the fan-out from
`c.concurrency` (`Slots(live, limit)`) up front so sub-agents rarely hit
the cap. Sub-agent code is otherwise unchanged.

Choosing `k` has one constraint beyond the user's intent: each provider
also has its own ceiling, and that ceiling refuses rather than queues —
a session limit above it just stops being the binding constraint, and
submits past the provider's own ceiling raise a `Busy` error instead of
`ConcurrencyFull`. `host.compute.status()` returns both your `k` and the
provider ceilings, so you can pick a value that actually parks. When
the user hasn't given a number, leaving the limit unset keeps today's
behavior; set one yourself only if a fan-out is wide enough to threaten
the provider cap.

## Warm reuse, reattachment, and `close()`

One handle = one container. The first `submit_job()` creates it;
subsequent calls on the same `c` reuse it warm (weights/XLA cache stay
hot). The poller's harvest does **not** terminate the container — it runs
until `c.close(intent=...)`, 15 minutes of inactivity (the sandbox's
PID-1 **idle watchdog** — a kill, not a harvest: anything unharvested
goes with the container), or its container timeout, whichever comes
first. Until then a finished — or failed — job's container bills idle,
and both the countdown and its remedy are in `job.notes` and
`host.compute.ledger()`. **Every handle that ran or attached a job ends
with `c.close()`** — after its last job, not between jobs, and not while its
sandbox holds the only copy of unrecovered outputs
(`result_rejected`/`harvest_failed` — see "When the job fails"). Close
once the final `compute_done` has arrived and the harvest is confirmed;
if the next job on this handle is imminent, or the user asked to keep
the container warm across jobs, leave it open and close when the
sequence ends. `close()` stops only the jobs THIS handle submitted or
attached; a *fresh* handle that holds no jobs — e.g. one recreated after
a kernel reap, `host.compute.create('modal').close(intent=...)` — closes
EVERYTHING this agent submitted on the target (and, from the session's
root agent — the orchestrator — everything the conversation has there),
so use that form only when no other agent in the session still has live
work there (to stop one known job's sandbox from a fresh handle,
`c.attach_job(job_id)` first, then `c.close()`; a handle whose submit
failed holds no jobs and its `close()` is a harmless no-op — though a
submit that failed mid-flight can leave a job the daemon settles on its
own, listed by `host.compute.ledger()`). Either way it returns a
`CloseReport` naming what it actually terminated (short of the
orchestrator's close-everything sweep, a sandbox that a live job outside
the close's reach has since re-adopted is kept, under `kept_in_use`).
Near end of life the **harvest watchdog** stops any running job early
enough to stage its outputs, so even the last job comes back harvested.
A warm container is
reused only when its remaining life covers the next job's deadline plus
margin; otherwise the submit creates a fresh sandbox (one more cold
start, same handle) and says so in `job.notes` — the swap is never
silent.
**Sequential only**: each submit wipes `/work`, so call job N+1's
`submit_job()` after job N's `compute_done` notification arrives; for
parallel jobs use separate handles. A second `create()` with different
`{gpu, cpu, memory}` is a separate container and a separate card. The
detached wrapper survives a Claude Science daemon restart — on restart
you'll see "1 job reattached" rather than a cold start.

**Multiple parallel jobs** (separate handles): submit all in one `repl`
cell, then loop `wait_for_notification` → act on every entry in
`notifications` (several may arrive at once) → repeat until it returns
`{status:'error'}` (= none left — that error is final, so stop calling
the tool there and move on). There's no need to poll `job.state()`
/ `.result()` — the notifications arrive on their own, and each poll is a
live host round-trip that tells you nothing the wake-up wouldn't.

**Before you finish the task**: every handle that ran a job is closed
(unless the user asked to keep one warm, or its sandbox holds unrecovered
`result_rejected`/`harvest_failed` outputs). Tear down job-surface
containers with `c.close()`, never a raw `sb.terminate()` — only
`close()` consults the host's recoverable-outputs gate. Terminate a
kernel probe sandbox only by the id you hold from creating it — the
workspace is shared and the app can be too, so an enumerate-then-
terminate sweep destroys other teams' running work.
`host.compute.ledger()` is the cheap final check that nothing you own is
still live.

## When the job fails

A failed job's container stays up on purpose, so you can fix and
re-submit warm — but "stays up" has a clock on it: the in-sandbox idle
watchdog terminates it after 15 minutes of inactivity, and reading files
off it does not reset that clock. If you aren't re-submitting on this
handle now, `c.close()` it and diagnose from the harvested tails and
outputs below — except on `result_rejected` and `harvest_failed`,
where the sandbox holds the only copy of the output; read those
entries before you touch `close()`. For every other kind, closing
loses only what didn't come back (a core dump, a verbose log, a file
outside `./out/` or left out of `outputs`) — and `c.download()` can't save
it here:
it is ssh-only and raises `NotSupported` on this handle. Read any such
file off the live sandbox from a `compute_provider` cell BEFORE you
close: find it with `modal.Sandbox.list(app_id=app.app_id,
tags={"claude-science-job": "<job_id>"})` — the tag names the job
whose submit cold-started the container: your failed job, unless you
chained submits on a warm handle (each fresh sandbox announces itself
in `job.notes`) — then `sb.exec("cat", "<path>")` to pull the bytes.

Read `res.exit_code`, `res.stdout_tail`, and `res["stderr_tail"]` (and
`res.notes`, which repeat any host-authored remedy hint). A job
that hit a deadline lands as `state == 'timed_out'` with its partial
outputs already harvested into `hpc/<job_id>/` — check `stdout_tail` for
progress and resubmit with a larger `run_timeout_s` (or resume from a
harvested checkpoint) only if the work was actually cut short. Failures
that never produced an exit code raise instead: every leaf under
`host.compute.Error` carries a closed `.kind`, and a submit-time or
provider failure arrives as `ProviderError` whose `.kind` (the same
string the `compute_done` payload's `error_kind` carries) maps cleanly
onto where to look:

`image_build_failed` — Modal's layer build errored: a yanked PyPI version,
a base-image pull failure, a pin that no longer resolves. The build-log
tail is in the `compute_provider` cell where you ran `build_env()`; fix the
env file and rebuild there. No image reference was produced, so the ledger
stays clean. If you passed an env name to `create()` without ever building
it, the name is valid but no image is in the ledger yet — `build_env()` it
first.

`unauthorized` — token rotated or revoked. The `compute_provider` kernel
will have already exited on the first 401; the next cell respawns and
re-resolves the stored Modal credential, so the user fixing their token in
Settings → Credentials is the whole fix. (If the user's organization limits
Modal to listed workspaces, a token from an unlisted workspace is refused
at every use with an error that names the workspace Modal reported and says
the user's organization does not allow it — not retryable; the user needs a
token from an allowed workspace.)

`quota_exhausted` — workspace quota, concurrent-GPU limit, or spend cap
(surfaces as a `Busy` error). For the concurrent limit, first free what
you hold: `c.close()` finished
handles (not one holding unrecovered outputs — see below) and terminate
kernel sandboxes you created and are done with — idle warm containers
count against it. The limit is workspace-shared: never terminate a
sandbox you didn't create to free capacity. A spend cap isn't freed by
closing — accrued spend stays accrued. The workspace's deployed-apps
cap also lands here: closing sandboxes doesn't free it either — the
user has to stop stale apps (dashboard, or `modal app stop`; shared
workspace, so never stop apps you didn't create), and reusing the
bound/configured app avoids refilling it. If
it still trips, surface the copy verbatim and pause; raising the limit
is the user's billing decision.

`rate_limited` — a request-rate throttle, not capacity (`.retryable`
is true): the token's request rate, or a Volume control-plane limit
(`rate limit exceeded` on listings, `too many layers` while Modal
compacts a volume in the background). Closing containers frees nothing
here. Back off ~60s and stagger fan-out submissions / batch volume
listings, per the error text — don't hand-roll a tight retry loop.

`ownership_mismatch` — another install sharing this workspace token adopted
the warm sandbox first. The adapter cold-starts a fresh one and says so in
`job.notes`; nothing for you to do beyond noting it.

`result_rejected` (`compressed_cap_exceeded`) — output archive larger than
the consented cap. Nothing was written to the workspace and the sandbox is
still warm with `out.tar.gz` intact; the user gets a raise-and-retry
affordance that re-streams without re-running. The sandbox holds the only
copy of the output — do **not** `c.close()` until it's resolved, and
surface it to the user now, not at end of task: the Compute panel lists
the job as recoverable for 24 h, but that listing only blocks
Claude Science-side kills (a queued `close()` is deferred ~15 min, then
executes) — the in-sandbox idle watchdog still terminates the sandbox
after 15 minutes of inactivity, only copy included.

`harvest_failed` — the output stream gave up after retries; the warm
sandbox likewise holds the only copy. Same rule: no `c.close()` until
the outputs are recovered — and the recovery path is the user's, not
yours: they retrieve from the recovery list in the Compute panel. Same
clocks as above: surface it immediately.

`input_changed` — a submit input was rewritten (or deleted/swapped) between
validation and staging: the transport re-hashes the bytes it actually
uploads and compares them to the sha256 captured at validation time.
Nothing was uploaded and the job never started. Re-run `submit_job()` so
the input is re-validated; if it keeps tripping, something is still writing
that file — wait for the writer to finish before resubmitting.

A plain non-zero `exit_code` with logs is the science tool failing on
inputs — same diagnosis as on SSH: read the tails, `res.raise_for_status()`
if you want the typed `JobFailed`, fix, resubmit.

## What to record

After a successful build, append the `### env:<name>@<spec_sha>` block to
`compute_details` — env-setup.md §"Recording the result" has the snippet.
That ledger is the durable record; don't also write the same facts to
memory. Do NOT record build timings, `validated:` dates, or sha256
confirmations — `spec_sha` already encodes staleness and the rest is
noise. Gotchas you hit (a documented invocation that failed, a flag you
had to add, a quota you bumped into) are worth a free-text line.

## GPU tier reference

| `gpu` value | device | VRAM |
|---|---|---|
| `"A10G"` | NVIDIA A10 | 24 GB |
| `"A100"` | A100-SXM4-40GB | 40 GB |
| `"A100-80GB"` | A100-SXM4-80GB | 80 GB |
| `"H100"` | H100 80GB HBM3 | 80 GB |

Each bundled env carries a `gpu_default` in its `META` — what its author
sized for the typical workload. Start there; reach for a bigger tier when
you have a concrete reason (the model is documented as needing >40 GB, the
last attempt OOM'd), not as a hedge. The approval card shows the tier you
picked, but the grant is keyed on provider only, so once approved for this
conversation a tier change doesn't raise a new card — the user is trusting
your judgment on sizing after the first approval.

## Volumes

Pass `'volumes': {"/weights": "<vol-name>"}` in `provider_params`. The
mount is a symlink to `/__modal/volumes/<id>/` — always reference it by the
mount path, never the resolved target.

The Files tab lists the Modal target alongside SSH hosts: at `/` it shows
Volumes as top-level directories, and inside one you can browse, import,
and download files (same pane as SSH). The path's first segment is the
Volume's *name*, not a mount path. For scripted listing use a
`compute_provider` cell:
`modal.Volume.from_name('<name>').iterdir('/', recursive=False)`.

### Consistency and shared writes — read this before two containers share a Volume

A Modal Volume is not a network filesystem. The Modal SDK states the
contract (`modal.Volume` docstring). The rules below follow from it.

**What Modal guarantees.**
- *Reads are a snapshot.* A container sees the Volume as it was when the
  container mounted it. Commits made later by other containers do not
  appear until that container reloads the Volume. A handle reused warm
  across `submit_job()` calls (see "Warm reuse") is still that one
  container, so every job on it keeps the view from the container's
  start. A long-lived job or sandbox that re-reads a path on its mount
  gets the same bytes each time, with no error.
- *Writes need a commit.* Changes become visible outside the writing
  container only after a commit. Mounts commit in the background every
  few seconds and again at container exit, so a job's files are durable
  once it ends. A container killed mid-write can leave partial state.
- *Same path, two writers: last writer wins.* Data the last writer did
  not have when it committed is lost. There is no distributed file
  locking. A read-modify-write "append" (read file, add rows, write the
  file back) from two containers — or from one container with an old
  view — silently truncates the file to that writer's view.
- *Reload has preconditions.* `volume.reload()` runs inside a container.
  It needs an authenticated Modal client. It fails while files on the
  mount are open. `submit_job` containers carry no Modal token (see
  env-setup.md, "Secrets belong here"), so a job cannot reload its own
  mounts. The `compute_provider` kernel holds the client. From there,
  `modal.Volume.from_name(name).read_file(path)` / `.iterdir()` /
  `.listdir()` read the latest committed state with no mount at all.

**Rules that follow.**
1. *One writer per path.* Give each concurrent writer its own file
   (`results/<job_id>.jsonl`, `roster/<worker>.json`). Merge with a
   single reader afterwards. Never implement "append to a shared file"
   as read + concat + overwrite. Never `batch_upload(force=True)` over a
   file that another writer also owns.
2. *Do not poll a mount for freshness.* A job cannot watch a Volume path
   for a flag, heartbeat, queue entry, or input batch written after its
   container started (on a warm handle, at the handle's first submit).
   Dispatch one job per batch on a fresh handle (each new container
   mounts fresh), or do the check from the `compute_provider` kernel with
   `read_file()`. Never conclude "component X is dead" or "the halt flag
   is clear" from a file read through a mount older than the writer's
   update interval.
3. *A failed read is not an empty file.* If `read_file()` raises (403
   from a blob host, `rate_limited`), stop and surface it. Do not write
   back a file rebuilt from "no existing rows".
4. *Order producer before consumer.* Start the reader after the writer's
   sandbox has exited (`sb.wait()` returned). A consumer whose container
   already exists does not see the new files without a reload. That
   includes a running job or sandbox, and a warm handle submitted to
   again. Submit it on a fresh handle.

Write-once / 

…(truncated)
