Skip to content

feat(sandbox-providers): shared VM slots are walled off from each other, and one slot ends without ending the VM - #829

Open
mandykwok-scale wants to merge 16 commits into
mainfrom
mandy/shared-slot-teardown
Open

mandykwok-scale wants to merge 16 commits into
mainfrom
mandy/shared-slot-teardown

Conversation

@mandykwok-scale

@mandykwok-scale mandykwok-scale commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Why

Several tasks will share one Modal VM to cut cost, each in its own slot (#775 gives each slot its own compose project, dir, ports and scratch files). Two things must hold before any task shares a VM: one task's close must not end the others, and no task may reach another task or the VM. This PR adds both. Nothing creates shared VMs in production yet.

What

Ending one slot. tear_down_slot(sandbox, layout) removes only the slot's containers, volumes, networks, dir and scratch files. A VM made by create_shared_box is tagged as a box, and every Modal terminate goes through one check: only terminate_shared_box(sandbox_id, box_id) ends a box. A source test fails if code ends a sandbox another way. One change to today's behaviour: a terminate by id now reads the sandbox's tags first. If that read keeps failing (3 tries, about 3 s), the sandbox is left running until its Modal timeout, which costs money but never ends a shared box.

Walls between slots.

  • The box runs every container under gVisor (pinned, checksummed), with Docker's user-namespace remap and no-new-privileges.
  • Each slot gets two fixed bridges. One atomic firewall load drops slot-to-slot, slot-to-VM, private-range and all IPv6 traffic, matched by bridge so a slot can't spoof its way out. DNS and the internet stay open.
  • A slot's compose is checked against an allowlist of the keys the generator emits, so a task can't add host mounts, devices or extra privileges.
  • The only way into a slot is its door, which needs a fresh per-deploy token (X-Agentenv-Slot-Token) and refuses any address that isn't a plain path. Every caller sends the token in slot mode. Default single-tenant stacks are byte-identical.
  • A box is marked walls_verified only after a live self-test on that box passes. If any check fails or times out, the box is ended and create raises. A source test fails if anything else writes that mark.

The live runs found one real bug: gVisor's default file overlay dropped files written while building an image on the box. runsc now runs with --overlay2=none.

Validation

5,231 provider and env unit tests pass. The one failure, the Windows disk-recipe test, also fails on main. On a real Modal box, the self-test passes all 16 checks: walls hold (the firewall's drop counters rise), DNS, internet and same-slot names work, and the door returns 401/401/200/400 for no, wrong and right tokens and a bad address. The live test is tst/integration/.../shared_box_walls_live_test.py (skipped unless AGENTENV_LIVE_MODAL=1). Not yet run: real tasks sharing a box.

🤖 Generated with Claude Code

RetriggerView in GreptileConfidence Score: 5/5

The PR appears safe to merge; no new actionable issues were found.

Summary

Adds isolated slots on shared Modal VMs, slot-only teardown, and a token-checked door.

  • Shared Modal VMs pass live checks before slots use them.
  • Each shared-VM slot exposes its services through a token-checked door.
  • Closing a slot removes its stack without ending the shared VM.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Create shared box] --> B[Set Docker protections and firewall]
  B --> C[Run live checks]
  C -->|Pass and remove probe slots| D[Mark walls verified]
  C -->|Fail or time out| E[End shared box]
  D --> F[Deploy isolated slots]
  F --> G[Token-checked door]
  F --> H[Remove one slot without ending VM]
Loading

Reviews (11) · Last reviewed commit: "fix(sandbox-providers): name the walls p..." · Reviewed by Greptile

tear_down_slot ends one slot's stack, leaving the VM and every other slot
running: it removes the containers, volumes and networks its compose project
labels, then its dir and scratch files. It needs no compose file, so it also
clears a slot whose deploy failed early, and it is idempotent, so a retry is
safe. It refuses the default stack and any layout not made by for_slot, so
its file glob can't reach another stack's files. Nothing calls it yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@mandykwok-scale
mandykwok-scale requested a review from a team as a code owner November 19, 2026 23:06
mandykwok-scale and others added 2 commits November 19, 2026 18:39
…_shared_box

Several tasks' slots will share one Modal VM, a shared box, so no single task's
close may end it. Every Modal terminate now goes through one check: a handle this
process created terminates as before; one reattached by id, and terminate_sandbox,
first read the sandbox's tags and refuse, with SharedBoxTerminateRefused, to end one
tagged agent_env_shared_box. A tag read that keeps failing raises and terminates
nothing. create_shared_box tags the VM at create, and terminate_shared_box ends a box
only when its tag names that box. Callers already log a failed terminate, and a
teardown reports the box as not terminated. Nothing creates boxes yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…dal SDK module for stray terminates

reset_vm refuses a handle known to be a shared box, whose reboot would end every
slot on it. The source check now covers every agent_env module that uses the
Modal SDK and fails on a direct SandboxTerminate RPC anywhere.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@mandykwok-scale mandykwok-scale changed the title feat(env-providers): tear down one slot of a shared VM feat(sandbox-providers): end one slot of a shared VM, and never end the shared VM from one task's close Nov 19, 2026
mandykwok-scale and others added 8 commits November 19, 2026 19:37
…and a walls tag only its self-test may write

A shared box now runs its own image: the VM image plus gVisor's runsc from the pinned release 20261116.0, its
tarball checked against a SHA-512 pinned in source, and a dockerd config that runs every container under runsc in
a user namespace with no-new-privileges, the userland proxy off, and address pools outside both the slot range and
172.16/12, where Modal's resolver is. Ordinary VMs keep today's image.

Set up for a gateway, a shared box gets one idempotent firewall for all 46 slots: forwarded slot traffic may reach
its own /23, the box's resolvers on port 53 and the internet; slot to slot, slot to private ranges and slot to box
are dropped. The rules only drop or return, so Docker's own rules still apply, and a guard keeps every slot walled
off while the chains are refilled.

walls_verified is true only on a shared box tagged agent_env_walls at the current WALLS_VERSION. get_shared_box
reads that tag and the box tag in one read. Nothing writes the tag yet: _mark_walls_verified is the only writer,
for the self-test to call, and a static test fails on any other write.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…into a slot takes a per-deploy token

A slot's compose is the default stack's, refitted: every service under runsc at a fixed address on the slot's
subnets, with fixed bridge names (aes<n>env, aes<n>web), peers named in extra_hosts on the networks they share, the
box's resolvers in a read-only resolv.conf, and no published port but the door's. A validator refuses anything that
reaches past the walls. The default stack's compose is unchanged, pinned by a golden file rendered from the previous
commit.

The door (python -m gateway.door, from the gateway image) forwards each of the slot's ports to its service, HTTP
streamed both ways and WebSockets relayed, and lets a request in only with X-Agentenv-Slot-Token, which it strips.
Each slot deploy draws a new token. The env's grant carries the header to the slot's own addresses, and the callers
that sent no credential to them now send it; the default stack sends nothing new.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…idge, wall off IPv6, and the tag guard sees every write

Re-applying the walls no longer flushes and refills chains one command at a time behind a temporary guard. One
iptables-restore --noflush transaction empties and fills AGENTENV-WALLS-FWD and AGENTENV-WALLS-IN, so a failure keeps
the old rules and the script exits non-zero; the jumps into DOCKER-USER and INPUT are then added once with -C || -I.

Rules match the bridge a packet came in on (-i aes+), not its source address, which a slot could spoof. A slot may
reach only its own two bridges, its upstream resolvers on port 53 and non-private addresses; INPUT from a slot is
dropped unless established. ip6tables gets the same atomic restore and drops all IPv6 forwarded or input from aes+,
hooked into FORWARD and INPUT; a box without ip6tables fails the script.

The walls-tag guard now also fails on WALLS_TAG as an attribute, any .set_tags reference (sync or not), getattr or
setattr by string, a _walls assignment other than __init__'s passthrough, and walls= or unnamed walls passed to
ModalVmSandbox. Each is proved by a planted snippet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…only the generator's keys, env values stay one string, and every slot caller sends the door header

The door built its upstream URL by appending the raw request target, so a target like @10.250.0.9:80/x sent the
request, token stripped, to another host. It now answers 400 to any target that isn't a path from the root (//x,
@host/x, an absolute URL, *), and builds the upstream URL from the route's host and port, for HTTP and WebSockets.

