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

# Run Postgres, ClickHouse, and Simulated APIs in Agent Evaluations

Services are the databases, caches, and third-party APIs your app talks to. They run inside each trial's container, next to the app. You declare them on the [runner](https://laminar.sh/docs/agent-evaluations/eval-runner.md). In each trial of an [agent evaluation](https://laminar.sh/docs/agent-evaluations/introduction.md), `lmnr-cli` starts the services before your code runs. It runs their migrations and seeds them with the case's data.

Built-in services cover Postgres, ClickHouse, and Valkey. Simulated SaaS APIs, such as Slack, Linear, and GitHub, come from [Rystic](https://www.rystic.ai).

For example, an app that uses Postgres, ClickHouse, Valkey, and Slack would declare the services below. Declare only the services your own app uses, at the versions it runs.

```python Example: evals/support/agent/eval.py theme={null}
from lmnr.evals import ClickHouse, EvalRunner, Postgres, Rystic, Valkey, case_fixture

class SupportEval(EvalRunner):
    services = [
        Postgres("16", database="support", migrations="../../../migrations",
                 seed=case_fixture("accounts.sql")),        # DATABASE_URL
        ClickHouse("25.8", database="analytics",
                   migrations="../../../clickhouse/migrations"),  # CLICKHOUSE_URL
        Valkey("8"),                                         # REDIS_URL
        Rystic("slack", version="0.0.31", seed=case_fixture("slack.json"),
               env={"SLACK_API_URL": "{url}/api/"}),
    ]
```

## How services run

* **When the image is built**, `lmnr-cli` copies each service's binaries from the vendor's official image, at the version you pinned. It also copies the service's migrations into the image. Changes to your app don't reinstall the services.
* **In each trial, before `setup()`**, all services start in parallel. Each one runs on `127.0.0.1` as its own OS user, and logs to `/logs/agent/<name>.log`. Each service waits until it's ready, runs its migrations, and loads the case's seed. See [the life of a trial](https://laminar.sh/docs/agent-evaluations/concepts.md#the-life-of-a-trial). Then its connection env, such as `DATABASE_URL`, is added to all later commands, including your app's.
* If a service fails to start or migrate, the trial fails. The error shows the end of the service's log.

**Pin the version production runs.** The version is required. `"latest"` works, but it prints a warning on each run.

**Point the app at the service through the app's own config.** Each service sets env vars from templates. The defaults are `{"DATABASE_URL": "{url}"}` for Postgres, `CLICKHOUSE_URL` for ClickHouse, and `REDIS_URL` for Valkey. Rename them to match your app's config, for example:

```python Example theme={null}
Postgres("16", env={"PGHOST": "{host}", "PGPORT": "{port}", "APP_DB": "{url}"})
```

The templates are `{url}`, `{host}`, `{port}`, `{database}`, `{user}`, and `{password}`. A variable a service sets can't also be in the runner's `env`.

## Migrations

`migrations=` takes the folder where your app keeps its schema. It can be anywhere in the repo. The path is relative to the file that declares the service. `lmnr-cli` copies the folder into the image, so `--remote` trials have it too. Editing a migration rebuilds one small last layer.

Reproduce what the app's own startup does, in the same order:

1. Extra roles and databases.
2. The migrations.
3. Anything the app creates in code after the migrations. This goes in `setup()`.

Your app may have no migrations, for example because another service manages its schema. Then create only the tables and columns that the tested code path needs. Put them in a SQL folder next to `eval.py`.

## Seed data

`seed=` loads data into a service after its migrations and before `setup()`:

* `seed=case_fixture("accounts.sql")` loads each case's own `tests/fixtures/accounts.sql`. The agent doesn't see `tests/` as files, and the seed is deleted from the container once loaded. A case without the file starts with empty tables. Pass `required=True` to make a missing file an error.
* A plain path, `seed="baseline.sql"`, loads the same file in all cases. Keep it inside the `evals/` folder (see [Where the code runs](https://laminar.sh/docs/agent-evaluations/concepts.md#where-the-code-runs)).

Some data needs computing, or comes from several files. Seed it in `setup()` instead, with the service's helpers or with a script that `ctx.container.run_file` runs.

## Postgres

```python Example theme={null}
Postgres(
    "16",
    database="support",                       # default "app"
    user="postgres", password="postgres",     # the defaults; both are in the URL
    migrations="../../../migrations",         # *.sql in natural order, subfolders skipped
    extensions=["pg_trgm"],                   # created before the migrations
    init_sql=["CREATE ROLE readonly"],        # run before the migrations
    seed=case_fixture("accounts.sql"),
)
```

* `migrate="cd /srv/app && alembic upgrade head"` runs your app's own migration command instead of a SQL folder. It runs in the container with the service's env.
* `migrate_at="build"` runs plain SQL migrations while the image is built, so each trial starts from a migrated database.
* `source="pgvector/pgvector:pg16-bookworm"` takes the binaries from a compatible image that has extras. Here, the extra is pgvector, enabled with `extensions=["vector"]`.
* Helpers:
  * `await self.service(Postgres).query(ctx, sql)` returns rows as dicts.
  * `.execute(ctx, sql)` runs SQL.
  * `.insert(ctx, "users", rows)` inserts a list of dicts.

## ClickHouse

```python Example theme={null}
ClickHouse(
    "25.8",
    database="analytics",
    migrations="../../../clickhouse/migrations",
    config="../../../clickhouse/config.xml",  # merged over the server's defaults
    users="../../../clickhouse/users.xml",
    seed=case_fixture("events.sql"),
)
```

* By default, migrations run with the [`clickhouse-migrations`](https://www.npmjs.com/package/clickhouse-migrations) CLI. It takes files named like `1_init.sql`, and records the versions it applied in `_migrations`. If your app applies migrations some other way, use `migrator="clickhouse-client"`. It runs all `*.sql` files in natural order.
* `config=` and `users=` merge production's server and user settings over the defaults. Keep the ports in these files the same as `http_port` and `tcp_port`. Leave the `default` user without a password.
* Helpers: `.query(ctx, sql)`, `.execute(ctx, sql)`, and `.insert(ctx, table, rows)`.

## Valkey

`Valkey("8")` runs a Redis-compatible server and sets `REDIS_URL`. Its helper sends one command: `await self.service(Valkey).cmd(ctx, "SET", "k", "v")`.

## Other services

For anything else you can run in the container, declare a custom service. For example, say production serves your app behind nginx. Then you can run nginx in front of the app in the container. This example installs nginx from Debian's packages, with a config that proxies to the app:

```python Example: evals/support/agent/eval.py theme={null}
from lmnr.evals import Service, port

# Proxies port 8000 to your app on 8080, which setup() starts.
NGINX_CONF = """\
server {
    listen 127.0.0.1:8000;
    location / { proxy_pass http://127.0.0.1:8080; }
}
"""

Service.custom(
    "nginx",
    "1.26",
    install=[
        "RUN apt-get update && apt-get install -y --no-install-recommends nginx"
        " && rm -rf /var/lib/apt/lists/*",
        f"COPY <<'EOF' /etc/nginx/sites-enabled/default\n{NGINX_CONF}EOF",
    ],
    start="nginx -g 'daemon off;'",
    ready=port(8000),
    port=8000,
    env={"APP_PUBLIC_URL": "{url}"},
)
```

* `install=[...]` adds Dockerfile lines to the final image. Here, they install the package and write the config file. To copy a binary from another image instead, pass that image as `source=` and the paths as `bundle=[paths]`. `lmnr-cli` copies those paths and the shared libraries they need.
* `start` must stay in the foreground. That's why nginx gets `daemon off;`. A process that exits counts as crashed.
* `ready` and `port` tell the runner when the service is up and what `{url}` is.

Your app may have an in-memory or local-disk fallback for a queue or a cache. If production also supports that fallback, you can use it in evals by leaving the queue's or cache's URL unset.

## Simulated SaaS APIs with Rystic

A simulator answers in place of a third-party API, such as Slack, Linear, or GitHub. The app talks to it through its usual base-URL setting. Each case seeds the simulator with its own data. `verify()` reads what the app did to it. Rystic simulators run inside the trial's container like any other service. For example, the [quickstart's example](https://laminar.sh/docs/agent-evaluations/quickstart.md#services) seeds a Slack workspace for each case:

```python Example: evals/billing/agent/eval.py theme={null}
from lmnr.evals import Rystic, case_fixture

Rystic(
    "slack",
    version="0.0.31",
    seed=case_fixture("slack.json", required=True),
    env={"SLACK_API_URL": "{url}/api/"},
)
```

* `version` pins the simulator. Each trial downloads that version before it starts.
* `seed=case_fixture("slack.json")` loads the case's workspace: its users, channels, and messages. A case without the file starts with an empty workspace.
* `env` templates take `{url}` and `{port}`. Point your app's existing base-URL setting at the simulator. The example uses `SLACK_API_URL` to point the official Slack SDK at it.

In `verify()`, read what the app did. For example:

```python Example theme={null}
slack = self.service(Rystic)
calls = await slack.calls(ctx)       # every API call the app made, in order
state = await slack.state(ctx)       # the simulated workspace after the run
history = await slack.get(ctx, "/api/conversations.history", channel="C0BILLING")
```

In `run()`, `await slack.settle(ctx)` waits until the app has stopped calling the simulator. With a [separate verifier](https://laminar.sh/docs/agent-evaluations/eval-runner.md#grade-in-a-separate-container), set `snapshot=True`, so the state and the calls are saved after the run.

### Rystic access

* **Local runs** use your own Rystic API key. Create one at [rystic.ai](https://www.rystic.ai/account/api-keys). Slack, Linear, and GitHub are on the free plan. Put the key in `.env` as `RYSTIC_TOKEN`. `lmnr-cli eval run` passes it to the trials of datasets that have a Rystic simulator. Without the key, it stops before building anything, with exit code `19`.
* **`--remote` runs** don't need your key. Laminar gives each trial its own access to Rystic.

Don't put `RYSTIC_TOKEN` in the runner's `env` or `secrets`. On a `--remote` run, it would replace the trial's own access.

## Base image compatibility

Services need glibc 2.36 or newer in the image: Debian bookworm or trixie, or Ubuntu 24.04. The `Image` builder's bases are all trixie. On an older base, pass an official image built on an older distribution as `source=`, such as `Postgres("16", source="postgres:16-bullseye")`. Alpine images can't run services.

ClickHouse's default migrator needs glibc 2.38 (trixie, Ubuntu 24.04). On a bookworm base, pass `migrator="clickhouse-client"`. Otherwise, the build stops with that hint.

## Next steps

> [card] [Mocks](https://laminar.sh/docs/agent-evaluations/mocks.md)
>
> Answer for an internal service or an observed function.

> [card] [Match production](https://laminar.sh/docs/agent-evaluations/production-harness.md)
>
> What to run for real, what to simulate, and what to mock.

> [card] [Write eval.py](https://laminar.sh/docs/agent-evaluations/eval-runner.md)
>
> The runner's attributes, its phases, and the `ctx` API.

> [card] [Build the image](https://laminar.sh/docs/agent-evaluations/image.md)
>
> Bases, dependencies, and source, or an existing Dockerfile.


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