# Query with SQL

> Ask questions about invocations, journals, state and usage with read-only SQL over POST /query.

Source: https://cairnflow.dev/docs/query

Everything cairnflow knows about your environment can be read with SQL: invocations and their
state, journals, timers, promises, streams, deployments, schedules and usage. Queries are
read-only, run across every node of the cell, and see only your environment's data.

Use it from the console's **Query** page, or over HTTP:

```sh
curl -X POST "$CAIRN_URL/query" \
  -H "authorization: Bearer $CAIRN_KEY" \
  -H "content-type: application/json" \
  -d '{"sql": "SELECT service, class, sum(count) AS n FROM sys_invocation_counts GROUP BY service, class"}'
```

You need a key or console role that can read the environment: an **Admin** key, or a console
session of an owner, admin, member or viewer. An Invoke only key cannot query.

## Request and response

| Field | Meaning |
|---|---|
| `sql` | One read-only statement |
| `params` | Values for `$1 … $n`: strings, integers, booleans or `null` |
| `allow_partial` | Default `true`. `false` turns a partial answer into a `503` |
| `timeout_ms` | Default 10,000; at most 30,000 |

```json
{
  "columns": [{ "name": "service", "type": "…" }, { "name": "n", "type": "…" }],
  "rows": [["Chat", 42], ["Greeter", 7]],
  "partial": false,
  "warnings": [],
  "read": 12,
  "ms": 3
}
```

Times come back as ISO-8601 strings; numbers and booleans keep their type. `read` is the number of
read units the query used.

### Parameters

Pass values separately instead of writing them into the SQL text. They are bound before the query
is planned and never become SQL:

```json
{
  "sql": "SELECT id, class, created_at FROM sys_invocation WHERE service = $1 AND key = $2",
  "params": ["Chat", "chat-42"]
}
```

Parameters are positional and consecutive (`$1`, `$2`, …), with exactly one value each. Named
parameters, floats, arrays and objects are refused.

## The tables

| Group | Tables |
|---|---|
| Invocations | `sys_invocation` (one row per invocation), `sys_invocation_counts` (counts per service, handler and state) |
| Inside one invocation | `sys_journal`, `sys_timer`, `sys_attachment`, `sys_log`, `sys_span`, `sys_stream`, `sys_stream_record`, `sys_artifact`, `sys_outbox` |
| Objects and workflows | `sys_state`, `sys_value`, `sys_promise`, `sys_promise_waiter`, `sys_object`, `sys_vqueue_entry` |
| Scheduled work | `sys_schedule`, `sys_delayed` |
| Code | `sys_deployment`, `sys_service`, `sys_handler` |
| Usage and performance | `sys_metering`, `sys_artifact_bytes`, `sys_handler_stats`, `sys_handler_history`, `sys_slow_run` |
| History | `sys_archive`, `sys_audit` |

Columns and meanings are in the [table reference](/docs/query/tables).

**Some tables need a key.** Tables that read inside one invocation or one object require an
equality filter on their key, so a query never scans everything: `id = …` for `sys_journal`,
`sys_log`, `sys_artifact` and the other per-invocation tables; `service = … AND key = …` for
`sys_state`, `sys_value`, `sys_promise` and `sys_promise_waiter`. Without it the query is refused
with `400`.

## Questions operators ask

### What is stuck?

Invocations still running or waiting after an hour:

```sql
SELECT id, service, handler, status, created_at
FROM sys_invocation
WHERE class = 'active' AND created_at < now() - INTERVAL '1 hour'
ORDER BY created_at
LIMIT 50
```

Paused invocations (out of attempts, or stopped by an error that needs a person), with the last
error:

```sql
SELECT id, service, handler, last_failure_message, transitioned_at
FROM sys_invocation
WHERE class = 'paused'
ORDER BY transitioned_at DESC, id
LIMIT 50
```

Invocations waiting for a retry, and why the last attempt failed:

```sql
SELECT id, service, handler, attempt, retry_at, last_failure_code, last_failure_message
FROM sys_invocation
WHERE retry_at IS NOT NULL
ORDER BY retry_at
LIMIT 50
```

### What is one invocation waiting for?

```sql
SELECT index, name, entry_lite
FROM sys_journal
WHERE id = $1
ORDER BY index
```

In `entry_lite`, a command with `"completed": false` is still waiting for its result: a call, a
promise, a sleep. Pending sleeps are also in `sys_timer`:

```sql
SELECT completion_id, due_at_ms FROM sys_timer WHERE id = $1
```

The console's **Why it is in this state** panel answers the same question in words.

### What is failing?