The slot compose check takes an allowlist instead of a denylist: the keys the default stack's generator and
slot_compose write, and services, networks and volumes at the top level. So build, env_file, extends, include,
configs, secrets, cgroup, gpus, deploy, security_opt, sysctls and volumes_from are all refused. A named volume with
any settings is refused, as driver_opts can bind any host path, and so is a $ in a mount's source or a mount type
other than bind, volume or tmpfs. An anonymous volume such as /var/lib/postgresql/data passes, which it didn't.

An MCP server's extra_env_vars and a sidecar's env are written as they are when YAML reads them back as one string,
and JSON-quoted otherwise, so a newline or ": " can't add a key or a service. Plain values render as before; the
default stack's golden file is unchanged.

The legacy MCP reset and tool check, the spec conformance check's live tool read, the legacy /export-state stream and
the in-process proxy's MCP registrations now send the slot's door header, and nothing new for the default stack. A
slot refuses computers on sandboxes of their own: their clock follower and site routing would need the door token
on another machine, so the token stays on the box.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…dropped in raw, the tag guard matches places, and a slot compose uses only its own networks

The walls chain now decides slot-to-slot traffic before it lets replies
through, so a slot can no longer pass a forged established packet into
another slot's flow. The script also turns on strict reverse-path
filtering (all and default, so slot bridges made later inherit it).
IPv6 from a slot is dropped in raw PREROUTING, which Docker's later
FORWARD jumps can't get ahead of.

