
# Invariants

An invariant is SQL in `agentcloud.toml` that returns the rows breaking a rule: no rows means it passes. `agc check` runs it on your mirror and shows up to three violating rows. `agc ship` runs it on a branch of production, and nothing goes live if it fails (exit 11).

```toml
[[check.invariant]]
name = "never overbooked"
sql  = "SELECT c.id FROM camps c JOIN bookings b ON b.camp_id = c.id AND b.status = 'confirmed' GROUP BY c.id, c.capacity HAVING count(*) > c.capacity"
```

## Ask your agent

```text
Add an Agent Cloud invariant that no camp ever has more confirmed bookings than its capacity, plus a smoke flow that tries to break it with twenty parents booking at once.
```

```text
A parent says they booked a camp but never saw the booking. Investigate on Agent Cloud, add a check that fails without your fix, and ship the fix with --fixes so the check stays.
```

## Steps

```bash runnable
agc up --detach
agc migrate
agc check
```

A passing invariant appears in `data.results` as `{"name": "never overbooked", "kind": "invariant", "ok": true, "detail": "no violations"}`. A failing one says how many rows and shows the first three, with numbers kept and text replaced by `‹text›` (example under Errors).

## How it works

Each ordinary (`hold = "empty"`) invariant runs in its own `BEGIN READ ONLY` transaction with a 30-second statement timeout, as a single statement (extended protocol). So `; DELETE …` can't escape, and a second statement is an error. Invariants run after the smoke flows, against the data those flows left behind, which is how a racing flow and an invariant together catch an overbooking.

In the rehearsal the queries run on an unmasked branch of production with `search_path = public`, and report only pass or fail. A failure reads "it found violations on a fresh branch of production; run agc check on your mirror to see them", and a query error gives a fixed sentence for its SQLSTATE, never the database's own text.

**Gating by migration.** `after` and `until` name a migration stem, compared with the database's `agentcloud_migrations` ledger (see Reference).

**Holds.** `hold` changes what "pass" means:

| `hold` | Passes when | Where it runs |
|---|---|---|
| `"empty"` (default) | The query returns no rows | `agc check` and every rehearsal |
| `"unchanged"` | The query's whole result (order-free) is the same before and after the migrations | Around `agc migrate` on the mirror, and around the migrations in a rehearsal that has any |
| `"equal:<check>"` | This query after the migrations returns exactly what the named invariant returned before | Same as `unchanged` |

