DEV Community

Sandscale
Sandscale

Posted on Originally published at sandscale.dev

LLM sandbox: how to run LLM-generated code without trusting it

Short answer: treat LLM-generated code as untrusted input and run it somewhere that has nothing to lose: a fresh isolated machine per task, with no secrets in it, a time limit on every command, only the network the task needs, and a short life. Then hand the model back the exit code, the output and whether the command timed out or ran out of memory, so it can fix its own mistakes. A Firecracker microVM gives you that boundary with its own kernel, which an in-process exec or a shared-kernel container does not.

Why not just run it in-process?

exec in Python, eval in JavaScript and Node's vm module run the code with your process's permissions. Node's own documentation says the vm module is not a security mechanism. node:vm is not a sandbox walks through why, and the same reasoning applies to Python's exec.

Containers are better but share the host kernel. For code nobody reviewed, a per-task virtual machine is the cleaner boundary; containers, gVisor or Firecracker compares the options.

The pattern

  1. Start a fresh sandbox for the task with a lifetime that ends on its own if your code never stops it.
  2. Write the generated code and its inputs into the sandbox as files.
  3. Run one command with its own timeout.
  4. Return structured results to the model: exit code, standard output, standard error, timed out, out of memory.
  5. Read back any output files, then stop the sandbox.

Nothing in that loop needs the model's code to be correct or well-behaved.

In TypeScript

With the TypeScript SDK (npm install @sandscale/sdk, Node.js 22 or later), using the options the SDK reference lists:

import { Sandscale } from '@sandscale/sdk';

const sandscale = new Sandscale(); // reads SANDSCALE_API_KEY

export async function runGenerated(code) {
  const box = await sandscale.sandboxes.create({ template: 'builtin:python', timeoutSeconds: 900 });
  try {
    await sandscale.sandboxes.writeFile(box.id, '/workspace/main.py', code, { region: box.region });
    const run = await sandscale.sandboxes.run(box.id, ['python3', 'main.py'], {
      region: box.region,
      timeoutSeconds: 60,
    });
    return {
      exitCode: run.exitCode,
      stdout: run.stdout.slice(-8000),
      stderr: run.stderr.slice(-8000),
      timedOut: run.timedOut,
      oomKilled: run.oomKilled,
    };
  } finally {
    await sandscale.sandboxes.stop(box.id, { region: box.region });
  }
}
Enter fullscreen mode Exit fullscreen mode

What each piece is for:

  • timeoutSeconds: 900 on create: the sandbox stops by itself after 15 minutes even if your process crashes before stop. The SDK reference gives a server default of 3600 and a maximum of 86400.
  • timeoutSeconds: 60 on run: the command's own limit (the SDK default is 60). An infinite loop comes back with timedOut: true instead of hanging your agent.
  • oomKilled: the command ran out of memory. Tell the model that plainly; it usually means loading a whole file into memory or an accidental quadratic.
  • Truncating output keeps a noisy program from filling the model's context. See truncating tool output for LLMs.

With curl

The same steps against the HTTP API:

API=https://api.sandscale.dev/api/v1/sandbox
AUTH="Authorization: Bearer $SANDSCALE_API_KEY"

curl -X POST "$API/instances" -H "$AUTH" -H "Content-Type: application/json" \
  -d '{"template_id": "builtin:python", "ttl_seconds": 900}'

curl -X PUT "$API/instances/$ID/files" -H "$AUTH" -H "Content-Type: application/json" \
  -d "{\"path\": \"/workspace/main.py\", \"content\": \"$(base64 < main.py | tr -d '\n')\"}"

curl -X POST "$API/instances/$ID/exec" -H "$AUTH" -H "Content-Type: application/json" \
  -d '{"command": ["python3", "main.py"], "timeout_sec": 60}'

curl -X DELETE "$API/instances/$ID" -H "$AUTH"
Enter fullscreen mode Exit fullscreen mode

The exec answer has exit_code, stdout, stderr, duration_ms, and timed_out and oom_killed flags. Every run is recorded, and GET /api/v1/sandbox/runs/{id} returns a run's details and cost.

What to keep out of the sandbox

  • Secrets the code does not need. Anything in the environment is readable by the code. If a task needs a credential, inject it for that run only with Vault references rather than putting it in the prompt.
  • Network it does not need. Network access follows your plan and your organization's policy, and a sandbox reaches only what the egress allowlist allows. Data analysis rarely needs any.
  • State from other tasks. One sandbox per task means one task's files cannot leak into the next. Per-run vs shared sandboxes covers when to reuse.

Where Sandscale fits

Each Sandscale sandbox is a Firecracker microVM with its own kernel, started from the SDK, the CLI, the API or MCP, with plan and policy limits, Vault and an audit log around it. The loop above is all the code you need on your side.

FAQ

What is an LLM sandbox?

An LLM sandbox is an isolated environment where code a language model wrote is executed, so mistakes or malicious instructions in that code cannot reach your servers, data or credentials. A per-task microVM with its own kernel is a common choice.

How do I run untrusted Python code from an LLM safely?

Run it in a fresh isolated machine per task, not in your process. Write the code as a file, run it with a command timeout, return the exit code, output and timeout and out-of-memory flags to the model, and stop the machine afterwards.

Should LLM-generated code have network access?

Only if the task needs it, and then only to the hosts it needs. Most analysis and test tasks need none.

What should I return to the model after running its code?

The exit code, truncated standard output and standard error, and whether the command timed out or was killed for memory. That is enough for the model to correct most mistakes.

Related

Originally published on the Sandscale blog.

Top comments (0)