```sql
SELECT id, service, handler, failure_code, failure_message, transitioned_at
FROM sys_invocation
WHERE class = 'failed'
ORDER BY transitioned_at DESC, id
LIMIT 50
```

Failed invocations per handler, from in-memory counters (reads nothing from storage):

```sql
SELECT service, handler, sum(count) AS n
FROM sys_invocation_counts
WHERE class = 'failed'
GROUP BY service, handler
ORDER BY n DESC
LIMIT 10
```

Common failure codes: `572` cancelled, `575` out of attempts, `578` journal too long. See
[Errors](/docs/reference/errors).

### What is slow?

Handlers by turn latency over the recent window:

```sql
SELECT service, handler, sum(turns) AS turns, sum(failed) AS failed, max(p99_ms) AS p99_ms
FROM sys_handler_stats
GROUP BY service, handler
ORDER BY p99_ms DESC
LIMIT 10
```

Invocations that took longer than ten seconds end to end:

```sql
SELECT id, service, handler, duration_ms
FROM sys_invocation
WHERE duration_ms >= 10000
ORDER BY created_at DESC, id
LIMIT 50
```

Long journals, which cost more on every resume in request-response mode:

```sql
SELECT id, service, handler, journal_len
FROM sys_invocation
WHERE journal_len >= 100
ORDER BY created_at DESC, id
LIMIT 50
```

### How much is used?

The current hour:

```sql
SELECT hour, invocations, steps, run_ms, input_tokens, output_tokens, units
FROM sys_metering
```

Completed, failed and compute units per hour, from a start time in milliseconds:

```sql
SELECT hour_ms, sum(completed) AS completed, sum(failed) AS failed, sum(cu) AS cu
FROM sys_handler_history
WHERE hour_ms >= $1
GROUP BY hour_ms
ORDER BY hour_ms
```

Tokens of one agent turn, per model call:

```sql
SELECT name, input_tokens, output_tokens
FROM sys_span
WHERE id = $1 AND input_tokens IS NOT NULL
```

### Find an invocation

By object key, idempotency key, tag, parent or whole call tree:

```sql
SELECT id, handler, class, created_at FROM sys_invocation
WHERE service = 'Chat' AND key = 'chat-42'
ORDER BY created_at DESC, id LIMIT 50;

SELECT id, service, handler, class FROM sys_invocation
WHERE idempotency_key = 'order-42' LIMIT 10;

SELECT id, parent_id, service, handler, class FROM sys_invocation
WHERE root_id = $1 ORDER BY id;
```

Send one statement per request; the block above shows three.

## Consistency

- **Only durable data.** A query sees rows that are committed to storage. It never waits for, or
  slows down, the invocations it reads. When the node ships the query worker, each statement runs
  in a separate worker process, apart from the engine.
- **Counts are exact** as of the last commit of each key range: `sys_invocation_counts` is kept in
  memory and updated with each commit.
- **Partial answers are flagged.** If part of the data cannot be read (a node does not answer, or
  an index is still being built after a change), the answer has `partial: true` and a `warnings`
  entry per affected range (`reason` such as `indexing`). It never silently drops rows. Send
  `allow_partial: false` to get a `503` instead.
- **Live tables come from the API.** Deployments, services, schedules, statistics, usage, archive
  and audit tables are read through the same API the console uses, with your key's permissions.

## Limits and errors

| Answer | Cause |
|---|---|
| `400` | SQL syntax error, unknown table or column, a statement that is not read-only (DDL, DML, `COPY`, `SET`), table functions, recursive CTEs, file reads, a keyed table without its key, or a statement too large to plan: over 64 KiB of text, more than 500 operators, more than 64 joined tables or more than 64 query blocks (`SELECT`, `UNION`, …) |
| `422`, `error` starting with `query_budget:` | The query would read more than 200,000 read units, use more than 128 MiB, run longer than its timeout, or return more than 10,000 rows. Add a `LIMIT` or filter on an indexed column (`service`, `class`, `created_at`, `id`) |
| `429` | More than 4 queries at once on a node or 2 of your environment's, or your environment used up its read units for now (`error` starting with `query_budget:`). Retry shortly |

A query either completes or fails: an error never comes back as a truncated `200`.

`sys_invocation` is stored in `created_at DESC, id` order, so "newest first" lists with a `LIMIT`
are cheap. Filters on `id`, `service`, `handler`, `key`, `kind`, `class`, `root`, `parent_id`,
`root_id`, `schedule`, `deployment`, `restarted_from`, `created_at`, `transitioned_at` and
`duration_ms` are applied during the scan; filters on other columns are applied after reading,
so combine them with one of these.

## Next

- [Table reference](/docs/query/tables)
- [The console](/docs/cloud/console)