`agc check` doesn't run `unchanged` or `equal:` checks itself. It reports what the last `agc migrate` proved, or `skipped: it’s checked around migrations, by agc migrate` if none has run. A query that couldn't run before the migrations (its column doesn't exist yet) passes an `unchanged` check as skipped, but fails an `equal:` one.

```toml
[[check.invariant]]
name = "approved spend in dollars"
sql  = "SELECT department, sum(amount) FROM requests WHERE status = 'approved' GROUP BY 1"
hold = "unchanged"

[[check.invariant]]
name = "spend survives the move to cents"
sql  = "SELECT department, sum(amount_cents) / 100.0 FROM requests WHERE status = 'approved' GROUP BY 1"
hold = "equal:approved spend in dollars"
```

This pair proves a backfill: the cents total after the migration equals the dollar total before it. Both read `amount`, directly or through the reference, so remove or rewrite them in the ship that drops `amount`. Give a referenced check a `hold` of its own (`unchanged` here). With the default `empty` it would also run as an ordinary invariant and fail, since it returns rows.

Every migration also gets a platform check you don't write: `no existing row was deleted` ([Safe schema changes](/docs/data/safe-schema-changes.md)).

**Retiring a check.** Change or remove a check only in the ship whose change makes it obsolete, and prefer `until` over deleting it, so the check keeps guarding the releases before that migration. Changing a [held check](#held-checks-and-fixes) goes to a person.

## Held checks and fixes

Once Agent Cloud holds a check, any ship that removes it or changes its definition waits for a person, who decides on the console. A ship that fixes a problem succeeds with `"outcome": "live"` and exit 0, and its new check is held from then on.

To fix a reported problem, reproduce it on the mirror, write a check that fails because of it, fix the code, run `agc check`, and ship with a short description of the report:

```bash
agc ship --fixes "parents saw no booking after booking"
```

| A check becomes held when | Recorded reason | When |
|---|---|---|
| It caught a bad release: an invariant found violations, or a smoke flow got a wrong answer | `it stopped v<N>` | As the rehearsal fails |
| It is new in a ship made with `--fixes` (not in the previous live release) | `added with the fix for: <text>` | When that release goes live |

A check that only failed to run (a broken query, a step that doesn't parse, no outbox) is broken, not a catch, so it isn't held. A `--fixes` ship doesn't hold checks that were already there.

**What counts as a change.** Agent Cloud compares the definition itself. For an invariant that's `sql`, `hold`, `after` and `until`, plus the definition of the check an `equal:` hold points at. For a smoke flow it's `steps` and `headers`. Any difference counts, including a stricter version or a new `until`. The order of keys in a `headers` table doesn't, so an unchanged check never goes to a person for that. Renaming a check counts as removing it.

**A ship that changes one** goes to a person whatever the app's autonomy, with a reason like `Removes or changes a check agent.cloud holds: "never overbooked" (it stopped v12).` It can't be approved with `agc approve` in the agent's session: held checks exist to stop the agent's own releases. When the release goes live, the held record follows the approved version, or is dropped if the check was removed.

**Letting a check go.** Held checks are listed on the console's Releases page, **Verifications** tab (`/console/apps/<app>/verifications`), with the source "Held by agent.cloud". The app's owner or an owner of its organization can press **Let go** there, and the next ship may then change or remove that check without asking. Letting go and approved changes are recorded in the app's events (`check.released`, `check.changed`).

## Reference

| Key | Type | Meaning |
|---|---|---|
| `name` | string | Shown in results; also the identity of a held check. Defaults to `invariant <n>` |
| `sql` | string | One statement that returns the violating rows |
| `hold` | string | `empty` (default), `unchanged` or `equal:<invariant name>` |
| `after` | string | Migration stem; reports `skipped: waits for <stem>` until it is applied. Use it for checks on a column a migration adds |
| `until` | string | Migration stem; reports `skipped: retired by <stem>` once it is applied. Use it to retire a check in the ship that makes it obsolete |

Any other key is ignored with a warning ([Lint warnings](/docs/checks/checks-overview.md#lint-warnings)).

`--fixes` text is trimmed, at most 200 characters ([Limits and quotas](/docs/reference/limits-and-quotas.md)). An empty value is dropped and holds nothing.

## Errors

Every code, its exit and fix: [Error code catalog](/docs/reference/error-code-catalog.md).

| Detail | Exit | Cause | Fix |
|---|---|---|---|
| `the query failed: …` | 11 | The SQL errored, timed out after 30 s, or tried to write | Make it one read-only statement |

A failing check on the mirror:

```json
{
  "ok": false,
  "product": "agent.cloud",
  "command": "check",
  "data": {
    "mirror": "main",
    "results": [
      { "name": "twenty parents race for the last spot", "kind": "smoke", "ok": true, "detail": "2 steps passed" },
      { "name": "never overbooked", "kind": "invariant", "ok": false, "detail": "1 violating row: id=17" }
    ],
    "warnings": []
  },
  "error": {
    "code": "check.failed",
    "message": "1 of 2 checks failed: never overbooked.",
    "fix": "Fix the change, not the check. Change a check only if this change makes it obsolete.",
    "retryable": false
  },
  "next": [{ "cmd": "agc check", "why": "run them again after fixing" }]
}
```

## Limits

| What | Value |
|---|---|
| Statement timeout | 30 s per ordinary invariant; 60 s per before/after preservation query |
| Rows shown on a failure | 3, mirror only |

## Agent notes

- For a test in a browser, use `[[verify]]` ([AI browser verification](/docs/checks/ai-browser-verification.md)); a `[[check.browser]]` table is ignored with a warning.
- Write the query to return violations, not to count them: `SELECT count(*) …` always returns one row and always fails.
- Don't depend on seed rows or on rows that may not exist in production; an invariant on an empty table passes trivially. Pair each invariant with a smoke flow that tries to break it.
- `after` and `until` don't gate `unchanged` and `equal:` checks.
- Loosening a held check doesn't get a ship through faster: the person on the console sees the held version next to yours.
- Strengthening an existing check to prove a fix is a change, not an addition, so `--fixes` doesn't hold it.

## Related

- [Checks overview](/docs/checks/checks-overview.md)
- [Smoke flows](/docs/checks/smoke-flows.md)
- [Safe schema changes](/docs/data/safe-schema-changes.md)
- [agc ship, end to end](/docs/ship/agc-ship-end-to-end.md)
- [Approvals](/docs/concepts/approvals.md)

<!-- feedback:start -->
---
Wrong, outdated or unclear? Run `agc feedback docs "checks/invariants: <what is wrong>" --body <file>` with the sentence quoted in the file. No code or app data is sent.
<!-- feedback:end -->