The walls-tag guard matches its writer, readers and handle __init__ by
module and qualified name. It also catches WALLS_TAG imported under
another name, the tag's value or a guarded name built with + or an
f-string, _walls= keywords, __dict__ or vars() in a module that mentions
walls, and a reattach passing walls= anything but what it read from tags.

The restore-failure test now runs through ModalVmSandbox's real exec
and exec_script against a fake exec that exits 1.

slot_compose_problems refuses a top-level network that isn't exactly the
slot's own (subnet, bridge name, no IPv6), and a service on no network
or on one outside them, since Compose would put it on a bridge the walls
don't see.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…fter its live self-test passes

create_shared_box, set up for a gateway, now runs verify_walls on the new box once dockerd is up and the walls are
applied. verify_walls runs one table of probes and, only after every one passes and both probe slots are torn down,
calls _mark_walls_verified, the one writer of the walls tag. Any probe that answers otherwise, raises or runs past its
own limit or the run's 5 minutes leaves the box untagged; create_shared_box ends it through terminate_shared_box and
raises an error naming the probe. Each probe's result is logged as one structured event.

The probes read the box's address, kernel and resolvers; check that Docker defaults to runsc with userns and
no-new-privileges; check every walls rule with iptables -C, each chain's size, the hooks and rp_filter; bring up probe
slots 0 and 1 from compose files slot_compose renders, with a door built on the box from this checkout's gateway
sources; then check from slot 0 that slot 1's containers, its door through the box's address, the box, the private
ranges and IPv6 are unreachable, that its own peer answers by name, that DNS answers through the mounted resolv.conf,
that the internet answers (both skipped under an allowlisted egress), and that slot 1's door gives 401, 401, 200 and
400 to no token, a wrong one, the right one and a target that isn't a path.

The live test, skipped unless AGENTENV_LIVE_MODAL=1, creates a box, checks the tag after a reattach, and checks what
only a real box shows: the walls' own drop rules counted the blocked probes, the box's egress and its tunnel still
work, no other interface is named aes*, and a container under gVisor can't open a raw socket.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…s, which a slot may reach

The first live run failed closed on 1.1.1.1:80: Modal's resolv.conf lists public resolvers after 172.21.0.1, and the
probe counted all of them as private.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…hrough to Docker, so images built on the box keep their layers

gVisor's default rootfs overlay keeps a container's writes inside the sandbox, so a docker build RUN step on the box
left nothing in its layer: the live self-test's door image had no httpx and the door never came up. With
--overlay2=none the walls self-test passes on Modal, all 16 probes and the live-only checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@mandykwok-scale mandykwok-scale changed the title feat(sandbox-providers): end one slot of a shared VM, and never end the shared VM from one task's close feat(sandbox-providers): shared VM slots are walled off from each other, and one slot ends without ending the VM Nov 23, 2026
Comment thread src/agent_env/env/gateway/door.py Resolved
mandykwok-scale and others added 4 commits November 23, 2026 13:31
… the slot teardown test from leaking or colliding

Both create_shared_box methods now share SHARED_BOX_DEFAULT_TIMEOUT_S. The slot teardown test brings its two stacks up
inside the try, so a failed setup is still torn down, and holds a machine-wide file lock, so two runs on one Docker
daemon never create and delete the same s43/s44 projects at once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…the door keeps no upstream cookies, and the live walls test skips with a named capability

The generator quotes an env value holding ": " or a newline, and the redaction pattern missed the opening quote, so
such a secret was logged in full. The door's shared httpx client kept upstream Set-Cookie responses and sent them on
every later request, so a caller with no cookie could ride an earlier caller's session; its jar now accepts nothing,
and only the caller's own Cookie header is forwarded. The live Modal walls test now skips as remote_sandbox, which
CI's skip policy allows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…l compose generator is masked in the log

The generator writes a multiline value as one JSON-quoted line, so the redaction pattern sees the whole secret on
that line. This renders both cases through create_docker_compose, checks the compose still reads back to the exact
values, and checks the logged form carries none of them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Main moved pgweb and db-mcp behind the gateway's /svc routes (#823), so a slot's door now routes only the gateway and
sidecar ports, and a slot's grant is its gateway's address alone. The console check asks through the door in a slot,
so the 401 it expects is the gateway's. A slot's compose writes a value with a line break on one double-quoted line,
so the logged compose masks a multiline secret in full.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…the door test's servers, and match the golden stack to main

Each probe's limit is now one of four named budgets by the kind of work it waits on, and the scripts that run on the
box name their own request and retry limits. The door probe test waits until its upstream and door accept connections,
so CI no longer sees a 502 from a server that hasn't started. The default-stack golden file takes main's change: pgweb
and db-mcp publish no ports, and the gateway reaches them by CONSOLE_URLS.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant