> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mirage.strukto.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Limits

> Limits that stop one agent's commands from starving other agents or the host.

A line an agent writes can loop forever, start processes without end, or grow
a variable until memory runs out. In Mirage it runs beside other agents'
sessions, in one process or one isolate, so each of these would cost them too.
Every limit below is on by default except `max_workspaces` and `capacity`,
and each stops
its case the way bash and Linux would, with the same exit status.

Three layers set them:

* **The host** (the server, or a Cloudflare app) sets ceilings. A workspace may
  set a lower value, never a higher one. A workspace that sets `null` (no
  limit) gets the ceiling.
* **The workspace** sets each limit for every session it holds.
* **A profile** overrides `processes` and `command_limits` for its
  sessions, field by field over the workspace's. It may raise a workspace's
  value as well as lower it; only a host ceiling holds it.

## What each limit stops

| Case | Limit | Default | What the line sees |
| - | - | - | - |
| A loop that never ends | [`command_limits` `@line` `timeout_seconds`](#line-time) | 600 seconds | exit 124, `line: timed out after 600s` |
| A fork bomb, `b() { b \| b; }; b` | `processes.max` | 128 per session | exit 254, `bash: fork: Resource temporarily unavailable` |
| A variable that keeps doubling, `x=$x$x` | `max_env` | `2MB` per session | exit 2, `bash: xmalloc: cannot allocate N bytes (past max_env of N bytes, a mirage workspace setting)` |
| A file or a command's output held in memory | [`max_memory`](#memory) | `96MB` per workspace | exit 1, `line: memory exhausted`; a write to a RAM file fails with `Disk quota exceeded` |
| One API reply read whole | `max_body_bytes` | `64MB` | the call fails |
| A command printing a huge result | [`command_limits`](#command-output) `max_lines` | 2,000 lines for `cat`, `grep`, `rg`, `head` and `tail` | the output is cut, with a notice on stderr; the exit code is kept |
| A walk over a huge mount | `command_limits` [`walk_limit`](https://docs.mirage.strukto.ai/home/integration/search#walk_limit) | set by each VFS | the walk stops at the limit |
| A mount filling up | [`capacity`](https://docs.mirage.strukto.ai/home/setup/vfs#mount-capacity) on a RAM, disk, Redis, OPFS or SQL mount | no cap | `Disk quota exceeded` |
| The read cache growing | [`cache.limit`](https://docs.mirage.strukto.ai/home/infrastructure/file-cache) | `32MB` in memory. Redis removes nothing at its `limit`: cap it with Redis's own `maxmemory` | nothing; see File Cache |
| Deep recursion in functions, `source`, `eval` or `bash -c` | 32 levels | fixed; `FUNCNEST` can lower it | exit 1, `environment: line 1: f: maximum function nesting level exceeded (32)` |
| Many sessions on one workspace | `max_sessions` | 16, or 4 on Cloudflare Workers | HTTP 429 |
| Many workspaces on one server | `max_workspaces` | no cap | HTTP 503 |
| A burst of requests | `rate_limits` | `ip=1000/minute` | HTTP 429 |

What each limit counts:

* **`max_env`:** bytes in a session's variables, functions, aliases and
  positional parameters, plus 1 per array element and parameter.
  * A session that would start over it, from `env`, a profile or a
    snapshot, is refused.
* **`processes.max`:** pipeline stages, subshells and background jobs
  running in the session.
* **`max_body_bytes`:** decoded bytes of one API reply read whole.
  * A call's own cap, or the memory left under `max_memory`, can stop it
    sooner.
  * An error reply keeps only its first 64 KiB.

For how the `timeout` command stops jobs, see [Shell](https://docs.mirage.strukto.ai/home/core/shell.md).

Some bounds are fixed:

* A session id, profile name or workspace id is 1 to 128 characters, with no
  control characters.
* A command log read returns the newest 10,000 entries, and `/.bash_history` the
  newest 10,000 commands. A workspace that keeps its command logs in memory holds
  at most 8 MB of logs, and drops the oldest entries first.

## Set them on a workspace

```yaml theme={null}
max_memory: 32MB
max_env: 2MB
processes: {max: 64}
command_limits:
  "@line": {timeout_seconds: 120}
profiles:
  batch:
    processes: {max: 512}
    command_limits:
      "@line": {timeout_seconds: 900}
```

Here a `batch` session runs 512 processes and 15-minute lines, and every other
session 64 processes and 2-minute lines. See
[configuration](https://docs.mirage.strukto.ai/home/configuration/workspace.md) and
[profiles](https://docs.mirage.strukto.ai/home/configuration/session.md).

## Command output

`cat`, `grep`, `rg`, `head` and `tail` print at most 2,000 lines by default.
`command_limits` sets a cap on the workspace, on a mount for the commands that
run on it, or on a profile for its sessions:

```yaml YAML theme={null}
mounts:
  /data:
    vfs: ram
    mode: write
    command_limits:
      grep: {max_lines: 50, on_exceed: error}
command_limits:
  head: {max_lines: 500}
profiles:
  researcher:
    command_limits:
      head: {max_lines: 5000}
```

```python Python theme={null}
from mirage import MountMode, Workspace
from mirage.types import Limit, OnExceed
from mirage.vfs.ram import RAMVFS

ws = Workspace(
    {
        "/data": (RAMVFS(), MountMode.WRITE, {
            "grep": Limit(max_lines=50, on_exceed=OnExceed.ERROR),
        }),
    },
    mode=MountMode.WRITE,
    command_limits={"head": Limit(max_lines=500)},
    profiles={
        "researcher": {"command_limits": {"head": Limit(max_lines=5000)}},
    },
)
```

```ts TypeScript theme={null}
import { Limit, MountMode, OnExceed, RAMVFS, Workspace } from '@struktoai/mirage-node'

const ws = new Workspace(
  {
    '/data': [
      new RAMVFS(),
      MountMode.WRITE,
      { grep: new Limit({ maxLines: 50, onExceed: OnExceed.ERROR }) },
    ],
  },
  {
    mode: MountMode.WRITE,
    commandLimits: { head: new Limit({ maxLines: 500 }) },
    profiles: { researcher: { commandLimits: { head: new Limit({ maxLines: 5000 }) } } },
  },
)
```

| Field | Caps |
| - | - |
| `max_lines`, `max_bytes` | A command's printed output; `null` for no cap |
| `on_exceed` | `truncate` (default) prints the capped output, a notice on stderr and keeps the exit code; `error` drops the output and exits 1, so `&&` and `\|\|` see a failure |
| `walk_limit` | The entries one walk lists on a mount, `-1` for no cap; see [walks](https://docs.mirage.strukto.ai/home/integration/walks.md) |
| `timeout_seconds` | A line's time, on the `@line` entry only; see [Line time](#line-time) |

* A key is a command's name, `"@all"` for every command, or `"@line"` for the
  whole line. Any other `@` key, or `*`, is refused.
* Each field comes from the most specific entry that sets it: the profile,
  the mount, then the workspace (each by the command's name, then
  `"@all"`), then the command's own default. An entry that sets one field
  inherits the rest.
* A command spanning mounts takes the tightest limit among them.
* Caps apply to what a command prints. `cat big.txt; echo end` still prints
  `end`, and `cat big.txt | wc -l` counts every line, since input to a pipe,
  redirect or substitution is not cut.

## Line time

A line has one time limit: the `@line` entry's `timeout_seconds`, on the
workspace or a profile. It bounds the whole top-level line, with its loops,
pipelines and the lines it runs (`sh -c`, `eval`, `xargs`), and is 600
seconds unless set; `0` or `null` lifts it.

* A line past it exits 124 with `line: timed out after Ns`. A program it runs
  gets `TERM` and a second to finish, then `KILL`, as with `timeout -k`.
* A background job runs under the same limit, counted from its own start, and
  can outlive the line that started it.
* A mount takes no `@line` entry, since a line spans mounts. To bound one
  command inside a line, use `timeout 5 grep -r TODO /data`.

## Memory

A workspace's `max_memory`, a [size](https://docs.mirage.strukto.ai/home/configuration/workspace.md#sizes),
bounds the files in its RAM mounts and each object a command builds while it
runs: a `$( )` capture, a `read` value, a file read whole, a `jq -s` input,
the parts an `office` document links to (and, in a Word document or a deck,
their parsed elements), a stream `pdftotext` decodes, or a Monty, Pyodide or QuickJS program's memory. Such an object must fit in what
the RAM files leave. It is 96 MB unless set; `null` lifts it. Commands running
at once can each take close to what is left, so it bounds each object, not
their sum. The read cache has its own [limit](https://docs.mirage.strukto.ai/home/infrastructure/file-cache.md).

* A write that would pass it fails with `Disk quota exceeded`.
* A command whose object passes it fails with `<command>: memory exhausted`,
  and the line goes on. A capture or `read` that passes it ends the line with
  `line: memory exhausted` and exit 1.
* A `python3` run raises `MemoryError`, and a `node` run gets
  `InternalError: out of memory`.

> [accordion] What streams, and what still holds data whole
>
> * `gzip`, `gunzip`, `zgrep`, `iconv -o`, `tar`, `sort`, `split`,
>   `csplit`, redirects and script output stream, or spill to scratch
>   storage. A `tar` member of unknown size is staged before its header is
>   written. `zip` copies unchanged members but reads the whole archive to
>   update it.
> * A single large record, archive metadata, `awk` arrays, `tac` with a
>   regex, `diff`, `patch` and `jq --slurp` keep their working data in
>   memory, and a whole-result API call collects its output.
> * `rg` limits each search's scratch storage to 64 MiB and refuses a pattern
>   that would need more; `--regex-size-limit` governs compilation only.
> * Disk, SSH, OPFS, GridFS, Drive, Dropbox, OneDrive, SharePoint and Box
>   write by streaming upload. S3 uploads in 8 MiB parts, up to 10,000 parts
>   (about 78 GiB). A presigned or conditional write to a custom S3 endpoint
>   is one PUT of at most 5 GiB, and an append to S3 uploads the object
>   again.
> * Streaming bounds memory, not CPU: compression and comparison cost the
>   same, and spilling adds local I/O.

## Host ceilings

A tenant controls its own workspace's config and profiles, so a host that
runs other people's agents holds them under ceilings. Each comes from the
app's option, else its environment variable, else its key in
`~/.mirage/config.toml`:

| Key | Env var | Holds |
| - | - | - |
| `max_memory` | `MIRAGE_MAX_MEMORY` | any workspace's `max_memory` |
| `max_env` | `MIRAGE_MAX_ENV` | any workspace's `max_env` |
| `max_processes` | `MIRAGE_MAX_PROCESSES` | any session's `processes.max` |
| `max_line_seconds` | `MIRAGE_MAX_LINE_SECONDS` | any line's time limit |
| `max_sessions` | `MIRAGE_MAX_SESSIONS` | the sessions each workspace holds |
| `max_workspaces` | `MIRAGE_MAX_WORKSPACES` | the workspaces the server holds |

```toml theme={null}
[daemon]
max_memory = "64MB"
max_env = "2MB"
max_processes = 64
max_line_seconds = 300
max_sessions = 8
```

The ceilings hold whatever sets the value: a create request, a profile
replaced over HTTP, or a snapshot loaded later. The
[Python](https://docs.mirage.strukto.ai/python/access/server.md) and [TypeScript](https://docs.mirage.strukto.ai/typescript/access/server.md)
servers and the [Cloudflare app](https://docs.mirage.strukto.ai/typescript/cloudflare-quickstart.md) take the
same settings as options.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.