When to reach for it
- Agents execute code, shell commands, or browser actions.
- Untrusted inputs are processed.
- Side effects must be contained.
Run code where it can't escape.
Model-generated or agent-selected code runs in an isolated environment — a container, a microVM (e.g. Firecracker), or a hosted code sandbox — with no access to the host filesystem, network, or credentials beyond what the task explicitly needs.
In practiceA data-analysis agent executes user-supplied Python snippets inside a gVisor container, so a malicious script cannot read the host filesystem.
Without itWithout a sandbox, model-generated code runs with the agent's full host permissions, turning a prompt-injection into an arbitrary code execution path. See the anti-pattern →
Code the model wrote runs in a separate, disposable environment. It gets the files the task needs and nothing else: no host filesystem, no credentials, and no network unless that is allowed explicitly.
1 · Prepare
2 · Run
| Code tries to | In the sandbox | Result |
|---|---|---|
| Read the uploaded CSV and compute a mean | The file was copied in | Works |
| Read the SSH keys of the host | That path does not exist here | File not found |
| Send the data to an external server | The network is off | Connection refused |
| Loop forever | The time limit applies | Killed after 30 seconds |
import shutil, subprocess, tempfile
def run_in_sandbox(code: str, input_files: list[str], timeout=30):
workdir = tempfile.mkdtemp() # a fresh directory per run
for path in input_files:
shutil.copy(path, workdir) # only the inputs of this task
open(f"{workdir}/main.py", "w").write(code)
try:
done = subprocess.run(
["docker", "run", "--rm",
"--network", "none", # no outbound connections
"--memory", "512m", "--cpus", "1", "--read-only",
"-v", f"{workdir}:/work", "-w", "/work",
"python:3.13-slim", "python", "main.py"],
capture_output=True, text=True, timeout=timeout)
return done.stdout or done.stderr
except subprocess.TimeoutExpired:
return "Killed: time limit reached"
finally:
shutil.rmtree(workdir) # nothing survives the runWhen to reach for it
When it backfires
The sandbox blocks file access, but the generated code uses a web-request tool to exfiltrate data.
Countermeasure
Audit the tool set available inside the sandbox. Remove network-facing tools unless explicitly required and monitored.
A runaway loop inside the sandbox consumes all CPU or memory. The host process degrades or crashes.
Countermeasure
Enforce cgroup limits on CPU, memory, and wall-clock time. Kill the sandbox when any limit is exceeded.
EU law
Duties from EU law that this pattern helps meet, or that land on it. A reading aid, not legal advice.
An engineer's reading aid, not legal advice. The legal texts and their interpretation are authoritative.
Next pattern
Search patterns, frameworks, and pages.