<!-- https://tinyactors.dev/guides/quickjs/ -->
# The quickjs sandbox

Kind: how-to. For: [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml), [Tech lead who approves dependencies](https://tinyactors.dev/audiences/tech-lead.xml).
Voice: [How-to](https://tinyactors.dev/voices/how-to.xml).

> Run charts your users upload in QuickJS, an engine inside the package that stops a runaway loop or allocation with an error.

An uploaded chart runs in QuickJS, a separate engine inside the package, where a runaway loop ends in an error.

<a id="datamodels"></a>

## Choose the engine for each host

A host runs all its charts' code in one engine, its datamodel, which the `datamodel` option picks.

- **`native`, the default**: Chart code runs in a `node:vm` context of your own engine, fast and with your engine's values. A `vm` context looks like a sandbox but is not one: a chart in it can reach your process.
- **`quickjs`**: Chart code runs in QuickJS, an engine compiled into the package. It has no modules, timers, files or network, and it stops an evaluation that runs too long or takes too much memory.

Give every chart you did not write a `quickjs` host: charts your users upload, and charts a program generates.

<a id="stopped"></a>

## Stop a chart that loops forever

This chart loops without end, allocates without end and looks for Node.js's globals. QuickJS stops both loops with `error.execution`, and finds no globals.

```javascript title="sandbox.mjs"
import { compileCharts, Host } from '@tinyactors/node';

const compiled = compileCharts([{ name: 'uploaded.scxml', text: `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="uploaded" initial="s">
  <state id="s">
    <transition event="spin"><script>while (true) {}</script></transition>
    <transition event="hog"><script>const hoard = []; for (;;) hoard.push(new Array(1000).fill(1));</script></transition>
    <transition event="peek"><log expr="typeof process + ' ' + typeof require + ' ' + typeof setTimeout"/></transition>
    <transition event="error.execution"><log expr="'stopped: error.execution'"/></transition>
  </state>
</scxml>` }]);

const host = new Host(compiled, {
  system: 'sandbox',
  datamodel: 'quickjs',
  quickjs: { maxOps: 1000, memoryLimit: 16 * 1024 * 1024 },
  log: (entry) => console.log(entry.text),
});
compiled.close();

const actor = host.spawn('uploaded');
actor.send('spin');
actor.send('hog');
actor.send('peek');
await host.idle();
host.close();
```

```text title="output"
stopped: error.execution
stopped: error.execution
undefined undefined undefined
```

The actor handles `error.execution` like any other event, then goes on to its next one.

<a id="the-limits"></a>

## Limit memory for the whole engine

The host's `quickjs` option sets the engine's limits. A host on the native datamodel refuses the option with a `TypeError`.

| Option | Default | What it bounds |
|---|---|---|
| `maxOps` | 1,000,000 | the engine's interrupt checks one evaluation may make before it is stopped |
| `memoryLimit` | 1 GiB (`2 ** 30`) | bytes for the whole engine, every actor of the host together |
| `stackLimit` | the engine's | bytes of native stack for JavaScript |
| `realm` | `'auto'` | `'isolated'` gives every actor a context of its own ([below](https://tinyactors.dev/guides/quickjs/index.md#realms)) |

40,000 resident actors take about 112 MB of engine heap, so the default of 1 GiB holds tens of thousands. Raise it for a host that keeps more actors resident.

`host.quickjsHeapBytes` reports the engine's heap, every actor's together, to watch against `memoryLimit`.

<a id="fuel"></a>

## Limit how long one evaluation runs

`maxOps` counts the engine's interrupt checks, one per 10,000 jumps and calls. How long one looping evaluation holds its thread at each setting:

| Loop | `maxOps: 200` | `1000` | `10_000` | the default, 1,000,000 |
|---|---|---|---|---|
| `while (true) {}` | 6 ms | 27 to 39 ms | 260 ms | 26 s |
| `while (_event.data.value !== null) {}` | 50 ms | 240 to 250 ms | 2.5 to 2.7 s | about 256 s |

Every host on the thread waits that long. Measured 2026-10-18 on an Intel Xeon at 2.10 GHz, Linux; Node.js 22 and Bun 1.4.1 alike.

Set it by the stall your other actors can take: a few hundred for request handling, about 1000 for background work.

An evaluation that needs more checks than `maxOps` fails every time, so measure your charts' real work before you lower it.

The actor's `_event.data.reason` names the limit that stopped it: `'fuel'` for `maxOps`, `'memory'` for `memoryLimit`.

<a id="realms"></a>

## Give each actor its own builtins

The actors of one chart share a context, so a chart that changes `Array.prototype` changes it for all of them. A chart whose scripts declare top-level names gets a context per actor.

With `realm: 'isolated'` every actor gets a context of its own, at the cost of its memory.

<a id="what-differs-from-the-native-datamodel"></a>

## Expect hibernation and values to differ

A chart behaves the same on both engines. Two things around it differ:

- **A blob holds more.**: QuickJS writes its own values into a hibernated actor's blob, so a `Date`, `Map`, `Set`, typed array or graph with cycles comes back. A class's instance comes back as a plain object, and a function in a variable keeps the actor in memory ([Hibernation](https://tinyactors.dev/guides/hibernation/index.md)).
- **Values cross as JSON would.**: Event data and spawn params are converted to the engine's values and back through the [value table](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/README.md#values). A key holding `undefined` is dropped and an array's `undefined` becomes `null`, where the native datamodel keeps both.

Most operations cost less on quickjs, and an idle actor takes less memory: [Capacity and memory](https://tinyactors.dev/guides/capacity/index.md#what-an-actor-costs) has the numbers.
