2026-11-26 15:39 UTC

Belay brings Lean-checked proofs and counterexample search to a subset of SQLite migrations

state: seedheat: mediumuncertainty: mediumrelevance: mediumformal-verification sqlite coding-agentsTzankoLean

What is this?

Belay is an open-source Lean 4 library by developer Tzanko Matev for checking claims about SQLite queries and migrations. Its public GitHub project describes a workflow in which a bounded search can find counterexamples, while Lean proofs can establish claims that its kernel checks. The project gives an example of detecting a migration that silently deletes related rows, then proving a corrected migration preserves query results. Belay is available to use as a Lean project dependency. The author says it models a subset of SQLite 3.51.0 and rejects unsupported SQL rather than approximating it. The evidence gives conflicting differential-test counts: the Hacker News post says 5,768 cases; the linked README says 5,525. The author also notes that not every model rule has had human audit.

Why it matters

Belay explores a practical bridge between formal methods and everyday database work: coding agents can search for failing cases and write proofs, while Lean's kernel checks the proofs. If the model becomes broad and trustworthy, this could catch subtle migration and data-integrity bugs that ordinary tests miss, and make stronger guarantees easier to include in agent-assisted development. For now, its scope is limited to a subset of one database engine, and it does not cover important behavior such as concurrency or crash semantics.

Current assessment

New: Belay is publicly available as an open-source Lean 4 library for a supported subset of SQLite 3.51.0; the README specifies dependency revision v0.2.0. The author describes two complementary mechanisms: #sql_check searches small databases for counterexamples, and Lean proofs can establish claims such as whether a migration preserves query results across databases with a specified schema. The proof is kernel-checked, but that guarantee concerns the modeled semantics, not all real-world SQLite behavior. The README’s example shows a migration that loses rows through foreign-key cascades and a corrected version with a preservation theorem. The author reports differential testing against native SQLite, but the supplied sources disagree on the number of cases (5,768 in the Show HN post versus 5,525 in the README); treat the count as unresolved. The author says unsupported SQL is rejected, some model rules have not been human-audited, and the model excludes query plans, locks, concurrency, and crash behavior. Broader engine/version coverage and shorter proofs are stated as future challenges, not completed capabilities. The author is seeking design partners; the supplied evidence does not establish adoption or independent validation. This is a technically notable experiment in making formal verification agent-compatible, with current utility chiefly for workloads that fit the modeled SQLite subset.

Measured heat

now 0 pts/hpeak 4 pts/hcomments 0/hpeers p10momentum: steady2 platformsage 362h
points/hour across evidence · reading as of 2026-11-27 02:23:58.509736+11:00 · deterministic, not a model opinion

How the heat travelled

11-11 13:00⭐ origin echo-reconstructedThe primary source is Tzanko Matev’s own project write-up, linked from the HN post. It begins: “An agent writes a migration in ten seconds,
Tzanko Matev on blog (echo) · attributed from hn.story.50531208
—
11-17 13:40first on hacker news · published · +144.7hShow HN: Belay – formal verification for SQLite migrations and queries in Lean 4
neprotivo
—
11-17 13:40amplified on hacker news 👑hn.story.50531208
neprotivo
peak 4 · 0 comments · 99% of case engagement
11-17 14:20our radar first saw it · +145.3hdiscovery anchor: hn.story.50531208—
pace: p35 vs 1845 stories at the 336h mark (now 362h old) — ahead of adobe-max-ai-agents-creative-tools-mcp (1.5x), behind 42loop-agent-operated-product-experiment (0.8x)

Evidence (2) — ⭐ canonical anchor

sourceobjectauthorscorecomments
🟧 hnShow HN: Belay – formal verification for SQLite migrations and queries in Lean 4
Retrieved article excerpt

Open article · Retrieved 2026-11-17T14:23:06.002244+00:00

# Belay

Belay is a Lean library to prove facts about SQLite databases, statements and
migrations. You write SQL, state what must hold, and Lean checks it:
with a search that finds the rows that break a claim, or with a proof that
Lean's kernel verifies.

