# Runtime and sandbox

> How the Limitr engine runs in your process: where it runs, the sandbox, the sealed engine, time and memory limits on policy calls, flat memory, reading the policy document, and errors.

# Runtime and sandbox

The Limitr engine is a [Stof](https://stof.dev) document: the engine's types and functions plus your policy and
customer state, in one document, inside your process. Stof runs it as WebAssembly in JavaScript and natively (Rust) in
Python.

## Where it runs

Node, Bun, Deno, and the browser, from the same npm package, and Python (3.9 and later) from the `limitr` package on
PyPI. There's no service to run, and no network call happens during `allow`, `check`, or any other engine call.

## The sandbox

Functions in a policy (cost functions, `enabled` rules, notifications) run in Stof's sandbox:

- **No network** unless your app allows it. A `Limitr.new` policy has none by default. A Cloud policy can reach any
  public host by default, so capabilities can call the services they list; limit it with `httpHosts`. Your machine
  and private network (`localhost`, `10.x`, `192.168.x`, cloud metadata addresses, ...) are never reachable unless
  you list them.
- **No files and no environment variables.**
- **Only the functions you register.** Your app can add host functions the policy may call (see
  [Call your app from a policy](../how-to/call-your-app)).

Allow HTTP from the policy for listed hosts, or for any host:

<Tabs groupId="lang" queryString>
<TabItem value="typescript" label="TypeScript">

```ts
limitr.doc.allowHttp(['api.example.com']);
limitr.doc.allowHttp();                          // any public host
```

</TabItem>
<TabItem value="python" label="Python">

```python
limitr.doc.allow_http_hosts(['api.example.com'])
limitr.doc.allow_http()                          # any public host
```

</TabItem>
</Tabs>

With Cloud, pass `Limitr.cloud({ httpHosts: ['api.limitr.dev', 'api.example.com'] })` (Python:
`Limitr.cloud(token, http_hosts=[...])`) to allow only those hosts (`true`, the default, for any public host; `false`
for none).

The sandbox is what makes it safe for a policy to carry logic at all, including a policy someone else (or a model)
edited. [Security model](./security) puts it together with who can change your pricing and what leaves your process.

## A sealed engine

The SDK seals the engine as it loads it (engine 0.8.3 and later, with Stof's
[sealing](https://stof.dev/start/security#sealing-what-you-trust)). Policy code, a Cloud update, or anything else
parsed into the document can call the engine's functions but can't change, remove, or replace them, and can't declare
a type with an engine type's name. A change that tries fails with a `sealed` error, and the engine is unchanged.

Your policy still customizes everything it did before: functions on its own objects (Ex. a credit's `overhead`), its
own types, and subtypes that override engine functions and call the engine's version
([Override engine functions](../how-to/extend-limitr)). Fields change as the engine runs, as always.

## Time and memory limits

Every policy call has a time limit, 5 seconds by default. A call that runs longer fails instead of blocking every
call after it, Ex. a cost function stuck in a loop. You'll only see this when a policy function goes wrong.

<Tabs groupId="lang" queryString>
<TabItem value="typescript" label="TypeScript">

```ts
limitr.setMaxExecutionTime(2000);      // 2 seconds
limitr.setMaxExecutionTime(null);      // no limit
```

</TabItem>
<TabItem value="python" label="Python">

```python
limitr.set_max_execution_time(2000)      # 2 seconds
limitr.set_max_execution_time(None)      # no limit
```

</TabItem>
</Tabs>

With Cloud, pass `maxExecutionTime` to `Limitr.cloud` (`max_execution_time` in Python).

Every call also has a memory limit: a call that grows memory by more than 256 MB fails, and the engine keeps working
for the next call. Engine calls use a tiny fraction of that; it's there for a policy function that goes wrong.

<Tabs groupId="lang" queryString>
<TabItem value="typescript" label="TypeScript">

```ts
limitr.doc.setMaxMemory(64 * 1024 * 1024);   // 64 MB
```

</TabItem>
<TabItem value="python" label="Python">

```python
limitr.doc.set_max_memory(64 * 1024 * 1024)   # 64 MB
```

</TabItem>
</Tabs>

## Memory

The engine document can live for months in a long-running server, and Stof has no garbage collector, so the engine
creates nothing per call except state that belongs there. Memory grows with:

- customers and their meters, grants, caps, and overrides,
- open reservation holds (they expire),
- estimate segments (one per entitlement and segment value; keep segment values few).

It doesn't grow with calls. Code you add to a policy has to keep it that way: see
[Write policies in Stof](../how-to/write-stof-policies#memory).

## Concurrency

The SDK runs one engine call at a time, so each call is atomic. A sequence of calls isn't: use
[reservations](./reservations) when concurrent requests mustn't overspend.

- **TypeScript:** every method is async, and calls run through a queue.
- **Python:** methods are plain calls (no `await`). One engine is safe to share across threads (Ex. a WSGI server's
  workers): calls take turns behind a lock, and the GIL is released while the engine runs, so other Python threads
  keep going. With asyncio, call it directly; a local engine never touches the network. A handler can be an `async`
  function: it's scheduled on the running event loop. Handlers run during the call that sent the event, so a handler
  can't call back into the same engine (the call raises, and the handler is logged and skipped); hand that work to a
  queue or a thread instead.

Each process has its own engine and its own copy of customer state. Several servers sharing customers need a shared
source of state: [save and load customers](../how-to/save-customer-state) yourself, or use
[Limitr Cloud](../tutorial/going-to-cloud), which syncs every engine.

## Errors

- **Calls don't throw** for unknown customers or entitlements; they're denied.
- **An invalid policy** throws from `Limitr.new` with a plain message (Python: `Limitr(...)` raises `ValueError`).
- **A failing policy function** is logged and handled safely: a cost function falls back to `overhead_cost`, and an
  `enabled` rule counts as off. Engine logs go to `console.error` in JavaScript; in Python, the SDK logs to the `limitr` logger.

## Reading the document

`limitr.doc` is the underlying Stof document (`StofDoc` in TypeScript, `Doc` from `pystof` in Python). Read and export anything in it:

<Tabs groupId="lang" queryString>
<TabItem value="typescript" label="TypeScript">

```ts
limitr.doc.get('policy.plans.pro.entitlements.chat.limit.value');  // 2000000
limitr.doc.stringify('json', 'policy.plans');                      // or yaml, toml, stof
```

</TabItem>
<TabItem value="python" label="Python">

```python
limitr.doc.get('policy.plans.pro.entitlements.chat.limit.value')  # 2000000
limitr.doc.string_export('json', 'policy.plans')                  # or yaml, toml, stof
```

</TabItem>
</Tabs>

Ask a question the API doesn't have a method for, with a Stof function that runs on the policy and leaves nothing
behind:

<Tabs groupId="lang" queryString>
<TabItem value="typescript" label="TypeScript">

```ts
const plans = await limitr.doc.callSource(`
    fn plans_with(entitlement: str) -> list {
        const names = [];
        for (const (name, plan) in self.plans.fields()) {
            if (plan.entitlements.contains(entitlement)) names.push_back(name);
        }
        names
    }
`, ['sso'], 'policy');
```

</TabItem>
<TabItem value="python" label="Python">

```python
plans = limitr.doc.call_source("""
    fn plans_with(entitlement: str) -> list {
        const names = [];
        for (const (name, plan) in self.plans.fields()) {
            if (plan.entitlements.contains(entitlement)) names.push_back(name);
        }
        names
    }
""", ['sso'], 'policy')
```

</TabItem>
</Tabs>

Change customers, meters, and plans through Limitr's methods, not the document: they keep meters consistent and send
the events your app and Cloud listen for. See the [Stof tutorial chapter](../tutorial/stof).

## Exporting the policy

`limitr.doc.stringify('json', 'policy')` (Python: `limitr.doc.string_export('json', 'policy')`) exports the policy with its customers as JSON (or YAML, TOML, or Stof), and
`difference(otherLimitr)` diffs two policies.