[A recording of 20 seconds in the editor. The check finds a database on which a migration deletes the sessions. Lean then checks a proof that the fixed migration keeps them on every database.](https://github.com/vihren-dev/belay/blob/main/docs/media/belay-demo.gif)

## An example

This example is a migration that can lose data. The same mistake deleted a
table of a Rails application
([write-up](https://kyrylo.org/software/2025/09/27/a-mere-add-foreign-key-can-wipe-out-your-whole-rails-sqlite-production-table.html)).
The task is to make a table a STRICT table.

The database has this schema. It has no rows: you do not know which data
breaks a migration.

```
import Belay
open Belay.Sqlite

def shop : Database := db! r"
  CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT, email TEXT NOT NULL);
  CREATE TABLE sessions (id INTEGER PRIMARY KEY,
    customer_id INTEGER NOT NULL REFERENCES customers(id) ON DELETE CASCADE,
    expires_at INTEGER NOT NULL);"
```

This migration makes `customers` a STRICT table. SQLite cannot do that in
place, so the migration copies the table, drops the old one and renames the
copy.

```
def badMigration : Script := sql r"
  PRAGMA foreign_keys = ON;
  BEGIN;
  PRAGMA foreign_keys = OFF;
  CREATE TABLE customers_new (id INTEGER PRIMARY KEY, name TEXT, email TEXT NOT NULL) STRICT;
  INSERT INTO customers_new SELECT id, name, email FROM customers;
  DROP TABLE customers;
  ALTER TABLE customers_new RENAME TO customers;
  COMMIT;"
```

The migration has a mistake that is difficult to see: `PRAGMA foreign_keys`
does nothing inside a transaction, so foreign keys stay on. `DROP TABLE customers` then deletes the customers row by row, and `ON DELETE CASCADE`
deletes the sessions of each customer.

### The counterexample

A correct migration must keep the result of this query:

```
def allSessions : Script := sql r"SELECT id, customer_id, expires_at FROM sessions"
```

This command tries to prove that claim or to find a counterexample. `on shop`
limits the claim to the databases with the schema `shop`, and the check
searches those databases:

```
#sql_check badMigration preserves allSessions on shop
```

The output is:

```
SQL check: false.
Database:
customers:
  id | name | email
  1  | NULL | ''
sessions:
  id | customer_id | expires_at
  1  | 1           | 0
allSessions: rows [[1, 1, 0]]
badMigration, statement 1: done 0
badMigration, statement 2: done 0
badMigration, statement 3: done 0
badMigration, statement 4: done 0
badMigration, statement 5: done 1
badMigration, statement 6: done 0
badMigration, statement 7: done 0
badMigration, statement 8: done 0
Construction:
CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT, email TEXT NOT NULL);
…
SQLite replay:
.bail off
CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT, email TEXT NOT NULL);
…
```

Belay wrote one customer and one session, the smallest database of the schema
that breaks the claim, and every statement of the migration reported success.
The editor prints the whole block. Paste the replay script into the `sqlite3`
shell and watch native SQLite do the same.

### The fact, in the kernel

Keep the rows that Belay found, and state the fact as a theorem of the file:

```
def found : Database := db! r"
  CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT, email TEXT NOT NULL);
  CREATE TABLE sessions (id INTEGER PRIMARY KEY,
    customer_id INTEGER NOT NULL REFERENCES customers(id) ON DELETE CASCADE,
    expires_at INTEGER NOT NULL);
  INSERT INTO customers VALUES (1, NULL, '');
  INSERT INTO sessions VALUES (1, 1, 0);"

example : (found.run badMigration).outputs.allOk = true ∧
    ((found.run badMigration).db.run allSessions).outputs.getLast? = some (.rows []) := by
  decide +kernel
```

Every statement of the migration succeeds, and the session is gone. Lean's
kernel ran SQLite's semantics and certified both, and does so again on every
build.

### The fix and the proof

```
def fixedMigration : Script := sql r"
  PRAGMA foreign_keys = OFF;           -- before the transaction, where it takes effect
  BEGIN;
  CREATE TABLE customers_new (id INTEGER PRIMARY KEY, name TEXT, email TEXT NOT NULL) STRICT;
  INSERT INTO customers_new SELECT id, name, email FROM customers;
  DROP TABLE customers;
  ALTER TABLE customers_new RENAME TO customers;
  COMMIT;
  PRAGMA foreign_keys = ON;"           -- on again after the commit

example : (found.run fixedMigration).outputs.allOk = true ∧
    ((found.run fixedMigration).db.run allSessions).outputs.getLast? = some (.rows [[1, 1, 0]]) := by
  decide +kernel
```

This theorem claims that on **every database** with the schema `shop`, the
query `allSessions` gives the same result after the fixed migration:

```
theorem fixed_keeps_sessions :
    fixedMigration preserves allSessions on shop
```

Your coding agent can prove such a claim, and Lean's kernel checks the proof.
The theorem is in [`TableRebuild.lean`](https://github.com/vihren-dev/belay/blob/main/examples/table-rebuild/TableRebuild.lean),
with the code of this section; its proof starts in
[`RebuildKeeps.lean`](https://github.com/vihren-dev/belay/blob/main/examples/table-rebuild/Proof/RebuildKeeps.lean).

## Try it on your schema

Put your `CREATE TABLE` statements in `db!`, your migration in `sql`, and state
`migration preserves read on schema` for the reads you care about. Without
`on schema`, the claim is about every database, also one with other tables and
triggers. `#sql_check` answers `false` with the
rows and a replay script, `proved`, or `unknown`. A counterexample becomes a
test with `sql_refute (db := found)`.

## What you can state

| The question | Notation | Who settles it |
| --- | --- | --- |
| Is the SQL valid against this schema? | `sql!`, `db!` | The elaborator, when the file compiles |
| Does it run without an error? | `succeeds`, `succeeds on`, `succeeds where` | `#sql_check` and tactics, or a proof |
| What does it do to the data? | `ensures`, `≈`, `preserves`, `preserves … on` | `#sql_check` and tactics, or a proof |
| Does the whole application behave the same? | `simulates` | A proof that you or an agent write |

The questions are independent. A migration that fails keeps every read, so
state `succeeds` together with `preserves`.

A fact about one run on one database, such as the two examples with
`found.run` above, is settled by Lean's kernel, which runs the statements. A
claim in the notation of the table is about every database. For such a claim,
`#sql_check` searches for a counterexample and tries the library's proofs, and
a proof by you or an agent settles the rest.

## Why trust it

Belay models a part of SQLite 3.51.0. The model is checked against SQLite's
own test suite and the project's corpora: 5,525 cases, replayed against native
SQLite and against the model, with no disagreement allowed. SQL outside the
model is refused. A proof is about the statements, not about locks, query
plans or concurrency; the [execution profile](https://github.com/vihren-dev/belay/blob/main/docs/execution-profile.md)
states the connection settings it assumes.

## Supported SQL

Tables with constraints, generated columns, `STRICT` and `WITHOUT ROWID`;
indexes, views and triggers; `ALTER TABLE`; transactions; `INSERT`, `UPDATE`
and `DELETE` with `RETURNING` and upserts; `SELECT` with joins, grouping,
ordering, limits, subqueries, common table expressions and compound queries;
the foreign-key and recursive-trigger pragmas. The exact list is in the
[supported subset](https://github.com/vihren-dev/belay/blob/main/docs/semantic-subset.md).

## Install

Install [elan](https://github.com/leanprover/elan), then add Belay to a Lake
project:

```
# lakefile.toml
name = "myproject"
defaultTargets = ["MyProject"]

[[require]]
name = "belay"
git = "https://github.com/vihren-dev/belay"
rev = "v0.2.0"

[[lean_lib]]
name = "MyProject"
```

When [Reservoir](https://reservoir.lean-lang.org) lists Belay, this shorter
requirement gives the same package. It works only after Reservoir lists the
package:

```
[[require]]
name = "belay"
scope = "vihren-dev"
rev = "v0.2.0"
```

```
lake update
lake build
```

The first build compiles the model and SQLite's parser once; later builds
reuse them. Then put the blocks above in a file of your project and open it in
an editor with the Lean language server. The folder
[`examples/table-rebuild`](https://github.com/vihren-dev/belay/blob/main/examples/table-rebuild) is a Lake project with the
example of this README and its proofs; open it in a clone of this repository.
The surface library's [README](https://github.com/vihren-dev/belay/blob/main/packages/belay/README.md) describes the
notation, SQL in separate files, and the options of the check.

## With a coding agent

An agent writes SQL, states claims, runs `#sql_check`, fixes the SQL when a
counterexample appears, and writes the proofs. The kernel checks the proof;
you review the claim, and `#explain` prints a claim in plain words.
[Use Belay with a coding agent](https://github.com/vihren-dev/belay/blob/main/docs/guide/agents.md) has the loop, the checks
of the agent's work. To start, tell your agent to set up Belay with the
[skill](https://github.com/vihren-dev/belay/blob/main/skills/belay/SKILL.md) of this repository.

## Documentation

- The [cheat sheet](https://github.com/vihren-dev/belay/blob/main/docs/cheat-sheet.md): how to define SQL, load it from
  files and state a claim.
- [Use Belay with a coding agent](https://github.com/vihren-dev/belay/blob/main/docs/guide/agents.md), with
  the [skill for the agent](https://github.com/vihren-dev/belay/blob/main/skills/belay/SKILL.md).
- The [surface library](https://github.com/vihren-dev/belay/blob/main/packages/belay/README.md): programs and runs, SQL in
  separate files, claims and the check.
- The [supported subset](https://github.com/vihren-dev/belay/blob/main/docs/semantic-subset.md) and the
  [execution profile](https://github.com/vihren-dev/belay/blob/main/docs/execution-profile.md).
- The [checked Lean API reference](https://github.com/vihren-dev/belay/blob/main/docs/development/api-reference.md) of the model.
- The examples under [`tests/surface`](https://github.com/vihren-dev/belay/blob/main/tests/surface), which CI compiles. The
  migration examples are in
  [`tests/surface/Schema/Tests`](https://github.com/vihren-dev/belay/blob/main/tests/surface/Schema/Tests).

## Community and support

Ask questions in [Discussions](https://github.com/vihren-dev/belay/discussions).
Report a case where the model and native SQLite disagree in
[Issues](https://github.com/vihren-dev/belay/issues), with the SQL, the output
of the `sqlite3` shell and the block that Belay printed. The project accepts
issues, reproductions of bugs and new test cases, and does not accept pull
requests that change code; [CONTRIBUTING.md](https://github.com/vihren-dev/belay/blob/main/CONTRIBUTING.md) has the details
and the build instructions.

## License

Project code is MIT licensed. SQLite is upstream public-domain software. Lean
and Nix dependencies retain their respective upstream licenses.
neprotivo40
🟧 echo.blog ⭐The primary source is Tzanko Matev’s own project write-up, linked from the HN post. It begins: “An agent writes a migration in ten seconds, Tzanko Matev——

Interpretation history

Decision trace