Introduction
Elinvar finds holes in software designs before you write code.
You describe the things in your system (users, roles, orders, states), the links between them, and the rules. Then you state a promise that should never break. Elinvar exhaustively searches every small case up to a size you choose and either confirms that nothing breaks the promise up to that size, or hands you the smallest concrete counterexample showing exactly how it breaks.
It is a single Rust binary (and Rust library) inspired by Alloy, with no Java or runtime dependencies, built to be just as easy for people and AI coding agents to run.
What Elinvar helps you catch
- Permissions and access control: Can a user still read or edit a resource after losing a role or unfollowing an owner?
- Workflows and state machines: Is there a 3-step sequence of actions that leaves an order, lease, or lock in a broken state?
- Database schemas: Import your SQL
CREATE TABLEschema directly and check whether foreign keys,UNIQUE, andCHECKconstraints actually enforce your business rules. - Design changes: Compare two versions of a model with
elinvar diffto see whether a change tightened, loosened, or diverged from the old rules. - Over-constrained rules: Catch contradictory rules (
vacuous) instead of being fooled by a false “passes”, and see which rules actually did the work with--explain.
Where to start
- Want to try it right now? Start with the Quick start.
- Want real-world patterns? Browse Practical examples (permissions, state machines, SQL schemas, diffs, and vacuity traps).
- Using the CLI? See the Command-line reference.
- Testing designs in Rust? Read Checking designs in Rust.
- Connecting Claude Code, Cursor, or Codex? Read Using Elinvar with coding agents.
- New to formal design checking? Read Finding holes in a design.
- Coming from Alloy? Read Alloy, and what Elinvar takes from it.
- Contributing to Elinvar? Read the architecture overview, the design, the logic, and AGENTS.md.
This guide explains how to use Elinvar; the specifications decide edge cases. Where the two disagree, the specification wins.
Quick start
This page takes you from zero to finding and fixing your first design bug in a few minutes.
1. Install Elinvar
Elinvar is a single Rust binary with no Java, Python, or C runtime required.
cargo install elinvar
elinvar --version
(Or from a local checkout: cargo install --path crates/elinvar. A tagged release
also has binary archives on the
releases page.)
Check that it runs cleanly. You can get help for any command with elinvar --help or
elinvar <verb> --help.
2. Check your first design
Suppose you are designing a company reporting tree:
- Each employee has at most one manager.
- Rule: nobody can be their own manager.
- Promise: following managers upward from anyone always reaches someone at the top (someone with no manager).
Save this as hierarchy.als (or pipe it directly into elinvar with -):
sig Employee {
manager: lone Employee
}
fact NoSelfManager {
no e: Employee | e = e.manager
}
assert EveryoneHasATop {
all e: Employee | some top: Employee | top in e.*manager and no top.manager
}
check EveryoneHasATop for 3
Run it:
elinvar check hierarchy.als
Output (exit code 1):
check EveryoneHasATop: COUNTEREXAMPLE with Employee: 2
Employee = {Employee0, Employee1}
manager = {Employee0 -> Employee1, Employee1 -> Employee0}
witness e = Employee1
searched every case up to Employee: 3.
Elinvar found the bug right away and shrank it to the smallest possible case: two employees managing each other in a cycle. Neither is their own manager, yet neither reaches the top.
You can also pipe a model straight from stdin without saving a file:
elinvar check - <<'EOF'
sig Employee { manager: lone Employee }
fact NoSelfManager { no e: Employee | e = e.manager }
assert EveryoneHasATop {
all e: Employee | some top: Employee | top in e.*manager and no top.manager
}
check EveryoneHasATop for 3
EOF
3. Visualize the counterexample
Pipe the JSON output into elinvar render to get a Mermaid diagram (or Graphviz --dot):
elinvar check hierarchy.als --json | elinvar render - --mermaid
flowchart LR
n_Employee0["Employee0 (Employee)"]
n_Employee1["Employee1 (Employee, $e)"]
n_Employee0 -->|"manager"| n_Employee1
n_Employee1 -->|"manager"| n_Employee0
4. Fix the design and verify
Replace NoSelfManager with a rule that forbids all cycles (e in e.^manager), and ask
Elinvar to explain which rules did the work using --explain:
sig Employee {
manager: lone Employee
}
fact Acyclic {
no e: Employee | e in e.^manager
}
fact Redundant {
no e: Employee | e = e.manager
}
assert EveryoneHasATop {
all e: Employee | some top: Employee | top in e.*manager and no top.manager
}
check EveryoneHasATop for 4
elinvar check hierarchy.als --explain
Output (exit code 0):
check EveryoneHasATop: holds
searched every case up to Employee: 4; a larger case might still break it.
used rules: field manager, fact Acyclic
unused rules: fact Redundant
Not only does the promise now hold up to 4 employees, --explain also spots that
Redundant was unnecessary once Acyclic was in place.
5. Understand the four verdicts
Every elinvar check ends with one of four verdicts:
| Verdict | Exit code | What it means |
|---|---|---|
holds | 0 | No counterexample exists up to the scope searched. Strong evidence, not an unbounded proof: raise --scope if you want to search larger cases. |
counterexample | 1 | A real case breaks your promise. Every counterexample is double-checked by an independent evaluator and shrunk to the fewest steps, atoms, and links. |
vacuous | 2 | Your rules contradict each other and allow no valid case at all. Nothing can break the promise only because nothing is allowed. Run with --explain to see which rules conflict. |
unknown | 2 | The solver ran out of its conflict budget before finishing. Raise --budget or reduce --scope. |
A fifth exit code, 3, means the model or command has an error (syntax, unknown name,
type/arity mismatch). Every error includes a code, file and line, and a suggested fix;
run elinvar explain CODE for details.
Next steps
- See five everyday scenarios in Practical examples: permissions, state machines, SQL schemas, comparing design revisions, and catching contradictory rules.
- Browse every command and flag in the Command-line reference.
- Run design checks inside
cargo testwith Checking designs in Rust. - Wire Elinvar into Claude Code, Cursor, or Codex with Using Elinvar with coding agents.
Practical examples
Elinvar shines whenever several simple rules interact and you want to know whether an edge case slips through the cracks. Below are five everyday problems and how to check them.
1. Permissions and access control
The problem: A document system has groups, users, and documents. Groups grant access to documents, and users belong to groups. A developer writes the check: “every document a user can access must be granted by some group.” Does that guarantee users only access documents granted by their own groups?
Model (corpus/holes/access.als):
sig Group { grants: set Doc }
sig User { member: set Group, access: set Doc }
sig Doc {}
fact EveryAccessIsGranted {
all u: User, d: Doc | d in u.access implies some g: Group | d in g.grants
}
assert UsersOnlyReachOwnGroups {
all u: User, d: Doc | d in u.access implies some g: u.member | d in g.grants
}
check UsersOnlyReachOwnGroups for 3
Run it:
elinvar check corpus/holes/access.als
Output:
check check$1: COUNTEREXAMPLE with Group: 1, User: 1, Doc: 1
Group = {Group0}
User = {User0}
Doc = {Doc0}
grants = {Group0 -> Doc0}
member = {}
access = {User0 -> Doc0}
searched every case up to Group: 3, User: 3, Doc: 3.
What Elinvar caught: User0 belongs to no groups (member = {}), yet can access
Doc0 because Group0 happens to grant it. Tightening the rule to some g: u.member
fixes the hole and the second check in corpus/holes/access.als reports holds.
2. Workflows and state machines over time
The problem: A sharing app has three actions:
share: a reader shares an item with someone who follows the owner.unfollow: a user stops following someone.note: someone an item was shared with leaves a note on it.
The promise: Nobody can leave a note on an item they can no longer open (opening requires being the owner, or having it shared and still following the owner).
Mark changing links with var, describe each action (including what stays the same), and
check over up to 6 steps (corpus/holes/sharing.als):
elinvar check corpus/holes/sharing.als NotesNeedAccess
Output:
check NotesNeedAccess: COUNTEREXAMPLE in 4 states, with Person: 2, Item: 1
start
Person = {Person0, Person1}
Item = {Item0}
owner = {Item0 -> Person1}
follows = {Person0 -> Person1}
step 1 shared gains {Item0 -> Person0}
step 2 follows loses {Person0 -> Person1}
step 3 notes gains {Item0 -> Person0}
step 4 nothing changes, back to state 3
broken at state 2, as step 3 begins
searched every case up to Person: 3, Item: 3, steps: 6.
What Elinvar caught: Share the item, unfollow the owner, then leave a note. Action 3
checked shared but forgot to re-check follows.
Inspecting a counterexample without solving again
Save the JSON result and ask questions about any state with elinvar eval:
elinvar check corpus/holes/sharing.als NotesNeedAccess --json > result.json
elinvar eval corpus/holes/sharing.als result.json 'Item.canOpen' --state 2
# {Person1}
elinvar eval corpus/holes/sharing.als result.json 'some notes' --state 3
# true
And render state 2 as a Mermaid diagram:
elinvar render result.json --mermaid --state 2
3. Checking a SQL database schema
The problem: Your PostgreSQL or SQLite schema has tables, foreign keys, NOT NULL,
UNIQUE, and CHECK constraints. You want to turn it straight into a checkable model
without rewriting it by hand.
Save schema.sql (or pipe via -):
CREATE TABLE users (
id INTEGER PRIMARY KEY,
email TEXT NOT NULL UNIQUE
);
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id),
status TEXT NOT NULL CHECK (status IN ('open', 'closed'))
);
Import it:
elinvar import schema.sql > schema.als
Elinvar generates a ready-to-run Alloy 6 model:
-- Generated by Elinvar from SQL DDL
enum orders_status_enum { orders_status_open_sql, orders_status_closed }
sig users_email_val {}
sig users {
id: one Int,
email: one users_email_val
}
sig orders {
id: one Int,
user_id: one users,
status: one orders_status_enum
} {
status in (orders_status_open_sql + orders_status_closed)
}
fact users_unique_id {
all disj a, b: users | some a.id implies a.id != b.id
}
fact users_unique_email {
all disj a, b: users | some a.email implies a.email != b.email
}
fact orders_unique_id {
all disj a, b: orders | some a.id implies a.id != b.id
}
run Show {} for 3
Now append any business invariant you want to test against your schema (for example,
“can two open orders belong to the same user?” or “does every user have at least one
order?”) and run elinvar check schema.als.
4. Comparing two versions of a design
The problem: You refactored a rule or tightened a policy in v2.als. Did you actually
narrow what is allowed, accidentally allow new bad cases, or keep the two designs
equivalent?
v1.als:
sig Employee { manager: lone Employee }
fact { no e: Employee | e = e.manager }
v2.als:
sig Employee { manager: lone Employee }
fact { no e: Employee | e in e.^manager }
Compare them with elinvar diff:
elinvar diff v1.als v2.als
Output (exit code 1):
diff: tightened
allowed by old, forbidden by new:
check OnlyInOld: COUNTEREXAMPLE with Employee: 2
Employee = {Employee0, Employee1}
manager = {Employee0 -> Employee1, Employee1 -> Employee0}
searched every case up to Employee: 3.
elinvar diff classifies any pair of models sharing signatures and fields as one of:
equivalent(exit0): both allow the exact same cases up to the scope.tightened(exit1): the new model forbids at least one old case (and shows the smallest one) while allowing nothing new.loosened(exit1): the new model allows at least one new case (and shows it).diverged(exit1): each allows cases the other forbids (and shows both).vacuous(exit2,--ofonly): the two models together allow no case, so their functions cannot be compared.
5. Catching contradictory rules (vacuous)
The problem: A scheduler requires that:
- There is at least one task (
some Task). - Every task depends on at least one task (
all t: Task | some t.depends). - Dependencies have no cycles (
no t: Task | t in t.^depends).
Those three rules are impossible to satisfy on any finite set of tasks. A naive checker would find zero counterexamples to any assertion and happily report “passed”.
Run it with --explain:
elinvar check - --explain <<'EOF'
sig Task { depends: set Task }
fact NonEmpty { some Task }
fact EveryTaskDepends { all t: Task | some t.depends }
fact Acyclic { no t: Task | t in t.^depends }
assert OneDep { all t: Task | one t.depends }
check OneDep for 3
EOF
Output (exit code 2):
check OneDep: VACUOUS
the rules allow no case at all up to Task: 3, so nothing can break the promise.
conflicting rules: field depends, fact NonEmpty, fact EveryTaskDepends, fact Acyclic
Elinvar refuses to report holds, exits with status 2, and points straight at the
minimal set of conflicting rules.
Modeling dated history tables (util/history)
Many designs keep an append-only table of dated rows (policy changes, prices,
memberships, effective dates) and look up “the value in force at time t”.
Elinvar ships a small built-in module util/history[Tick] for this pattern.
Opening util/history
open util/history[Tick]
sig Tick {}
enum Policy { Open, Closed }
sig Entry { at: one Tick, policy: one Policy }
sig Read { when: one Tick, saw: one Policy }
Opening util/history[Tick] automatically opens util/ordering[Tick] on the
same clock signature Tick, so first, next, lt, lte, gt, and gte
are available immediately.
Helpers provided
| Name | Meaning |
|---|---|
at_or_before[t1, t2] | t1 <= t2 in the clock order |
before_tick[t1, t2] | t1 < t2 in the clock order |
rows_at_or_before[rows, at, t] | every row in rows whose at is <= t |
latest[rows, at, t] | the row(s) in rows with the greatest at <= t (inclusive) |
latest_strict[rows, at, t] | the row(s) in rows with the greatest at < t (exclusive) |
same_tick_conflict[rows, at, t] | whether a row in rows was written at the exact same tick t |
monotonic_append[rows, at, t] | whether every row in rows has at <= t |
The same-tick pitfall
When a read and a policy change happen in the same clock tick (for example, the
same Unix second), latest[Entry, at, t] and latest_strict[Entry, at, t]
disagree:
latest(<= t) includes the change written at tickt, so a read in the same second sees the new policy.latest_strict(< t) ignores changes at tickt, so a read in the same second sees the previous policy.- If two entries share the same tick
t,latestreturns both rows unless a uniqueness rule forbids two entries for the same key at the same tick.
Checking a promise like:
assert SameTickAgrees {
all r: Read | latest[Entry, at, r.when].policy = latest_strict[Entry, at, r.when].policy
}
check SameTickAgrees for 3
immediately produces a minimal counterexample where an Entry and a Read
occur at the same Tick, forcing an explicit decision in the specification
before code is written.
Command-line reference
Every Elinvar command is a verb (elinvar <verb> ...). Pass --json to any verb for
machine-readable JSON output, or --help for full flag details.
Verbs at a glance
| Command | What it does |
|---|---|
elinvar check FILE [NAME] | Check every assertion in FILE, or only the named command |
elinvar run FILE [NAME] | Find a valid example instance for a run command |
elinvar tests FILE | Generate step reachability and per-guard refusal tests |
elinvar accepts FILE TRACE | Check whether a model allows a trace JSON or SQL DML script |
elinvar fuzz FILE --against CMD | Run dependency-ordered seeded SQL scripts on both a real database and the model (--require-coverage) |
elinvar discover FILE | Discover and prove common invariants of a SQL schema by induction |
elinvar audit FILE --data DUMP | Check table rules and single-state promises directly on a SQL dump (no solver) |
elinvar ci [MANIFEST] | Run a repository manifest under one timeout (Markdown, JUnit, SARIF, JSON) |
elinvar diff OLD NEW | Compare two models or schemas (also diff BASE --migration MIG.sql, --of FUN, --ignore-unread) |
elinvar import FILE|DIR | Convert SQL DDL (or a migrations/ directory) into an Alloy 6 model |
elinvar render RESULT | Render a JSON result’s instance or trace as Graphviz dot, Mermaid, or SQL |
elinvar eval FILE RESULT EXPR | Evaluate an expression or formula on a saved result without re-solving |
elinvar explain [SUBJECT] | Explain an error code, print a JSON Schema (schema[:NAME]), print skill, or list all codes |
elinvar serve --mcp | Run the Model Context Protocol (MCP) server over stdio |
elinvar --version | Print the binary version (also -V) |
Reading from stdin (-)
Pass - for any single input file argument to pipe input without creating temporary files:
# Check a model inline
cat model.als | elinvar check - --json
# Check and immediately render as Mermaid
elinvar check model.als --json | elinvar render - --mermaid
# Import SQL DDL from stdin
pg_dump --schema-only mydb | elinvar import - > schema.als
Two-file commands (diff, eval) accept - for one of the two inputs, not both.
Common flags
| Flag | Applies to | Meaning |
|---|---|---|
--json | all verbs and --version | Output structured JSON (including CLI usage and file errors) |
--explain | check, run | Extract minimal unsatisfiable core of rules on holds or vacuous, or on a run with no instance |
--scope N | check, run, diff | Override the default atom limit per top-level signature |
--steps N | check, run, diff | Override the maximum trace length in states |
--from-any / --from-empty | check, run, diff, import | For .sql schemas, start from any allowed state (diff and import default) or empty tables (check and run default) |
--budget N | check, run, diff | Maximum solver conflicts per solve (default 10000000) |
--no-slicing | check, diff | Solve every check whole instead of slicing away what the assertion cannot see first: slower, and the reference answer |
--symmetry N / --no-symmetry | check, run, diff | Symmetry-breaking predicate length (default 20, matching Alloy; 0 or --no-symmetry disables symmetry breaking) |
--no-overflow | check, run, diff | Forbid signed integer overflow (noOverflow in Alloy); any case whose integer arithmetic wraps is ruled out |
--dot / --mermaid / --format FMT | render | Output format: dot (default), mermaid, or sql |
--state K | eval, render | Pick one state K (0-indexed) of a trace |
--timeout DUR | check, run, diff, tests, fuzz, discover, ci | Wall-clock limit (500ms, 30s, 2m): per solve for check, run, diff, per test for tests, for the whole run for fuzz, discover, and ci. Running out turns an answer into unknown, never into another answer; shrinking has its own conflict budget and no time limit |
--with FILE | check, run, tests, diff, accepts, import, fuzz, discover, audit, eval | Append a sidecar: .als promises, predicates, and commands, or .sql views and queries (repeatable) |
--tables A,B | check, run, tests, diff, accepts, import, fuzz, discover, audit, eval | For a .sql schema, only these tables and the tables their foreign keys point to |
--with-referencing | as --tables | With --tables, also the tables whose foreign keys point into the slice |
--brief | check, run | Leave empty relations and ordering helpers out of the text |
Flags of one verb
| Flag | Verb | Effect |
|---|---|---|
--summary | check | One Markdown table across all checks; with --json, the summary shape of schema:results |
--climb | check | Raise the scope step by step under the budget until a counterexample is found or the budget runs out |
--induction [K] | check | Prove always P for any number of steps by k-induction (default K 1); proved when it succeeds |
--shrink | run | Shrink the instance found to the fewest atoms and tuples |
--all | run | Enumerate every instance up to the scope, one of each group that differ only by renaming atoms |
--limit N | run | With --all, stop after N instances (default 1000) |
--sql | tests, run, render | Render as executable SQL: test cases as replay scripts, run --all instances as inserts, a result as statements (--format sql) |
--values SPEC | tests, render | Sample values for SQL columns: table.col=v1,v2, or @file with one such line each (repeatable) |
--allow-dead S1,S2 | tests | Steps expected never to happen, so they are not reported as dead; also read from -- expect-dead: comments |
--strict | import | Exit 3 if any SQL rule was not read |
--only-ruled | import | Leave out columns that no key, index, constraint, or trigger mentions |
--migration FILE | diff | Compare BASE with BASE plus the migration FILE |
--data FILE | audit | The SQL dump to audit, as INSERT statements (required; - for stdin) |
--show-rejected | discover | Also list the candidates that were refuted, with their counterexamples |
--against CMD | fuzz | The database command to compare with (default sqlite3; for example psql mydb) |
--seed N | fuzz | The seed of the random scripts (default 1); the same seed gives the same scripts |
--scripts N | fuzz | How many random scripts (default 100) |
--length N | fuzz | Statements per script (default 8) |
--junit / --sarif | ci | Write JUnit XML or SARIF 2.1.0 instead of the Markdown table |
--mcp | serve | Serve the verbs as MCP tools over stdio |
Exit codes
| Exit code | Meaning |
|---|---|
0 | Every promise holds (check), instance found (run), models are equivalent (diff), or utility command succeeded |
1 | Counterexample found (check), no instance (run), or models differ (diff: tightened, loosened, diverged) |
2 | Verdict is vacuous (contradictory rules, also diff --of) or unknown (solver budget reached) |
3 | Model error (syntax, unknown name, arity mismatch), bad flag (cli.usage), or unreadable input (cli.input); with --json, a refusal before the verb starts has code, error, and help (schema:usage) |
Names in imported SQL models
A table or column whose name is an Alloy keyword (fact, set, sig, …) or one of
the names the generated model binds itself (a, b, d, r, w, x, and q, v,
or p followed by digits) is renamed with _sql in the model: a column x is the
field x_sql, and a table r the signature r_sql. Promises written in Alloy use the renamed name; SQL scripts given to
accepts, fuzz, and audit keep the SQL name, and SQL rendered by render --sql and
tests --sql uses it too.
Row identity in SQL temporal models
When importing a SQL schema with --temporal, each table T has a pool T_row, a
changing active set T, and a retired set T_retired. Deleting a row moves its atom
into T_retired, and insert_T never reuses a retired atom (just as an autoincrement
rowid is not given out again). Promises quantified over T_row (such as “a closed row
never reopens”) therefore distinguish a deleted row from a later inserted row. If a
promise is instead about a logical entity identified by a business key column (for
example, id or email), quantify over that key column across rows rather than over
the row atom alone.
Self-discovery commands
You never need to look up error codes or JSON formats in the source code:
elinvar explain # list every error code
elinvar explain arity.mismatch # when a code triggers and how to fix it
elinvar explain schema # list every verb's JSON Schema
elinvar explain schema:result # print the JSON Schema (v1) for one check/run result
elinvar explain schema:results # every shape check/run print: one, several, --summary, run --all
elinvar explain schema:diff # also: schema:import, schema:render, schema:eval, schema:tests, schema:accepts, schema:fuzz, schema:discover, schema:ci, schema:audit, schema:usage
elinvar explain skill # print the embedded agent skill guide
Checking designs in Rust (cargo test)
You can write a design model directly in Rust right next to your production code and check
it in cargo test. When a promise breaks, the test fails and prints the shrunk story as
its panic message.
1. Add elinvar as a dev-dependency
[dev-dependencies]
elinvar = "0.1"
elinvar brings the engine, the Alloy reader (elinvar::als), and the command line’s
two small dependencies, rayon and serde_json, with zero unsafe code and no C/Java
build tools.
2. Check a static design
Import elinvar::prelude::*, declare sets and fields on a Model, add rules with
m.fact(...) (or m.fact_named(...)), and assert your promise with assert_holds():
use elinvar::prelude::*;
#[test]
fn managers_always_reach_the_top() {
let mut m = Model::new();
let employee = m.set("Employee");
let manager = m.field_with("manager", &employee, Multiplicity::Lone, &employee);
// Rule: no cycles in the reporting chain.
m.fact_named(
"Acyclic",
all([&employee], |[e]| e.is_in(&e.join(&manager.closure())).not()),
);
// Promise: everyone reaches someone with no manager.
let promise = all([&employee], |[e]| {
some([&employee], |[top]| {
top.is_in(&e.join(&manager.reflexive_closure()))
.and(&top.join(&manager).no())
})
});
m.check(&promise)
.named("EveryoneHasATop")
.scope(4)
.assert_holds();
}
If you remove Acyclic and only forbid self-management, cargo test fails immediately and
prints the two-employee cycle.
3. Check a state machine over time with action
In Alloy text, every step predicate must explicitly repeat every relation that stays
unchanged. In Rust, m.action(...) handles frame conditions automatically: anything you
do not touch in an action stays the same.
Here is the sharing app from crates/elinvar/tests/readme.rs:
use elinvar::prelude::*;
fn notes_need_access() -> (Model, Formula) {
let mut m = Model::new();
let person = m.set("Person");
let item = m.set("Item");
let owner = m.field_with("owner", &item, Multiplicity::One, &person);
let follows = m.changing_field("follows", &person, &person);
let shared = m.changing_field("shared", &item, &person);
let notes = m.changing_field("notes", &item, &person);
let can_open = owner.union(&shared.intersection(&owner.join(&follows.transpose())));
m.fact(shared.no().and(¬es.no()));
m.action("share", [&item, &person], |step, [i, p]| {
step.when(i.join(&owner).is_in(&p.join(&follows)));
step.add(&shared, i.product(&p));
});
m.action("unfollow", [&person, &person], |step, [p, q]| {
step.when(q.is_in(&p.join(&follows)));
step.remove(&follows, p.product(&q));
});
let note = m.action("note", [&item, &person], |step, [i, p]| {
step.when(p.is_in(&i.join(&shared))); // forgot to check follows
step.add(¬es, i.product(&p));
});
let promise = always(all([&item, &person], |[i, p]| {
note.happens(&[&i, &p])
.implies(&p.is_in(&i.join(&can_open)))
}));
(m, promise)
}
Running m.check(&promise).named("NotesNeedAccess").scope(3).steps(6).assert_holds()
fails in cargo test with the shrunk 3-step story:
check NotesNeedAccess: COUNTEREXAMPLE in 4 states, with Person: 2, Item: 1
start
owner = {Item0 -> Person1}
follows = {Person0 -> Person1}
step 1 share(Item0, Person0) shared gains {Item0 -> Person0}
step 2 unfollow(Person0, Person1) follows loses {Person0 -> Person1}
step 3 note(Item0, Person0) notes gains {Item0 -> Person0}
broken at state 2, as step 3 begins
4. Working with reports, cores, diffs, and diagrams
Instead of panicking via assert_holds(), call .report() or .report_explained() to
inspect structured data:
let report = m.check(&promise).scope(4).report();gives a serializableReportwithverdict,instance,trace,shrunk_to,errors,stats, andstory.let report = m.check(&promise).scope(4).report_explained();also populatesreport.core(usedandunusedrule names) when the verdict isHoldsorVacuous.elinvar::diff_models(&old, &new, 3, &Options::default())compares twoModels and returns aDiffReport(Equivalent,Tightened,Loosened,Diverged).elinvar::render_report(&report, DiagramFormat::Mermaid)(orDiagramFormat::Dot) renders any counterexample or found instance as a diagram.m.check(&promise).report_with(MySolver::new)plugs in a customSolverimplementation for solving and shrinking.
Using Elinvar with AI coding agents
Elinvar is designed so coding agents (Claude Code, Codex, Cursor, Windsurf, or custom
agent loops) can verify a design before writing code. Agents can use Elinvar either
through the CLI or through MCP. Both return the same JSON; MCP offers every verb but
fuzz, which runs a database command, and ci, which reads files from disk.
Option A: Connect via MCP (elinvar serve --mcp)
Install the binary once:
cargo install elinvar
(Or from a local checkout: cargo install --path crates/elinvar. A tagged release
also has binary archives on the
releases page.)
Add Elinvar to your MCP client configuration (Claude Code, Claude Desktop, Cursor, etc.):
{
"mcpServers": {
"elinvar": {
"command": "elinvar",
"args": ["serve", "--mcp"]
}
}
}
When an MCP client connects to elinvar serve --mcp, it automatically receives:
-
Server instructions on
initializeexplaining the workflow, verdicts, and frame conditions. -
Embedded MCP resources (
resources/listandresources/read):skill://elinvar/SKILL.md: the full agent guide and supported Alloy 6 subset.elinvar://schema/<name>-v1.json: the thirteen versioned JSON Schemas ofelinvar explain schema:result,results,diff,import,render,eval,tests,accepts,fuzz,discover,ci,audit, andusage.
-
Eleven stateless tools (
tools/listandtools/call):check: check assertions (supportsexplain: truefor minimal unsat cores).run: find an example instance of a predicate.diff: compareold_modelandnew_model, or a function between them (of).import_sql: turn SQL DDL into a starter Alloy 6 model.render: render a result’s instance or trace asdot,mermaid, orsql.eval: evaluate an expression on a result at any state without re-solving.tests: generate step reachability and refusal tests.accepts: check whether a trace or SQL DML script is allowed.discover: find and prove invariants of a SQL schema.audit: check a SQL dump’s rows against a schema without the solver.explain: explain an error code,schema/schema:<name>, orskill.
check,run,eval, andacceptstake SQL DDL asmodelwithis_sql: true, and the command line’s--withsidecars aspromises(Alloy) andviews(SQL). An argument a tool does not list is refused with the list of those it takes.
Option B: Use the CLI directly (shell-capable agents)
If your agent already has shell access, it does not even need MCP configured. As long as
elinvar is on PATH:
- The agent can teach itself in one command from the embedded guide:
(Or copy skills/elinvar/SKILL.md into your project’s agent skills folder.)elinvar explain skill - The agent checks designs in one stateless command using stdin (
-) and--json:elinvar check - --json <<'EOF' sig User { roles: set Role } sig Role {} ... EOF - Every response is structured JSON with stable exit codes (
0holds/found,1counterexample/diff,2vacuous/unknown,3error withcode,place, andfix).
Good prompts to give an agent
You do not need to write Alloy yourself. Ask your coding agent things like:
- “Before implementing the permissions table and revocation endpoint, model the rules in Elinvar and check whether a revoked user can still edit a document.”
- “Import
migrations/001_init.sqlwithelinvar importand check whether an order can be marked shipped without a valid payment.” - “Compare our old and new state transition rules with
elinvar diffand show me any behavior change.”
What an agent should report back
- On
counterexample: the concrete steps or links that break the promise, and how to change the design to close the hole. - On
holds: always include the scope searched (for example, “holds up to 4 users, 4 documents, and 6 steps”), since bounded checking is strong evidence rather than an unbounded proof. - On
vacuous: stop and fix the contradictory rules (never treatvacuousas a pass). - On
unknown: raise--budgetor simplify the scope.
Finding holes in a design
A design can be wrong before a line of it is written. Each rule looks fine alone, and the hole is in how they meet. This chapter says what Elinvar looks for and what its answers mean. It needs no background.
Things, links, rules, and a promise
A design, as Elinvar sees it, has four parts.
- Things: people, items, groups, accounts. Sets of them.
- Links between things: who follows whom, who owns what. Relations.
- Rules: what must be true, and what a step is allowed to change.
- A promise: something that must hold whatever happens.
Take a sharing app with three rules.
- A reader shares an item with a follower.
- The reader can end the follow.
- Someone an item is shared with can leave a note on it.
The promise: nobody leaves a note on an item they can no longer open.
A hole
Share an item. End the follow. Leave a note.
Rule 3 forgot to ask whether the follow is still on. No rule is wrong by itself, and reading them one at a time will not find it. A list of steps that breaks a promise is a counterexample, and it is what Elinvar returns:
check NotesNeedAccess: FAILS in 3 steps, with 2 people and 1 item
start Person0 follows Person1. Item0 is owned by Person1.
step 1 share(Item0, Person0) shared gains Item0 -> Person0
step 2 unfollow(Person0, Person1) follows loses Person0 -> Person1
step 3 note(Item0, Person0) notes gains Item0 -> Person0
broken at step 3: Person0 notes Item0, but Item0.canOpen is {Person1}.
The sharing model runs in corpus/holes/sharing.als and crates/elinvar/tests/readme.rs, producing a shrunk story of the same shape (DESIGN.md section 9.6).
Why small cases are enough to be useful
Elinvar does not reason about every possible size. It tries every case up to a size you choose: every way three people and three items can be linked, every order six steps can happen in. That is a great many cases, and it tries all of them, not a sample.
It works because holes are rarely about size. The one above needs two people, one item, and three steps. A design that survives every case with up to three of everything has had most of its mistakes found.
What the two answers mean
A counterexample is certain. Elinvar checks each one against the rules as you wrote them before it shows it, by a separate and much simpler piece of code (DESIGN.md section 10).
“Holds” is weaker, and says so: no case up to this size breaks the promise. A larger case might. It is evidence, not proof.
There is a third answer worth knowing. If the rules contradict each other, no case satisfies them, so no case breaks the promise, and a careless tool says “holds”. Elinvar says the rules allow nothing (DESIGN.md section 7.6).
How it searches
Every question of the form “is this link present?” becomes a yes-or-no unknown: does Person0 follow Person1 at step 2? The rules and the broken promise become constraints on those unknowns. A solver for such constraints, a SAT solver, either finds values that satisfy all of them, which is a counterexample, or shows there are none (DESIGN.md section 7).
What it does not do
- It does not check code. It checks the design that was described.
- It does not prove a promise for every size or for unbounded traces (REQUIREMENTS.md section 6).
Alloy, and what Elinvar takes from it
Alloy is a language and a tool for describing designs and searching them for holes, by Daniel Jackson and the Alloy team at MIT. Its engine, Kodkod, is by Emina Torlak. The time extension of Alloy 6 comes from the Electrum project and its engine, Pardinus. Elinvar is inspired by all three and affiliated with none.
The parts of Alloy
| Part | What it does | In Elinvar |
|---|---|---|
| the language | signatures, fields, facts, predicates, assertions, run and check | a documented subset is the text form of a model (DESIGN.md section 9.4) |
| Kodkod | relational logic with bounds, turned into a boolean circuit, then clauses for a SAT solver | the core, rebuilt in Rust after its design (DESIGN.md sections 6 and 7) |
| symmetry breaking | skips cases that differ only by renaming | the same method (DESIGN.md section 7.5) |
| time, from Pardinus | changing relations, always, eventually, traces that loop | bounded lasso traces (DESIGN.md section 8) |
| the visualizer | draws an instance | text stories, plus Graphviz dot and Mermaid (elinvar render) |
| integers, strings, and sequences | bounded, wrapping arithmetic, string literals, and seq | supported with configurable bitwidth (LOGIC.md section 16), String with each command’s literals, and util/sequniv |
| the library modules | util/ordering, util/relation, util/graph, util/boolean, util/ternary, util/natural, util/integer, util/time, util/sequence, util/seqrel, util/sequniv | each read, in Elinvar’s own statement of it with Alloy’s names and parameters (LOGIC.md section 15.1) |
The same, on purpose
The logic is Alloy’s: sets and relations, join, closure, quantifiers, and bounds on what each relation may hold (LOGIC.md). It is kept the same so that answers can be compared. A corpus of Alloy’s own example models is checked both ways: the verdict must match Alloy’s, and where the cases can be counted, so must the count (CORPUS.md).
Alloy is never needed to build or test Elinvar. Its answers are recorded once and kept in the repository.
Different, on purpose
- No Java. One binary, built by
cargoalone. - Built for agents first: results as data, error codes with fixes, a budget on every search (DESIGN.md section 9.1).
- The smallest counterexample, not the first one found.
- A model can be written in Rust, beside the code, and checked in
cargo test. - A helper that says what a step leaves unchanged, the thing most often forgotten.
- “Holds” is told apart from “the rules allow nothing”.
A fact that matters when comparing
Alloy puts 16 integer atoms in the universe of every command, whether the
model uses integers or not. univ, iden, and * range over them. A
comparison with Alloy on a model that mentions those has to account for it
(LOGIC.md section 10).
Architecture overview
One engine, several front doors: cargo test, the command line, and an MCP
server are clients of the same calls and the same result types
(DESIGN.md section 5). All of it exists.
cargo test (Rust model) elinvar check model.als --json agents over MCP
| | |
+------------ the same calls and result types --------------+
|
elinvar: the facade (re-exports) and the command line, over
elinvar-engine: the engine
model builder, scopes to bounds, time unrolled into steps
skolemize -> circuit -> clauses -> solver (behind a trait)
symmetry breaking, next instance, shrinking, stories
|
every instance goes back down to be refereed
|
elinvar-logic: the relational core
atoms, tuples, relations, bounds, expressions, formulas,
instances and traces, the evaluator, brute-force enumeration
The crates
| Crate | Role | Phase |
|---|---|---|
elinvar-logic | the logic and its evaluator | 1 |
elinvar-engine | the engine | 2 |
elinvar-als | reads Alloy text into a model | 5 |
elinvar | the one crate a user depends on or installs: re-exports the engine and the Alloy reader, and builds the elinvar binary | 5 |
xtask | the cargo x verbs | 0 |
The referee
The split between the two libraries is the trust boundary. A checker with
a bug says “no holes” when there are some, so every instance the engine
finds is evaluated again by elinvar-logic, directly from the definitions,
before it is returned. elinvar-logic cannot depend on the engine, so the
referee cannot call what it referees
(DESIGN.md section 10, AGENTS.md laws 12 and 13).
The pipeline
A formula and its bounds go through five steps (DESIGN.md section 7):
- A top-level
somebecomes a fresh relation, so its witness has a name. - Each relation becomes a table of boolean values, one per tuple it may hold, and each operator a computation on tables. The formula becomes one boolean circuit with shared parts.
- A predicate that breaks symmetries is added, so renamed copies of a case are skipped.
- The circuit becomes clauses, and a SAT solver gets them with a budget.
- A solution is read back as an instance, refereed, and shrunk.
Every step is a function of its input, so the same model gives the same answer on every machine (DESIGN.md section 7.8).
Working on it
Every operation is a cargo x verb, and cargo x verify is what CI runs
(AGENTS.md law 31). cargo x fetch checks out the pinned Alloy, Kodkod,
and Pardinus sources for reading.
cargo x docs serves this book, rebuilt on change, and cargo x docs --build
builds it into target/book/. Both need cargo install mdbook.
Elinvar: design
Status: current, 2026-11-29. Phases 1 to 5 and bounded integers are built.
Companions: REQUIREMENTS.md (what Elinvar must do; R numbers refer to it),
LOGIC.md (the relational logic and its meaning),
CORPUS.md (the models checked against Alloy),
AGENTS.md (the laws)
Upstream reference: Alloy 6.2.0 (59ba203), Kodkod (6e80244), Pardinus 1.2.4 (d3e7aea)
Elinvar is an alloy whose springiness stays the same as it warms and cools. This tool checks what must stay the same in a design: its invariants. Its first end-to-end test is the hole in the README’s sharing app: share an item, end the follow, leave a note. Three steps, found from three rules and one promise.
Contents: 1 Vision · 2 Landscape · 3 Principles · 4 Users · 5 Architecture · 6 The relational core · 7 Finding · 8 Time · 9 Front doors · 10 Verification · 11 Roadmap · 12 Risks · 13 Decisions and open questions · 14 Naming and licensing
1. Vision
Elinvar answers one question about a design: can this promise break, and if so, how? It searches every case up to a chosen size and either finds none that breaks the promise, or returns the shortest story of how it breaks.
It is built for agents first (section 13, 2026-11-28). A coding agent that is asked to add sharing to an app writes the rules and the promise, runs one command, and reads back either “holds for every case up to this size” or three steps it can act on. Then it fixes the design and runs the command again. People use the same doors; nothing is possible only for one of them.
Near term, Elinvar rebuilds the core of Alloy and its engine Kodkod in Rust: relational logic with bounds, turned into a satisfiability problem. The core follows theirs closely enough that its answers can be compared with Alloy’s on the same models (CORPUS.md), and that comparison is a large part of why its answers can be trusted.
Past the core it goes where Alloy does not: one binary with no Java, results
as data, the smallest counterexample instead of the first, checks that run in
cargo test, a helper for what a step leaves unchanged, and later a model
read from a database schema (REQUIREMENTS.md section 8).
What it does not do: prove a promise for every size, or check code. It checks the design that was described, up to the size that was set, and every answer says so.
2. Landscape
Rows about Alloy are checked against the pinned source. The other rows are from memory, unchecked (AGENTS.md law 5), as of 2026-11-28.
| Project | Stack | Strength | Gap Elinvar targets |
|---|---|---|---|
| Alloy 6, with Kodkod and Pardinus | Java | the language, the logic, twenty years of models and teaching; a visualizer; a command line and a language server in the repository (org.alloytools.alloy.cli, org.alloytools.alloy.lsp) | needs a Java runtime; shows the first counterexample found, not the smallest; models live apart from the code; output is made for a person at a window |
| TLA+ with TLC, and Apalache | Java, Scala | state machines and refinement, used in industry | a different logic, built around actions and not around relations; Java |
| Quint | TypeScript, over TLA+ tools | syntax programmers find familiar | the engines behind it are the ones above |
| Forge | Racket | teaching, with a relational logic close to Alloy’s | not built to be embedded or driven by an agent |
| stateright | Rust | explicit-state checking of actor systems written in Rust | checks an executable model by running it, not a relational description by solving |
| Kani, Prusti, Creusot | Rust | verify Rust code | check code, not designs |
Two conclusions.
First, the relational logic of Alloy is the right core, and nobody needs a new one. What is missing is a form of it that an agent can call the way it calls a compiler: one binary, text in, data out, the same answer every time.
Second, agents already read and write Alloy. Its syntax is in their training data. So the text form of a model should be Alloy’s own (section 9.4), not a new language they would have to be taught in a prompt.
3. Principles
- Agents are the first users. Every input has a schema or a grammar, every output is data with a version, nothing fails silently, nothing hangs, and nothing an agent sends can execute code.
- Trust before reach. A checker that is wrong says “no holes” when there are some. The evaluator referees every instance (R15), brute force checks tiny cases (R18), the corpus checks agreement with Alloy (R16), and planted holes check that known holes are found (R17). A feature that cannot be tested this way waits.
- One engine, many doors. The engine is a library.
cargo test, the command line, and the MCP server are clients of the same calls and the same result types. - An answer says what it covers. “Holds” means “holds for every case up to
this size”, and the size is in the result. Out of budget is
unknown. A check whose rules allow nothing says that, not “holds”. - Inspired, not ported. The core follows Alloy and Kodkod so answers can be compared. Everything else is designed fresh, in Rust, from the documents.
- Small counterexamples. A hole is shown with the fewest steps and the fewest things that still show it, as a story of what happened.
- Same input, same output. The same model and scope give the same verdict and the same instance on every run and machine (R14).
- Own the public surface. Public signatures contain Elinvar and
stdtypes only. The solver, and any other pre-1.0 dependency, sits behind an internal module. - Rule of two. An extension point gets a public trait when it has two real implementations. The solver trait is the exception R9 asks for.
- Simple things simple. A check is one call. Building a model never fails halfway: errors are collected and reported together, each with its place.
- Rust only, and
cargoalone builds it. No Java, Python, or C toolchain (R28). - Speed is not a first goal (R29). It is measured, so a slowdown is seen, and it never buys back any of the above.
4. Users
| User | Front door | What they need |
|---|---|---|
| Coding agent designing a data model, a permission system, or a protocol | elinvar check with --json; the MCP server | Alloy syntax it already knows, one call per check, a verdict as data, a short story to act on, codes with fixes, a budget |
| Coding agent in a Rust project | the elinvar crate in cargo test | a model beside the code, a failure message that is the counterexample |
| Developer | the same two doors | the same, read by eye |
| Research or review agent | results as JSON, elinvar eval | to ask what a relation holds in a state, compare runs, keep records |
| Tool builder | elinvar-logic, the result schemas | stable types and formats that do not churn |
5. Architecture
5.1 Layers
cargo test (Rust model) elinvar check model.als --json agents over MCP
| | |
+------------ the same calls and result types --------------+
|
elinvar: the engine -------------------+------------------------------------
model builder, scopes to bounds, time unrolled into steps
skolemize -> circuit -> clauses -> solver (behind a trait)
symmetry breaking, next instance, shrinking, stories
|
every instance goes back down to be refereed (R15)
|
elinvar-logic: the relational core -----------------------------------------
atoms, tuples, relations, bounds, expressions, formulas,
instances and traces, the evaluator, brute-force enumeration
5.2 Crates
Decided 2026-11-28 (section 13); this answers open decision 6 of REQUIREMENTS.md.
| Crate | Role | From phase |
|---|---|---|
elinvar-logic | the relational core: universe, relations, bounds, the syntax tree, instances, traces, the evaluator, and brute-force enumeration | 1 |
elinvar-engine | the engine: the model builder, translation, the solver trait and the default solver, symmetry breaking, run and check, time, shrinking, stories. It re-exports elinvar-logic as logic and its common items in prelude | 2 |
elinvar-als | reads Alloy text into a model: parser, name resolution, the type and arity check, scopes | 5 |
elinvar | the facade and the elinvar binary: re-exports elinvar-engine and elinvar-als (as elinvar::als), and holds check, run, eval, explain, serve --mcp, and the other verbs in its cli module. The one crate a user depends on or installs | 5 |
elinvar-macros | a macro or derive for models, only if the builder turns out noisy (R23) | 4, if needed |
xtask | the cargo x verbs; never published | 0 |
Why two library crates and not one: the split is the trust boundary. The
referee must not be able to call what it referees (AGENTS.md law 12), and a
crate boundary is the one module boundary the compiler enforces. Nothing
else is split until something needs it: translation, solving, and time are
private modules of elinvar-engine. The facade is a crate of its own so that
the crate a user names, elinvar, is both the library and the binary
(section 13, 2026-12-03).
Public paths and source layout:
- A crate’s public API is the
pub uselist in itslib.rs. Source directories are private modules, so moving code between them never changes a public path. elinvarre-exportselinvar-engine, and through itelinvar-logicaselinvar::logicand the common building types inelinvar::prelude, andelinvar-alsaselinvar::als, so a user needs one crate.- White-box tests stay inline in their module. Spec tests that drive a crate
live in
tests/, and corpus models incorpus/at the workspace root (CORPUS.md section 3).
5.3 Dependencies
elinvar-logicdepends onserdeand on no other Elinvar crate.elinvar-enginedepends onelinvar-logicandserde. Its bit-sliced SIMD brute-force counter (bitslice.rs) usesmacerator(pinned exactly, pre-1.0) behind the optionalbitslicefeature, enabled for workspace tests and off by default for downstream dependents;elinvarpasses on a feature of the same name. The default solver (Cdcl) is written insideelinvar-enginewith no external solver dependency.elinvar-alsdepends onelinvar-engine.elinvardepends on both, and onrayonandserde_jsonfor its command line.- The libraries do no I/O. Only the
climodule ofelinvarand its binary read files and stdin, and nothing touches the network. - No crate in the workspace needs a C toolchain.
cargo denybanscc,cmake,bindgen, andpkg-config(AGENTS.md law 6).
6. The relational core
Phase 1, R1 to R7. LOGIC.md is the specification: every operator’s arity rule and meaning, the error codes, and hand-worked examples that are tests. This section gives the shape and the reasons.
6.1 Atoms and tuples
A universe is a finite, ordered list of named atoms (R1). An atom is its
position in that list. A tuple of arity k is k atoms, and it has an index:
its atoms read as the digits of a number in base n, the size of the
universe. A set of tuples is a sorted set of indices. This is Kodkod’s
scheme (kodkod/instance/TupleFactory.java, IntTuple, and
kodkod/instance/TupleSet.java); the reason to share it is that tuple order
then fixes variable order (section 7.8).
6.2 Relations, bounds and instances
A relation has a name and an arity of one or more; a set is a relation of arity one (R2). Bounds give each relation a lower bound, the tuples it must hold, and an upper bound, the tuples it may hold (R3). An instance gives each relation a set of tuples between its bounds.
Atoms never appear in a formula. A formula that needs “this atom” names a relation whose bounds fix it to that atom. Symmetry detection depends on this: the bounds are then the only place two atoms can be told apart (section 7.5).
Sets with a size limit (R11), subsets, and “exactly one of” are not core
notions. The model builder in elinvar-engine turns them into bounds and formulas.
6.3 Expressions and formulas
The operators are those of R4 and R5 (LOGIC.md sections 3 and 4). Two
differ from Kodkod’s list, on purpose: domain and range restriction are core
operators, and the quantifiers no, one, and lone are core, where Alloy
rewrites them before Kodkod sees them (LOGIC.md section 10). They are
core so the evaluator computes what the user wrote, not a rewriting of it.
An expression or a formula is an immutable value, cheap to clone and share
between threads. Building one is a method call with no context argument:
a.join(&b), f.and(&g). The translator finds equal subterms by structure
and translates each once (R8).
6.4 Errors at build time
Rust’s types catch one class of mistake at compile time: an expression is
not a formula, so some cannot be applied to a formula and and cannot
take a set. They cannot catch an arity mismatch in general, because the
arity of a join is a sum of two arities minus two, and stable Rust cannot
compute that in a type. So arity is checked when a node is built (R6).
Building never fails (principle 10). A method that would make an
ill-formed node records the error, with the file and line of the caller
(#[track_caller]), and returns a node that carries it. run and check
refuse a model with errors and return all of them together. For a model
written in Rust the place is the line of Rust that built the node; for a
model read from text it is the line and column of the text.
Whether typed handles for sets and binary relations can catch more at compile time and still read well is a phase 4 question (section 13).
6.5 The evaluator
Given an instance, the evaluator computes any expression to a set of tuples and any formula to true or false, with no solver (R7). It follows the definitions in LOGIC.md one for one: a quantifier is a loop, a closure is repeated until nothing changes. It is the referee for everything else (R15), so it is kept slow and plain on purpose (AGENTS.md law 12).
elinvar-logic also enumerates every instance within given bounds, for tiny
universes (R18). With the evaluator, that gives the count of instances that
satisfy a formula with no solver involved. Phase 1 checks those counts
against known numbers: six total orders on three atoms, fifteen equivalence
relations on four (LOGIC.md section 8).
7. Finding
Phase 2, R8 to R18. Each step below is specified in LOGIC.md section 12;
this section fixes the design. Upstream citations refer to the pinned commits
(cargo x fetch).
formula + bounds
| skolemize: a top-level "some" becomes a fresh relation
v
circuit: one boolean value per (relation, tuple); shared gates
| symmetry-breaking predicate, added as one more conjunct
v
clauses in conjunctive normal form
| solver, behind a trait, with a budget
v
model of the clauses -> instance -> referee -> verdict
7.1 From formula to circuit
Each relation becomes a table with one boolean value per tuple of its upper
bound: true if the tuple is in the lower bound, otherwise a fresh variable.
Each expression becomes such a table, computed from its parts: union is or
entry by entry, join is a boolean matrix product, transitive closure is
repeated squaring. Each formula becomes one boolean value. A quantifier is
grounded: all x: e | F is the conjunction, over the tuples t that e
may hold, of “t is in e implies F with x bound to t”.
Gates are and, or, not, and if-then-else, built through one factory
that simplifies constants and returns the existing gate when asked for one
it has already built. That is where shared subterms come from (R8): a node
of the formula met twice, with the same bindings for its free variables,
gives the same gate.
7.2 Skolemization
A some that is not inside an all is replaced by a fresh relation, bounded
by what its declaration may hold, and the constraint that the relation is in
the declared set. The witness then shows up in the instance by name, which
is how a counterexample says which person and which item. This is also what
makes a some over sets or relations checkable at all (REQUIREMENTS.md
section 6): check negates an assertion, so all r: univ->univ | ...
becomes a some, and that is how the first Alloy exercises are written
(CORPUS.md section 2).
A some inside an all is grounded, not skolemized. That matches Alloy’s
default (skolemDepth = 0 in A4Options.java). A quantifier over sets or
relations that skolemization cannot remove is an error with a code, not a
silent approximation.
“Not inside an all” is not the whole of Kodkod’s rule, and the rest
matters, because a skolem relation is part of an instance and so of every
count (section 7.7). At depth 0 the skolemizer in Alloy’s copy of
Pardinus replaces a some only where the formula around it must hold as a
whole. It stops below iff, below or and implies where they are not
negated, below and where it is negated, and below every temporal operator
(Skolemizer.java, the visit methods for BinaryFormula, NaryFormula,
and the temporal formulas). Under a negation the roles swap: an all is
replaced, and or lets it through. Phase 2 specifies the same rule in
LOGIC.md, position by position, before it is coded. How counts are compared
when Alloy’s rewriting of no, one, and lone puts a quantifier where
Elinvar has none is open (section 13).
7.3 From circuit to clauses
Each gate gets a variable, and clauses relate the variable to the gate using
polarity-aware Plaisted-Greenbaum encoding (LOGIC.md section 12.4):
monotone gates (and, or, maj) emit only the polarity directions their
callers need, while ite and xor emit both polarities where needed.
7.4 The solver
The solver sits behind a trait Elinvar owns (R9):
pub trait Solver {
fn new_var(&mut self) -> Var;
fn add_clause(&mut self, clause: &[Lit]);
/// Solves under assumptions. `Unknown` when the budget runs out.
fn solve(&mut self, assumptions: &[Lit], budget: &Budget) -> Solved;
/// The value of a variable in the model, after `Solved::Sat`.
fn value(&self, var: Var) -> bool;
/// Total conflicts spent by this solver, for statistics (defaults to `0`).
fn conflicts(&self) -> u64 { 0 }
/// After `Solved::Unsat`, a subset of the assumptions that derived UNSAT.
fn unsat_core(&self) -> Vec<Lit> { Vec::new() }
}
Assumptions are in the trait from the start because three things need them:
the next instance (R13), shrinking (R25), and later the explanation of “no
counterexample” from an unsatisfiable core. Callers plug in an external
Solver through Finder::with_solver, run_with_solver,
check_with_solver, count_with_solver, Command::solve_with, and
Command::report_with; every instance or trace returned through a plugged-in
solver is still refereed by elinvar-logic (R15).
The default must be pure Rust (R9, R28), deterministic (R14), and under a
license cargo deny accepts. The candidates of REQUIREMENTS.md open
decision 3, as crates.io shows them on 2026-11-28:
| Crate | Newest release | License | Reading |
|---|---|---|---|
batsat | 0.6.0, 2025-01-20 | MIT | a port of MiniSat to Rust; small; recommended |
splr | 0.19.0, 2026-08-22 | MPL-2.0 | maintained and modern, but its license is outside the allowed list |
varisat | 0.2.2, 2020-09-09 | MIT or Apache-2.0 | no release in six years |
rustsat | 0.7.5, 2026-01-30 | MIT | a common interface and encodings, not a solver; its pure Rust backend, rustsat-batsat, wraps batsat, and its MiniSat and CaDiCaL backends compile C++ |
Decided on 2026-11-28: Elinvar’s own solver (sat::Cdcl), behind the trait,
and not batsat; the table is kept as the record of what was considered.
rustsat is not the public interface, since that would put a pre-1.0
third-party trait in Elinvar’s signatures (principle 8). The
in-tree solver supports assumptions and conflict/time budgets, stays usable
after a budget stop (tested in sat::tests), and uses only deterministic
arithmetic with ties broken by lowest variable index so the same clauses give
the same model across platforms.
A faster solver written in C is plugged in from outside the workspace: a
crate that implements Solver, which may well go through rustsat. The
determinism promise (R14) covers the default solver only.
7.5 Symmetry breaking
Two atoms are interchangeable when no bound tells them apart. Kodkod finds
the coarsest partition of the universe such that every bound is a union of
products of its parts (SymmetryDetector.java), and adds a predicate that,
for each pair of neighbouring atoms in a part, requires the instance to be
no larger than its image under swapping them, comparing at most 20 values
per pair (SymmetryBreaker.java, generateSBP; symmetryBreaking = 20 in
Options.java, and symmetry = 20 in Alloy’s A4Options.java). Elinvar
does the same, on by default, with a switch (R12).
The predicate removes many renamed copies of an instance but not all of them, so a count of instances means something only with symmetry breaking off. That is the setting the corpus counts under (R16).
Kodkod also breaks the symmetries of relations declared to be total orders
or acyclic by fixing their value (SymmetryBreaker.java, breakTotalOrder,
breakAcyclic). For a total order it gives the order, its first, and its
last exact bounds that follow the order of the atoms. That step does not
depend on the symmetry option: in Alloy’s copy of Pardinus, Translator.java calls
breakMatrixSymmetries whatever symmetryBreaking is, and only
generateSBP returns early at 0. Alloy does the same to util/ordering
itself before Kodkod runs (TranslateAlloyToKodkod.java, simplify). So
with symmetry breaking off, Alloy still counts one order, not every order.
Elinvar therefore needs two things at two times. In phase 2 a corpus model
that opens util/ordering is translated by hand, and the translation gives
the order exact bounds in atom order, which is what Alloy solves. Finding a
total order in a model and fixing it without being told is needed when
Elinvar reads util/ordering itself, in phase 5, and not before.
The predicate must not constrain shrinking (section 9.6).
7.6 Verdicts and budgets
run looks for an instance of a formula. check looks for an instance of
the rules together with the negation of an assertion: a counterexample
(R10). Both return a verdict, and a verdict never claims more than it knows
(AGENTS.md law 14):
| Verdict | From | Meaning |
|---|---|---|
found | run | an instance, refereed |
none | run | no instance up to this scope |
counterexample | check | an instance that breaks the promise, refereed and shrunk |
holds | check | no counterexample up to this scope, and the rules allow at least one case |
vacuous | check | no counterexample up to this scope, because the rules allow no case within it |
unknown | both | the budget ran out; says which budget and how far it got |
vacuous costs one more solve, of the rules without the negated assertion,
and only when no counterexample was found. It is there for agents: a model
whose rules contradict each other passes every check, and an agent that sees
“holds” will report that the design is sound. This is new relative to
REQUIREMENTS.md; its section 8 has the larger form, explaining which rules
did the work.
vacuous is scoped like every verdict: with time, it says no trace of the
rules exists within this scope and this many steps. A larger scope may
allow one.
diff gives equivalent, tightened, loosened, diverged, or
unknown, from two checks: each model’s rules against the other’s. A
model’s rules include what its bounds alone say, such as that a one set
has exactly one atom. diff --of compares two functions over the cases
both models allow; when they allow none, its verdict is vacuous, never
equivalent. Two whole models that each allow no case are equivalent,
which is true of them.
If the first solve shows there is no counterexample and the second runs out
of budget, the verdict is unknown, and it says what is known: no
counterexample up to this scope, and whether the rules allow any case not
settled. It is not holds, which would claim the second half (AGENTS.md
law 14).
Every verdict carries the scope it was computed for. A budget is a count of
solver conflicts, which is deterministic, or a time limit, which is not, or
both. A time limit can only turn an answer into unknown (AGENTS.md law 17).
There is always a budget: the default is generous and finite (AGENTS.md
law 22). Both apply to each solve. A command makes several, the check, the
solve for vacuous, and shrinking among them, so it can take a few times
its time limit, but each part ends. Shrinking takes no time limit, only its
own conflict budget (LOGIC.md section 14.3):
stopping it on time would return a less shrunk instance on a slower
machine. A command with a short time limit and a large scope can therefore
spend longer shrinking than solving (decided 2026-12-02, section 13).
What comes before the first solve is bounded by size, not by time: each
possible tuple of a relation is a solver variable, so a command whose
relations have more than 2^24 possible tuples in all, such as one of arity 6
at a scope of 30, is refused with model.scope_too_large before any bound
is built, as one with more than 4096 atoms is.
7.7 More instances
The next instance (R13) is found by adding one clause that rules out the
last one: not all of the relation variables take these values again. The
clause covers the variables of relations, skolem relations included, and
not the variables of gates. Alloy enumerates the same way: A4Solution.java
calls solveAll on its bundled Pardinus, whose clause covers every primary
variable, those of skolem relations among them (ExtendedSolver.java,
nextNonTrivialSolution). Two instances that differ only in a witness are
therefore two instances on both sides.
7.8 Determinism
The same model and scope give the same verdict and the same instance everywhere (R14). That needs every step to be a function of its input:
- Relations are numbered in the order they were declared, and a relation’s variables in the order of its tuples.
- Gates are numbered in the order they are first built, and the translation walks a formula in a fixed order.
- Clauses are added in gate order. The symmetry predicate and blocking clauses come last, in a fixed order.
- No collection on a result path iterates in hash order (AGENTS.md law 16).
- The default solver runs with a fixed seed, one thread, and no time-based decision. Separate solves may run on separate threads, as the command line runs a file’s commands and the comparison with Alloy runs the corpus’s, because each result depends on its own command alone and the results are reported in a fixed order; two threads never share one solve.
- Shrinking tries its candidates in a fixed order (section 9.6).
The check: the corpus’s first instances and their order are golden files, compared on the three CI platforms.
7.9 Slicing
Before a check is solved whole, Elinvar tries to solve a smaller problem
that gives the same verdict: the cone of influence of the assertion
(coi.rs). It starts from the relations the assertion names and adds
every fact that mentions one of them, and every step of the transition
fact that can change one of them, until nothing more is added. The rest is
dropped, and solved apart only to show that it allows some case, so that
holds is never reported where the dropped part is empty.
The argument is that every trace of the whole model projects onto a trace of the slice and back. It needs each dropped step to leave every kept relation unchanged, so what a step leaves unchanged is read exactly:
R' = RfixesR.all x: D | x.f' = x.ffixesfonly whenDis a fixed relation and a fact typesfasf in D -> ..., so that no row offlies outsideDin either state. It never fixesDitself.- Anything else fixes nothing: a frame over part of
f’s domain, a frame over a changingD, and a one-rowp.f' = p.finsidesome p | ...each leave the other rows offfree, so the step writesf.
A frame read as fixing more than it does once gave a wrong holds; each
such model is a planted hole (CORPUS.md section 5).
Slicing can be switched off (Options::slicing, --no-slicing on check
and diff). Symmetry breaking (Options::symmetry_breaking,
Options::predicate_length, --symmetry N / --no-symmetry) and Alloy’s
noOverflow (Options::no_overflow, --no-overflow) are exposed on check,
run, and diff (and MCP). Off, every check is solved whole, and so are diff’s
reductions of a transition fact. That is the reference answer: a test
draws small temporal models from a seeded generator over these frame
shapes and requires the same verdict with slicing on and off, and no
proved where the whole problem has a counterexample
(crates/elinvar-als/tests/slicing.rs).
8. Time
Phase 3, R19 to R22. Specified in LOGIC.md before it is coded (LOGIC.md section 11).
8.1 Traces
A relation is fixed or changing (R19). A trace is a finite list of states,
each an instance of the changing relations, with a loop from the last state
back to one of the states: a lasso (R21). Read as an infinite sequence that
repeats its loop for ever, it gives every temporal formula a plain meaning,
and that reading is the definition. Pardinus assumes the same: “traces are
assumed to always loop” (TemporalTranslator.java).
The limit on steps is part of the scope (for 3 but 6 steps). Alloy’s
default is 10 (ScopeComputer.java, maxtrace).
8.2 Temporal formulas
The operators are those of R20: always, eventually, after, until,
releases; the past operators before, historically, once, since,
triggered; and the prime, for the value of an expression in the next
state. triggered, the past form of releases, is in Alloy 6 (Alloy.lex;
TemporalOperator.java in Pardinus) and was added to R20 on 2026-11-28, so
that Alloy’s temporal models can be read unchanged
(section 13).
The evaluator gets its own direct reading of these on a lasso, written from the definition and sharing nothing with the translation. A counterexample trace is refereed like any other instance (R15).
8.3 Translation
Start where Alloy 6 does (REQUIREMENTS.md open decision 5): unroll. For each trace length from 1 up to the limit, build the static problem “a lasso of this length satisfies the formula” and solve it. The shortest counterexample in steps is then the first one found.
Pardinus builds that static problem inside the relational logic: it adds
state atoms, gives every changing relation one more column for the state,
and adds relations for the first state, the last state, the successor, and
the loop (TemporalTranslator.java: Time, S/first, S/last, S/next,
loop). To keep past operators sound on a loop it unrolls the loop as many
times as past operators are nested (countHeight in the same file).
Elinvar can do the same, or unroll one level lower, in the circuit: one table per changing relation per state, and one variable per candidate loop target. The second avoids the extra column and keeps state atoms out of the universe and out of symmetry detection. Which one is open (section 13); it is settled when the time section of LOGIC.md is written, and either way the evaluator’s independent reading referees the result.
8.4 Actions and frames
Forgetting to say what a step leaves unchanged is the most common mistake in a model of this kind (R22). An action is a named step with parameters, a guard, and effects on named relations. The helper adds, for every changing relation the action does not mention, that it stays as it was. The model says which actions exist, and the helper adds that every step is one of them, or a step where nothing changes.
Actions also give counterexamples their words. Each step of a trace is labelled with the action that happened and its arguments, which is what turns a list of states into a story (section 9.6).
9. Front doors
9.1 What agents need
Elinvar is designed for an agent’s loop: describe the design, check it, read what broke, change the design, check again. From that:
- A way in that needs no Rust project: one binary, a model as text, one call per check, no state kept between calls.
- A syntax it already knows. Alloy’s.
- A verdict as data, with a schema and a version, and an exit status that says the same thing.
- A counterexample it can act on: the smallest one, as named steps, in few tokens.
- Errors that say where and how to fix it, under stable codes, with
elinvar explain CODEfor the long form. - No silent success. An empty model, a rule that was ignored, or rules that contradict each other are reported, not passed (section 7.6).
- A budget on every call, and
unknownwhen it runs out. An agent must never wait on a solver without a limit. - The same answer for the same input, so results can be cached and compared.
- A way to ask questions about a counterexample without solving again:
elinvar eval, the evaluator as a tool. - Safety: model text is data, and nothing an agent sends executes code or reaches the network (AGENTS.md law 11).
9.2 The Rust library
The second door is a model written in Rust, beside the code it describes,
checked in cargo test (R23, R26). The README’s example, as it is in
crates/elinvar/tests/readme.rs, where a test keeps it under fifty lines:
use elinvar::prelude::*;
fn notes_need_access() -> (Model, Formula) {
let mut m = Model::new();
let person = m.set("Person");
let item = m.set("Item");
let owner = m.field_with("owner", &item, Multiplicity::One, &person);
let follows = m.changing_field("follows", &person, &person); // follower -> reader
let shared = m.changing_field("shared", &item, &person);
let notes = m.changing_field("notes", &item, &person);
// Who can open an item: its owner, and those it is shared with who
// still follow the owner.
let can_open = owner.union(&shared.intersection(&owner.join(&follows.transpose())));
m.fact(shared.no().and(¬es.no()));
m.action("share", [&item, &person], |step, [i, p]| {
step.when(i.join(&owner).is_in(&p.join(&follows)));
step.add(&shared, i.product(&p));
});
m.action("unfollow", [&person, &person], |step, [p, q]| {
step.when(q.is_in(&p.join(&follows)));
step.remove(&follows, p.product(&q));
});
let note = m.action("note", [&item, &person], |step, [i, p]| {
step.when(p.is_in(&i.join(&shared))); // forgot the follow
step.add(¬es, i.product(&p));
});
let promise = always(all([&item, &person], |[i, p]| {
note.happens(&[&i, &p]).implies(&p.is_in(&i.join(&can_open)))
}));
(m, promise)
}
#[test]
fn notes_need_access_holds() {
let (m, promise) = notes_need_access();
m.check(&promise).named("NotesNeedAccess").scope(3).steps(6).assert_holds();
}
assert_holds panics with the story of section 9.6 as its message, so the
counterexample is the test’s failure (R26). The value it would have returned
is the same result type every other door gets.
API rules, checked on every public change (AGENTS.md law 26):
- No third-party types in stable signatures.
- Growing structs and enums are
#[non_exhaustive]. - Building a model never fails;
runandcheckreturn every error together, each with its place (section 6.4). - The library never prints, reads stdin, installs signal handlers, or spawns processes.
- Every result type implements
Displayfor people,serdefor machines, andClone + Send + Sync. #[must_use]on builders and results. No panic on user input; the one panic is a failed referee (AGENTS.md law 13).- Every public item has a compiled example. Error codes are documented and tested.
9.3 The command line
The first door. Every command is a verb, modes are flags, and subjects are arguments (AGENTS.md law 32):
elinvar check sharing.als every check in the file
elinvar check sharing.als NotesNeedAccess one of them
elinvar check sharing.als --explain with minimal unsat-core facts/guards on holds/proved/vacuous
elinvar run sharing.als --explain with the minimal unsat-core facts on a run with no instance
elinvar check sharing.als --induction prove `always P` for any number of steps by k-induction
elinvar check sharing.als --climb --budget 100000
climb scopes under budget until a hole or budget runs out
elinvar check sharing.als --summary one compact Markdown table across all checks
elinvar run sharing.als show --shrink --brief
find a shrunk instance, omitting empty relations
elinvar run sharing.als show --all --sql enumerate all non-isomorphic instances up to scope
elinvar tests sharing.als --sql generate step reachability and per-guard refusal tests
elinvar accepts sharing.als trace.sql check whether a trace JSON or SQL script is allowed
elinvar eval sharing.als result.json 'Item.shared' --state 2
elinvar diff old.als new.als --json compare two design revisions (or two `.sql` schemas)
elinvar diff old.sql new.sql --tables orders compare a table slice (plus FK and trigger targets)
elinvar diff old.als new.als --of visible compare one function or query between two models
elinvar import schema.sql --strict --temporal
turn SQL DDL (and triggers) into an Alloy 6 model
elinvar render result.json --sql render an instance or trace as DOT, Mermaid, or SQL
elinvar render sharing.als --mermaid render a model's signatures, fields, and steps
elinvar explain arity.mismatch an error code, in full
elinvar explain schema:result a verb's JSON Schema (`elinvar explain schema` lists them)
elinvar serve --mcp the same verbs as MCP tools
--jsonon every verb prints the result as one JSON document (section 9.5). Without it the same result is rendered as text.--scope,--steps, and--budgetoverride what the file says.- How a SQL schema becomes a model, and what
import,accepts,fuzz,audit,discover, andcido with it, is SQL.md. - Exit status: 0 when every promise holds or the instance was found; 1 when
a counterexample was found or no instance exists; 2 when a verdict is
unknownorvacuous; 3 when the model has errors. The JSON says the same in full. - A verb that cannot start, for a flag, argument, or verb it does not take
(
cli.usage) or an input it cannot read (cli.input), exits 3 too. With--jsonit printscode,error, and the verb’shelp(schema:usage); without,elinvar: error[CODE]: ...on stderr. --helpon every verb is complete enough to use the verb with nothing else, andelinvar explaincovers every code and schema (AGENTS.md law 18).
9.4 Model text
The text form of a model is Alloy 6’s own syntax, a documented subset of it (decided 2026-11-28; this answers open decision 4 of REQUIREMENTS.md with “yes”, for a new reason: it is the agent’s door). The README’s example, as an agent would write it:
sig Person { var follows: set Person }
sig Item {
owner: one Person,
var shared: set Person,
var notes: set Person
}
fun canOpen: Item -> Person { owner + (shared & owner.~follows) }
pred share[i: Item, p: Person] {
i.owner in p.follows
shared' = shared + i->p
follows' = follows
notes' = notes
}
pred unfollow[p, q: Person] {
q in p.follows
follows' = follows - p->q
shared' = shared
notes' = notes
}
pred note[i: Item, p: Person] {
p in i.shared // rule 3 forgot the follow
notes' = notes + i->p
follows' = follows
shared' = shared
}
pred nothing { follows' = follows and shared' = shared and notes' = notes }
fact {
no shared and no notes
always (nothing
or (some i: Item, p: Person | share[i, p] or note[i, p])
or (some p, q: Person | unfollow[p, q]))
}
assert NotesNeedAccess {
always all i: Item, p: Person | note[i, p] implies p in i.canOpen
}
check NotesNeedAccess for 3 but 6 steps
Each predicate repeats what stays the same, three times over. That repetition is what R22’s helper removes in the Rust form, and a matching form for text is an extension to consider once the subset works (section 13).
What the subset leaves out: strings, unbounded 1.. steps, sum disj, and
recursive predicates or functions. Bounded integers
(LOGIC.md section 16) and sequences (seq T,
seq/Int, for N seq, util/sequniv) are read. A model that uses an
unsupported construct gets an error with a code that names the construct
and the line, never a wrong answer. Reading text needs what the core does
not have: name resolution, Alloy’s types, signature hierarchies turned into
bounds, and scopes. That is why it is its own crate and its own phase.
One fact from the source shapes this. Alloy puts 16 integer atoms in the
universe of every command, whether the model uses integers or not
(ScopeComputer.java: shouldUseInts = true, bitwidth 4), so univ,
iden, and reflexive closure range over them. Agreement with Alloy on a
model that mentions those needs the same atoms present, as plain atoms
(LOGIC.md section 10).
9.5 Results as data
One result type serves every door. Its JSON form has a schema and a version
(AGENTS.md law 19): docs/schema/result-v1.json, written by cargo x generate and checked by cargo x verify, with the README example’s result
pinned by a golden file. LOGIC.md section 14 specifies it; what follows was
the first sketch, kept as the record of the intent:
{
"elinvar": 1,
"command": "check",
"name": "NotesNeedAccess",
"verdict": "counterexample",
"scope": { "Person": 3, "Item": 3, "steps": 6 },
"shrunk_to": { "Person": 2, "Item": 1, "steps": 3 },
"trace": {
"loop_to": 3,
"states": [
{ "step": 0, "follows": [["Person0", "Person1"]], "shared": [], "notes": [] },
{ "step": 1, "action": "share", "args": ["Item0", "Person0"],
"changed": { "shared": { "added": [["Item0", "Person0"]] } } }
]
},
"broken_at": 3,
"story": "..."
}
An instance lists its atoms and each relation’s tuples (R24). A trace lists
its states, what changed at each step, and where it loops. States and steps
share one numbering: state 0 is the start, step i is the change that leads
to state i, and broken_at and loop_to are state numbers. The story
uses the same numbers, so “broken at step 3” is "broken_at": 3. Errors and
warnings are entries with a code, a place, a message, and a fix. Atom names
come from the set they belong to and a number, as Alloy’s do.
Graphviz dot, Mermaid flowchart, and executable SQL replay renderings of an
instance or trace are produced directly from the same result data
(render_instance, render_trace, render_report, and elinvar render;
REQUIREMENTS.md section 3).
9.6 Stories and shrinking
The text rendering of a counterexample is a story: what there is, then one line per step saying what happened and what changed, then where the promise broke (R24). For the README’s example it should read about like this:
check NotesNeedAccess: FAILS in 3 steps, with 2 people and 1 item
start Person0 follows Person1. Item0 is owned by Person1.
step 1 share(Item0, Person0) shared gains Item0 -> Person0
step 2 unfollow(Person0, Person1) follows loses Person0 -> Person1
step 3 note(Item0, Person0) notes gains Item0 -> Person0
broken at step 3: Person0 notes Item0, but Item0.canOpen is {Person1}.
searched every case up to 3 people, 3 items, 6 steps.
Before it is shown, a counterexample is shrunk (R25). Smaller means, in this order: fewer steps, then fewer atoms, then fewer tuples.
- Fewer steps come from the search itself, which tries trace lengths in increasing order (section 8.3).
- Fewer atoms: solve again with smaller scopes, one set at a time in the order the sets were declared, keeping a reduction when a counterexample still exists.
- Fewer tuples: for each tuple of the instance in a fixed order, ask the solver for a counterexample without it, keeping the removal when one exists. These are solves under assumptions on the clauses already built.
The symmetry predicate is left out of the solves that remove tuples. It keeps one representative of each group of renamed instances, and the smaller counterexample need not be the one it keeps, so with the predicate in force a removal can be refused though a smaller counterexample exists. The result would still be a true counterexample, only not the smallest. Either the predicate sits behind one literal that these solves assume false, or the clauses are rebuilt without it; phase 4 chooses.
Every candidate is refereed, and the order is fixed, so shrinking is deterministic. The exact procedure, and its budget, are specified in phase 4 before they are coded. The result says both the scope searched and the size shrunk to.
9.7 MCP
elinvar serve --mcp offers the verbs of section 9.3 as tools over stdio,
one JSON-RPC 2.0 message per line, under MCP 2025-06-18: check, run,
diff, import_sql, render, eval, tests, accepts, discover,
audit, and explain. On initialize, it returns concise instructions
and advertises resources: skill://elinvar/SKILL.md and every schema of
elinvar explain schema, served from the copies embedded in the binary.
Each tool takes model text or result JSON and options and returns the
result JSON, with isError when the result is the verb’s errors.
Where the command line names a file, a tool takes its text. A .sql file
is is_sql with the DDL as model, and --with sidecars are promises
(Alloy) and views (SQL), on check, run, eval, and accepts as on
the command line.
It is an adapter: it holds no state, and it can do nothing the command line
cannot. Two verbs are left out because a tool call would make them do what
an agent’s text should not: fuzz runs a database command (--against),
and ci reads a manifest and the files it names from disk. An agent with a
shell runs both from the command line.
Nothing sent is dropped without an answer (AGENTS.md law 20). An argument a
tool’s inputSchema does not list is a tool error that names the arguments
it takes, as a wrongly typed one is, so the agent can correct the call. A
message that is not a request object, a JSON array (MCP 2025-06-18 has no
batches) included, is answered with -32600 and id null; a request with no
string method or no "jsonrpc": "2.0" with -32600; params that are not
an object, an unknown tool, or a missing resource uri with -32602. A
message with no id is a notification and gets no reply. If another agent
protocol replaces MCP, the adapter is replaced and nothing else changes.
A guide for agents, skills/elinvar/SKILL.md, ships in the release archive:
when to reach for Elinvar, how to turn a design into rules and a promise,
how to read a verdict, and what holds does and does not mean.
9.8 Measuring it
“Agents first” is measured, not asserted. The agent suite is a set of tasks,
each a design described in prose with a hole planted in it (the planted
holes of CORPUS.md section 5, told as stories),
a task with no hole, or a vacuous-rules trap where contradictory rules must
be reported as vacuous rather than holds. An agent gets the prose, the
elinvar binary, and SKILL.md. It passes a hole task when the trace or
instance it reports is a real counterexample: the evaluator replays it
against the task’s reference model. It passes a no-hole or vacuity task by
reporting the matching verdict without inventing a hole or altering the
rules.
cargo x agents --agent CMD runs the suite (7 tasks) and records a
baseline per agent; --replay re-scores the outputs it saved. The first
baseline, Claude Code on 2026-11-28, passed all four initial tasks
(agents/baselines/claude-code.md). A change to the command line, the result format, the error messages,
or SKILL.md is judged by what it does to that baseline.
10. Verification
Alloy is never run to build or test (R16), so correctness comes from four sources that need no reference implementation at test time, and one that needs Alloy only when its answers are regenerated.
- The referee (R15). Every instance returned by
run,check, the next instance, or shrinking is evaluated against the formula as the user wrote it, before skolemization. This catches every wrong “here is a counterexample”. It cannot catch a wrong “there is none”; the rest of this list is for that. - Spec tests. Each rule in LOGIC.md gets tests with hand-worked values, and its worked examples are tests (LOGIC.md section 9).
- Known counts. Brute-force enumeration with the evaluator must give the known number of total orders, equivalence relations, functions, and acyclic graphs on small sets (LOGIC.md section 8). No solver, no reference implementation.
- Brute force against the solver (R18). For tiny universes, the set of
instances the solver enumerates with symmetry breaking off equals the set
brute force finds, and with it on, both agree on whether any exists.
Formulas come from the spec tests and from a seeded generator of random
formulas, so a failure is reproduced from its seed. A second, bit-sliced
counter in
elinvar-engine(count_bitsliced) evaluates 4,096 instances at once with SIMD bit operations (macerator), which takes the comparison to five atoms, 2^25 instances of a relation, against known counts. It must agree with the plain counter ofelinvar-logic, which stays the definition and the referee. - Planted holes (R17). Models with a known hole; reporting no counterexample is a failure (CORPUS.md section 5). Every wrong “no counterexample” ever found becomes one.
- Agreement with Alloy (R16). A corpus of models exists twice, as
.alsand as Rust. For each command the verdict matches Alloy 6.2.0, and with symmetry breaking off the count of instances matches where the count is small enough to enumerate (CORPUS.md section 4). From phase 5 the.alsside is read directly, and the two translations check each other. - Determinism (R14). Golden first instances, compared on Linux, macOS, and Windows (section 7.8).
- Formats. Golden files of the result JSON and the stories; old versions keep parsing.
- Agents. The suite of section 9.8.
- Speed (R29).
cargo x bench corpusrecords each corpus command’s time beside Alloy’s recorded time and prints the change from a local baseline. It fails only if the harness fails.
What this does not give: proof that the translation is right. A formula outside everything above could still translate wrongly to “no counterexample”. The mitigation is breadth in the corpus and the random formulas, and the rule that the referee never shares code with the translation.
11. Roadmap
Phases 1 to 5 are those of REQUIREMENTS.md section 5, with the agent door written into phases 4 and 5.
| Phase | Scope | Exit criteria |
|---|---|---|
| 0. Bootstrap | workspace, cargo x verbs, AGENTS.md, this design, LOGIC.md for phase 1, the corpus inventory, CI on three platforms, the license, the book | CI green; the open decisions that block phase 1 settled |
| 1. Relational core | elinvar-logic: universe, relations, bounds, expressions, formulas, build-time errors with places, instances, the evaluator, brute-force enumeration (R1 to R7) | every operator matches its hand-worked answer; brute-force counts match the known numbers |
| 2. Finding | LOGIC.md extended first; skolemization, circuit, clauses, the solver trait and the default solver, symmetry breaking, run, check, verdicts and budgets, the next instance, the referee wired in; the corpus and cargo x corpus, oracle, bench corpus (R8 to R18) | the first ten corpus models agree with Alloy; every planted hole in a static model is found; the solver agrees with brute force on random formulas; first instances identical on three platforms |
| 3. Time | LOGIC.md extended first; changing relations, temporal formulas, traces, the unrolling, the evaluator on traces, actions with frames (R19 to R22) | the sharing example’s hole is found as a three-step trace; the temporal corpus agrees with Alloy 6 |
| 4. Answers | the Rust front polished, results as data with schemas, error codes with fixes, stories, shrinking, assert_holds (R23 to R26, R30 to R33) | the README example is under fifty lines and its failure reads as a short story; result JSON pinned by golden files |
| 5. The agent door | elinvar-als for the documented subset of Alloy 6, the command line, serve --mcp, SKILL.md, the agent suite (R34, R35) | Alloy’s example models that stay inside the subset run unmodified and agree with Alloy; an agent suite baseline is recorded; release binaries |
Phases 1 and 2 are the critical path: that is where trust is won or lost, and nothing in a later phase delays them (AGENTS.md law 35).
Agent-first does not mean the agent door is built first. The laws under “Agents first” in AGENTS.md hold from phase 1: codes, places, data before text, no panic, no hang. Phase 4 ran before phase 5 so stories and shrinking were ready for the command line and MCP; both phases are now built.
12. Risks
- A wrong “no counterexample”. The whole of section 10 exists for this, and it remains the main risk.
- Scale. Grounding a quantifier multiplies the circuit by the size of what it ranges over; nested quantifiers over a scope of 6 or 7 can already be large. Speed is not a first goal (R29), but a check an agent waits a minute for is not used. Measured from phase 2 on the corpus.
- The default solver. Elinvar’s own CDCL solver (
sat::Cdcl) is small and in-tree, and sits behind theSolvertrait so callers can plug in a faster external solver when needed. - The size of Alloy’s language. Signatures, multiplicities, modules,
util/ordering, and the type system are a large surface, and agreement with Alloy depends on details such as the integer atoms in every universe. Phase 5 takes a documented subset and rejects the rest by name. - Time. Past operators on a loop are easy to get subtly wrong. Mitigated by the evaluator’s independent reading and the temporal corpus.
- Shrinking can cost many solves. It has its own budget, and a counterexample that ran out of it is still returned, marked as not fully shrunk.
- Agents trust “holds” too much. Mitigated by the scope in every verdict,
the
vacuousverdict, and whatSKILL.mdsays about both. The agent suite’s tasks without a hole measure the opposite failure.
13. Decisions and open questions
Decided on 2026-11-28, by the user:
- Inspired by Alloy and extending it, not a line-by-line port. The relational core follows Alloy’s and Kodkod’s design closely enough that answers can be compared; everything around it is free to differ (REQUIREMENTS.md section 1 and open decision 2).
- Agents first. Elinvar’s first users are agents; the principles, the laws under “Agents first” in AGENTS.md, and section 9 follow from that.
- The project is laid out as kepler is: the documents in
docs/, served as a book bycargo x docs, every operation acargo xverb, the laws in AGENTS.md. - License: MIT OR Apache-2.0, the Rust convention (section 14). This settles open decision 1 of REQUIREMENTS.md.
- The default solver is Elinvar’s own conflict-driven solver, written in
the
elinvar-enginecrate, notbatsat(section 7.4). Settles open item 2. - Elinvar aims to be the best version of Alloy, not a copy: matching Alloy’s verdicts matters, matching its internals does not.
- Integers are in scope: bounded and wrapping, as Alloy’s are (LOGIC.md section 16). REQUIREMENTS.md section 6 left them out; the user chose to add them on 2026-11-28, with 17 of Alloy’s example files unread for want of them.
- The minimum supported Rust version is 1.94 (AGENTS.md law 9), the
version
maceratorneeds;cargo x msrvruns the tests on it. Set with the user on 2026-11-28. - The crates are published on crates.io, from 0.1.0 on:
cargo install elinvarinstalls the command line, and a tagged release also builds archives (cargo x dist). The four crates share one version and are published in dependency order:elinvar-logic,elinvar-engine,elinvar-als,elinvar. Until 2026-12-03 they were not published, set with the user on 2026-11-28; the user chose to publish on 2026-12-03. - SIMD, through
macerator, for brute-force enumeration: a bit-sliced counter inelinvar-engine(section 10). The solver’s hot path, unit propagation, walks pointers and gains nothing from SIMD, so it does not use it. - Threads, through
rayon, asked for by the user on 2026-11-29: the command line solves a file’s commands in parallel, and the comparison with Alloy incargo x corpusruns its commands in parallel. The library stays single-threaded (AGENTS.md law 23), and one solve is never split, since which thread finished first would then choose the answer (section 7.8). - Shrinking is bounded by its conflict budget only, never by the time
limit, so
--timeoutcannot change which instance is returned (AGENTS.md law 17, LOGIC.md section 14.3). The cost: a short time limit at a large scope can be followed by a long shrink. Decided by the user on 2026-12-02. - The integer shifts
<<,>>, and>>>joinIntOp, which becomes#[non_exhaustive]in the same change: the public signature breaks once, before the first release, and not again (LOGIC.md section 16). Decided by the user on 2026-12-02. - The crate a user names is
elinvar, for both uses:cargo install elinvarinstalls the command line, anduse elinvar::prelude::*reaches the library. The engine is renamedelinvar-engine, andelinvar-clibecomes theelinvarfacade, which re-exports the engine and the Alloy reader and holds the command line in itsclimodule (section 5.2). The cost: a library user also builds the command line’s two dependencies,rayonandserde_json; a feature to leave them out waits for someone to need it (AGENTS.md law 25). Decided by the user on 2026-12-03, before the first release, so no published name changes.
Assumed on 2026-11-28 while the user’s answers are pending, each the recommended option of a question put to them; each is easy to reverse:
- Counts are compared with Alloy only for commands where no skolem witness arises; for the rest, verdicts only. Settles open item 9 for now.
- Without Java on the development machine, expected corpus answers came
from the models’ own
expectlines, comments, and reasoning, untilcargo x oracleran. It ran on 2026-11-28 with a JDK unpacked undertarget/oracle/, which changes nothing outside the repository; its answers are incorpus/expected.txt. - Alloy’s example models are not copied into the repository: its LICENSE at 6.2.0 is unclear (AGENTS.md law 39). Rust translations cite the upstream file at the pinned commit.
- Random formulas for the brute-force comparison come from an in-house seeded generator, so no dependency is added. Settles open item 8.
Decided on 2026-11-28, by the user, as the first draft proposed them:
- Crates:
elinvar-logicandelinvaras the two libraries, split at the trust boundary, withelinvar-alsandelinvar-cliin phase 5 (section 5.2). Answers open decision 6 of REQUIREMENTS.md. The engine and the command line were renamed on 2026-12-03 (above). - Model text is a subset of Alloy 6’s syntax (section 9.4). Answers open decision 4 with “yes”.
triggeredis included with the other temporal operators, and added to R20 (section 8.2).- The
vacuousverdict (section 7.6). - Domain and range restriction, and the quantifiers
no,one, andlone, are core operators (section 6.3). - Upstream pins: Alloy at its 6.2.0 tag (
59ba203), the newest release, so that expected answers come from a released build; Kodkod (6e80244) and Pardinus (d3e7aea, also its 1.2.4 tag) at the heads of their default branches on 2026-11-28. - No minimum supported Rust version until the first release (AGENTS.md law 9). Superseded: 1.94, decided on 2026-11-28 (above).
Open:
- How much of Kodkod’s source is read (REQUIREMENTS.md open decision 2). This draft read the operator lists, the option defaults, the symmetry classes, and Pardinus’s temporal translator, for their design. No code follows them. A file that does follows AGENTS.md law 38.
- The default solver. Decided above: Elinvar’s own.
- The time translation. Settled on 2026-11-28 when LOGIC.md section 13 was
written, as section 8.3 said it would be: unrolling in the circuit
(LOGIC.md section 13.4). For
L > 1, one problem per lengthLunrollspast_depth + 1copies and chooses the loop target with selector variables (ruling out allLloop targets in one solve when unsatisfiable, then picking the earliestjunder assumptions). - Whether phase 5, the agent door, should come before phase 4. Settled on 2026-11-28: phase 4 ran first so stories and shrinking were ready for the command line and MCP, and both phases are built.
- Compile-time checks beyond the split between expressions and formulas (section 6.4).
- A frame helper in model text, to match R22’s in Rust (section 9.4). It would be an extension to Alloy’s syntax, so a model using it would no longer run in Alloy.
- Whether a default scope exists. Alloy’s is 3 (
ScopeComputer.java). The README says “a size you choose”. For text, following Alloy is the least surprise; for the Rust builder, no default. - Random formulas for the brute-force comparison. Assumed above: an in-house seeded generator.
- Assumed above: verdicts only where a witness arises. How instance
counts are compared with Alloy’s when a command has
witnesses. Skolem relations count on both sides (section 7.7), so
the counts agree only if both skolemize the same quantifiers
(section 7.2). Alloy rewrites
no,one, andlonebefore Kodkod sees them, which can put a skolemizable quantifier where Elinvar’s core form has none. The plain case is acheckofno x: e | F: Alloy solves the negation ofall x: e | not F, and the witness forxis skolemized.oneandloneover sets become the multiplicity of a comprehension, and nothing inside a comprehension is skolemized (TranslateAlloyToKodkod.java,visit_qt;Skolemizer.java,visit(Comprehension)). Either Elinvar’s skolemization mirrors what Alloy’s rewriting produces, or counts are compared only for commands where no witness arises and verdicts for the rest. To be settled when phase 2 specifies skolemization.
14. Naming and licensing
- The name is Elinvar (README.md). The crates,
elinvar,elinvar-engine,elinvar-logic, andelinvar-als, are on crates.io (section 13). - Elinvar is not affiliated with Alloy, Kodkod, Electrum, or Pardinus, and credits them in the README and in NOTICES.md.
- Elinvar is dual licensed, MIT OR Apache-2.0 (
LICENSE-MIT,LICENSE-APACHE), copyright Dilshod Tadjibaev. Alloy’sLICENSEfile begins “THIS IS NOT VALID YET! CURRENTLY CODE IS UNDER MIT LICENSE” above the text of Apache-2.0, and its source files carry an MIT notice; Kodkod and Pardinus are MIT (theirLICENSEfiles). The dual license is compatible with all of them. A file that follows upstream source, or a model copied from it, keeps upstream’s notice and is listed in NOTICES.md (AGENTS.md laws 38 and 39).
Elinvar: the logic
Status: current, 2026-11-29. Specifies phases 1 to 5 and bounded integers (R1 to R26 of REQUIREMENTS.md): what a model is made of, what every operator means, finding, time, answers, model text, and integers.
This is the definition the evaluator computes and everything else is judged by (DESIGN.md section 6.5, AGENTS.md law 12). Where it follows Alloy or Kodkod, and where it does not, is in section 10.
Contents: 1 Universe, atoms, tuples · 2 Relations, bounds, instances · 3 Expressions · 4 Formulas · 5 Declarations and variables · 6 Errors · 7 The evaluator · 8 Counting by brute force · 9 Worked examples · 10 Compatibility with Alloy and Kodkod · 11 Not yet specified · 12 Finding · 13 Time · 14 Answers · 15 Model text · 16 Integers
1. Universe, atoms, tuples
A universe is a list of n atoms, n at least 1, each with a name, the
names distinct. The position of an atom in the list, from 0, is the atom:
two universes with the same names in a different order are different
universes.
A tuple of arity k, k at least 1, is a sequence of k atoms of one
universe. An arity of 0 is an error (arity.zero), and so is a tuple that
names an atom the universe lacks (universe.unknown_atom). Its index is its
atoms read as digits in base n, first atom most significant:
index(a1, ..., ak) = a1 * n^(k-1) + a2 * n^(k-2) + ... + ak
Tuples of the same arity are ordered by index. A tuple set has an arity and
holds tuples of that arity, in order, each at most once; a tuple of another
arity is an error (tuples.arity), and so is one over another universe
(tuples.other_universe). Two universes are the same when they have the
same names in the same order.
The number of tuples of an arity in use, n^k, is at most 2^64 - 1, so
that it and every index fit in 64 unsigned bits. A universe and an arity
past that are an error (section 6, universe.capacity). An expression
has no universe of its own, so the check is made where an arity meets a
universe: when a tuple set is built, and when a formula is evaluated, run,
or checked.
2. Relations, bounds, instances
A relation has a name and an arity of 1 or more (arity.zero otherwise).
Two relations are the same only if they are the same declaration; the name
is for people. A set is a relation of arity 1.
Identity is compared for equality and for nothing else. Whatever it is made of may differ from one run to the next, so it has no order that means anything, and nothing on a result path sorts or iterates by it (AGENTS.md law 16). Order comes from the bounds.
Bounds, over one universe, give each of a list of relations two tuple sets
of its arity: a lower bound and an upper bound, with the lower inside the
upper. The order of the list is the order in which the relations were given
their bounds. That is the declaration order every later section means: the
model builder gives bounds in the order the model declares. A relation is in
the list once (bounds.duplicate_relation), and the names in one list are
distinct (bounds.duplicate_name). An exact bound is one whose lower and
upper are equal.
An instance, over the same universe, gives each relation a tuple set of its
arity. It is within the bounds when, for every relation, the lower bound is
inside its tuple set and its tuple set is inside the upper bound. An
instance built by hand is checked as bounds are, under the instance.
codes of section 6.
Because names are distinct within one bounds or instance, its serialized form names each relation by its name, in list order. Reading one back takes the list of relations it is for and matches them by name; identity itself is never written.
3. Expressions
An expression has an arity and, given an instance and values for its free
variables, denotes a tuple set of that arity. Below, A and B are the
tuple sets of a and b, and |a| is the arity of a.
| Expression | Written | Requires | Arity | Denotes |
|---|---|---|---|---|
| relation | r | that of r | the instance’s tuple set for r | |
| variable | x | bound (section 5) | 1 | the one atom x is bound to |
| empty | none | 1 | no tuples | |
| everything | univ | 1 | every atom | |
| identity | iden | 2 | (a, a) for every atom a | |
| union | a + b | |a| = |b| | |a| | tuples in A or in B |
| intersection | a & b | |a| = |b| | |a| | tuples in A and in B |
| difference | a - b | |a| = |b| | |a| | tuples in A and not in B |
| join | a . b | |a| + |b| > 2 | |a| + |b| - 2 | (a1, ..., a(i-1), b2, ..., bj) for every (a1, ..., ai) in A and (b1, ..., bj) in B with ai = b1 |
| product | a -> b | |a| + |b| | (a1, ..., ai, b1, ..., bj) for every tuple in A and every tuple in B | |
| transpose | ~a | |a| = 2 | 2 | (y, x) for every (x, y) in A |
| closure | ^a | |a| = 2 | 2 | the smallest set T with A inside T and T . T inside T |
| reflexive closure | *a | |a| = 2 | 2 | ^a + iden |
| override | a ++ b | |a| = |b| | |a| | the tuples of A whose first atom is the first atom of no tuple in B, and every tuple of B |
| domain restriction | s <: a | |s| = 1 | |a| | the tuples of A whose first atom is in S |
| range restriction | a :> s | |s| = 1 | |a| | the tuples of A whose last atom is in S |
| comprehension | {x1: e1, ..., xm: em | F} | section 5 | m | (a1, ..., am) for every binding of the declarations under which F is true |
| if-then-else | F => a else b | |a| = |b| | |a| | A if F is true, otherwise B |
Notes.
idenand*arange over the whole universe, not over the atoms some relation happens to hold.- For sets, override is union: every tuple is its own first atom.
- Join has no arity-0 result.
s . tfor two sets is an error, not “is the intersection non-empty”.
4. Formulas
A formula, given an instance and values for its free variables, is true or false.
| Formula | Written | Requires | True when |
|---|---|---|---|
| constants | true, false | always, never | |
| subset | a in b | |a| = |b| | every tuple of A is in B |
| equality | a = b | |a| = |b| | A and B hold the same tuples |
| some | some a | A has at least one tuple | |
| no | no a | A has no tuple | |
| one | one a | A has exactly one tuple | |
| lone | lone a | A has at most one tuple | |
| not | not F | F is false | |
| and | F and G | both are true | |
| or | F or G | at least one is true | |
| implies | F implies G | F is false or G is true | |
| iff | F iff G | both are true or both are false | |
| all | all x1: e1, ..., xm: em | F | section 5 | F is true under every binding |
| some | some x1: e1, ..., xm: em | F | section 5 | F is true under at least one binding |
| no | no x1: e1, ..., xm: em | F | section 5 | F is true under no binding |
| one | one x1: e1, ..., xm: em | F | section 5 | F is true under exactly one binding |
| lone | lone x1: e1, ..., xm: em | F | section 5 | F is true under at most one binding |
and and or take any number of formulas. With none, and is true and
or is false.
5. Declarations and variables
A variable has a name and stands for one atom. Two variables are the same only if they are the same declaration, as with relations.
A declaration x: e introduces x, where e is an expression of arity 1.
A quantifier or a comprehension has a list of one or more declarations
(logic.no_declarations for an empty list), and a later declaration’s
expression may use an earlier one’s variable.
A binding of x1: e1, ..., xm: em is a tuple (a1, ..., am) of atoms such
that a1 is in what e1 denotes, a2 is in what e2 denotes with x1
bound to a1, and so on. The bindings of a list are counted as tuples: in
one x: s, y: t | F, “exactly one” means exactly one pair. With no binding
at all, all, no, and lone are true, and some and one are false.
A variable is bound inside the body of the quantifier or comprehension that
declares it, and in the expressions of later declarations in the same list.
Anywhere else it is free. A formula given to the evaluator, to run, or to
check has no free variables.
There is no shadowing: a variable is not declared where it is already bound
(logic.rebound_variable). That rules out two cases and allows two.
- Twice in one list is an error:
all x: s, x: t | F. - Inside the body, or a later declaration, of a quantifier or comprehension
that declares it is an error:
all x: s | some x: t | F. - In two places of which neither is inside the other’s scope is fine, and
each is its own binding:
(all x: s | F) and (all x: t | G). - A declaration’s own expression is outside its variable’s scope, so
all x: {x: s | F} | Gis fine.
A declaration over sets or relations is written x: m e, with m one of
set, some, lone, or one, and x of the arity of e. Its bindings
are the tuple sets inside what e denotes with as many tuples as m
allows: any number, at least one, at most one, or exactly one. x: e with
e of arity 1 and no m is the declaration of one atom above, and with
e of greater arity it is x: set e. The evaluator enumerates these
bindings as it does any others; when e denotes more than 63 tuples it
cannot, and says so (enumerate.too_large). A comprehension declares
atoms only (logic.higher_order).
6. Errors
Arity errors are found when the node is built, and carry the place it was
built (DESIGN.md section 6.4). The others are found where the table says.
Every code is explained by elinvar explain (AGENTS.md law 21).
An ill-formed node has no arity. A node built from an ill-formed part is
ill-formed too. It keeps the errors of all its parts and records none of
its own, so (s + r) . r reports the one arity.mismatch and nothing for
the join, and (s + r) + (r <: r) reports both of its parts’ errors and
nothing for the outer +.
The evaluator, run, and check refuse a formula with any error, and
return all of them together (section 7). The evaluator takes an
expression too, and what this section and the table say of a formula that
is evaluated holds for an expression that is evaluated.
| Code | When | Message carries |
|---|---|---|
universe.empty | a universe with no atoms | |
universe.duplicate_atom | two atoms with one name | the name |
universe.unknown_atom | a tuple names an atom the universe lacks | the name |
universe.bitwidth | a bitwidth outside 1 to 32 (section 16.1) | the bitwidth |
universe.int | an integer atom’s integer outside the bitwidth’s range, two integers for one atom, or two atoms for one integer (section 16.1) | the atom, the integer, the range |
universe.capacity | n^k is more than 2^64 - 1, for a tuple set of arity k when it is built, or for an expression of arity k when its formula is evaluated, run, or checked | n, k |
tuples.arity | a tuple set is given a tuple of another arity | both arities |
tuples.index | a tuple set is given an index of no tuple of its arity, n^k or more | the index, n^k |
tuples.other_universe | a tuple set is given a tuple, or combined with a tuple set, over a different universe | |
bounds.arity | a bound whose arity is not the relation’s | both arities, the relation |
bounds.lower_outside_upper | a lower bound with a tuple the upper bound lacks | the relation, the first such tuple |
bounds.other_universe | a tuple set over a different universe | the relation |
bounds.duplicate_relation | bounds are given for a relation that has them | the relation |
bounds.duplicate_name | two relations of one bounds have one name | the name |
instance.arity | a tuple set whose arity is not the relation’s | both arities, the relation |
instance.other_universe | a tuple set over a different universe | the relation |
instance.duplicate_relation | a tuple set is given for a relation that has one | the relation |
instance.duplicate_name | two relations of one instance have one name | the name |
arity.zero | a relation or a tuple of arity 0 | |
arity.mismatch | +, &, -, ++, in, =, if-then-else with unequal arities | the operator, both arities |
arity.join | a join of two expressions of arity 1 | |
arity.not_binary | ~, ^, * on an expression of arity other than 2 | the operator, the arity |
arity.not_a_set | the set side of <: or :>, or a declaration’s expression, of arity other than 1 | the arity |
logic.free_variable | a formula with a free variable is evaluated, run, or checked | the variable |
logic.no_declarations | a quantifier or a comprehension with an empty list of declarations | |
logic.rebound_variable | a formula is evaluated, run, or checked, and declares a variable where it is already bound (section 5) | the variable |
logic.higher_order | a declaration over sets or relations in a comprehension, or, when a formula is run or checked, in a quantifier that skolemization cannot remove (section 12.2) | the variable |
logic.unbound_relation | a formula is run or checked and uses a relation the bounds lack | the relation |
instance.missing_relation | a formula is evaluated and uses a relation the instance lacks | the relation |
enumerate.too_large | brute-force enumeration over more free tuples than its cap | the count, the cap |
7. The evaluator
The evaluator takes an instance and an expression or a formula with no free variables, and returns the tuple set or the truth value that sections 3 to 5 define. It keeps an environment that maps each bound variable to an atom.
Before it computes anything it checks the whole expression or formula: the
errors recorded when its nodes were built, free and rebound variables, relations
the instance lacks, and capacity. It returns every error it finds,
together, and computes only when there is none. So an error is never hidden
by a part the computation would not reach, as in false and F or
all x: none | F.
It computes each definition as written:
- Set operators work on sorted tuple sets.
- Join and product build each result tuple from a pair of tuples.
- Closure starts from
T = Aand replacesTbyT + T . AuntilTstops growing. - A quantifier or a comprehension enumerates the bindings of its
declarations, first declaration outermost, each in tuple order, and
evaluates the body under each.
oneandlonecount the bindings under which the body is true.
It does not cache, reorder, or stop early in a way that could change an answer or hide an error. Its cost is whatever the definitions cost.
8. Counting by brute force
Given bounds, the free tuples are the tuples in some relation’s upper bound
and not in its lower bound, listed relation by relation in declaration
order and by index within a relation: t0, t1, ..., t(m-1). Instance
number j, for j from 0 to 2^m - 1, gives every relation its lower
bound plus those ti of its own for which bit i of j is set.
Enumeration goes through j in increasing order. The caller gives a cap on
m (enumerate.too_large). Whatever the cap, m above 63 is
enumerate.too_large, so that j and the count fit in 64 bits.
The count of a formula under bounds is the number of those instances under
which the evaluator finds it true. elinvar::count_bitsliced computes the
same count 4,096 instances at a time, for static first-order formulas, and
must agree with this one (DESIGN.md section 10).
These counts are known, and are phase 1’s test that the evaluator and the
enumeration are right together. The universe has n atoms, and r is one
relation of arity 2 with an empty lower bound and every pair in its upper
bound.
r is | Formula | n = 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| anything | true | 2 | 16 | 512 | 65536 |
| reflexive | iden in r | 1 | 4 | 64 | 4096 |
| symmetric | ~r in r | 2 | 8 | 64 | 1024 |
| a function | all x: univ | one x.r | 1 | 4 | 27 | 256 |
| a bijection | a function, and all x: univ | one r.x | 1 | 2 | 6 | 24 |
| transitive | r.r in r | 2 | 13 | 171 | 3994 |
| an equivalence | reflexive, symmetric, and transitive | 1 | 2 | 5 | 15 |
| a strict partial order | no iden & r, and transitive | 1 | 3 | 19 | 219 |
| a strict total order | a strict partial order, and all x, y: univ | x = y or x->y in r or y->x in r | 1 | 2 | 6 | 24 |
| acyclic | no ^r & iden | 1 | 3 | 25 | 543 |
The first three rows and the two with factorials are 2^(n*n),
2^(n*n - n), 2^(n*(n+1)/2), n^n, and n!. The others are the
sequences A006905 (transitive relations), A000110 (Bell numbers), A001035
(partial orders), and A003024 (acyclic digraphs) of the OEIS.
9. Worked examples
Each line is a test (AGENTS.md law 29). The universe is (A, B, C), and
the instance is
s = {A, B} t = {B, C} r = {(A,B), (B,C)} q = {(A,C)}
Expressions:
| Expression | Denotes |
|---|---|
none | {} |
univ | {A, B, C} |
iden | {(A,A), (B,B), (C,C)} |
s + t | {A, B, C} |
s & t | {B} |
s - t | {A} |
s -> t | {(A,B), (A,C), (B,B), (B,C)} |
s . r | {B, C} |
r . t | {A, B} |
r . r | {(A,C)} |
r . univ | {A, B} |
univ . r | {B, C} |
~r | {(B,A), (C,B)} |
^r | {(A,B), (A,C), (B,C)} |
*r | {(A,A), (A,B), (A,C), (B,B), (B,C), (C,C)} |
r ++ q | {(A,C), (B,C)} |
s ++ t | {A, B, C} |
t <: r | {(B,C)} |
r :> s | {(A,B)} |
{x: univ | some x.r} | {A, B} |
{x: s, y: x.r | y in t} | {(A,B), (B,C)} |
{x: s, y: t | x->y in r} | {(A,B), (B,C)} |
(some s - t) => s else t | {A, B} |
(no s) => s else t | {B, C} |
Formulas:
| Formula | Value |
|---|---|
r in s -> t | true |
s = t | false |
s + t = univ | true |
some s & t | true |
no s - univ | true |
one s | false |
one s & t | true |
lone s | false |
lone s - univ | true |
all x: s | some x.r | true |
all x: univ | some x.r | false |
all x: none | false | true |
some x: univ | no x.r | true |
some x: none | true | false |
one x: univ | no x.r | true |
lone x: univ | some x.r | false |
no x: univ | x in x.r | true |
one x: s, y: t | x->y in r | false |
some x: univ, y: x.r | no y.r | true |
r.r in r | false |
^r . ^r in ^r | true |
Errors, with s and r as above:
| Built | Code |
|---|---|
s + r | arity.mismatch |
s . t | arity.join |
~s | arity.not_binary |
r <: r | arity.not_a_set |
all x: r | some x | arity.not_a_set |
(s + r) . r | arity.mismatch, once |
(s + r) + (r <: r) | arity.mismatch and arity.not_a_set, once each |
Checked before evaluation (section 7), with x and y variables:
| Evaluated | Result |
|---|---|
x in s | logic.free_variable |
false and x in s | logic.free_variable |
all x: none | y in s | logic.free_variable |
all x: s, x: t | x in s | logic.rebound_variable |
all x: s | some x: t | x in s | logic.rebound_variable |
(all x: s | x in s) and (all x: t | x in t) | true |
all x: {x: s | x in t} | x in s | true |
10. Compatibility with Alloy and Kodkod
Where Elinvar’s logic differs from upstream, or depends on a fact about it
(AGENTS.md laws 3 and 5). Files are at the pinned commits (cargo x fetch).
| Topic | Upstream | Elinvar |
|---|---|---|
| which engine | Alloy 6.2.0 does not solve through the Kodkod repository. It uses the copy of Pardinus in its own tree, a fork of Kodkod (org.alloytools.pardinus.core, reached from A4Solution.java as PardinusSolver) | a claim about what Alloy answers is checked in that copy. The Kodkod repository is cited for the design the two share |
| expression operators | Kodkod has union, intersection, override, product, difference, join, transpose, closure, and reflexive closure (kodkod/ast/operator/ExprOperator.java), and no restriction operators. Alloy builds s <: a as a intersected with s -> univ -> ..., and a :> s as a intersected with ... -> univ -> s, for any arity of a (TranslateAlloyToKodkod.java, visit(ExprBinary), cases DOMAIN and RANGE) | the same nine with the same meaning, and domain and range restriction as operators of the core, with the meaning Alloy gives them |
| override | a tuple of the left operand is kept when the right has none in the same row, a row being the tuples that share a first atom (kodkod/engine/bool/BooleanMatrix.java, override) | the same (section 3) |
| quantifiers | Kodkod has all and some (kodkod/ast/operator/Quantifier.java). Alloy rewrites the others: no as all of the negated body; one and lone as the multiplicity of a comprehension when every declaration ranges over a set, and otherwise through all over two copies of the declarations (TranslateAlloyToKodkod.java, visit_qt) | all five are core, counting bindings as section 5 says, which is what both of Alloy’s forms count. The rewriting still matters to instance counts, through skolemization (CORPUS.md section 4) |
| multiplicity of an expression | no, lone, one, some (kodkod/ast/operator/Multiplicity.java) | the same four |
| integer atoms | Alloy gives every command an integer bitwidth of 4 unless told otherwise, and so 16 integer atoms in the universe, whether or not the model uses integers (ScopeComputer.java: shouldUseInts = true, then bitwidth = 4 and 1 << bitwidth atoms) | integers as section 16 has them, with integer atoms only where a model asks for them. univ, iden, and * therefore range over fewer atoms than Alloy’s in a model without integers. A corpus model whose answer depends on that is read with Alloy’s integer atoms (CORPUS.md section 4) |
| integer arithmetic | wraps around at the bitwidth unless the noOverflow option is on, which is off by default (A4Options.noOverflow); Kodkod’s integers are two’s complement circuits (kodkod/engine/bool/TwosComplementInt.java) | wraps around always (section 16); there is no option that rules out overflow |
| empty universe | Kodkod rejects one (kodkod/instance/Universe.java, both constructors) | rejected (universe.empty) |
| the same variable in two quantifiers | Kodkod allows one Variable in both non-enclosing and nested quantifiers, with the innermost binding shadowing the outer (kodkod/engine/fol2sat/Environment.java, extend and lookup; kodkod/ast/QuantifiedFormula.java and Decls.java do not forbid reuse) | allowed in non-enclosing quantifiers; rebinding where it is already bound is an error (section 5) |
| instances told apart | enumeration rules out the last instance with a clause over every primary variable, and skolem relations have primary variables (ExtendedSolver.java, nextNonTrivialSolution; Skolemizer.java adds each skolem relation to the bounds) | the same (DESIGN.md section 7.7), so two instances that differ only in a witness count as two on both sides |
11. Not yet specified
Each item is written here, with its tests, before its code (AGENTS.md law 1). The design for each is in DESIGN.md.
Phase 3 is specified in section 13.
Phase 4 is specified in section 14.
Phase 5 is specified in section 15.
Integers are specified in section 16.
12. Finding
Phase 2: how run and check find an instance with a SAT solver
(DESIGN.md section 7). Everything here is a function of its input, so the
same problem gives the same answer on every machine (AGENTS.md law 16).
12.1 Problems and verdicts
A problem is bounds and a formula with no free variables, checked as
section 7 checks it, against the bounds (logic.unbound_relation).
run Flooks for an instance within the bounds under whichFis true. The verdict isfound, with the instance, ornone.check Aunder rulesRlooks for an instance ofR and not A. The verdict iscounterexample, with the instance; or, when there is none,holdsifRalone has an instance andvacuousif it has none, found by a second solve ofRalone.- A solve that runs out of its budget gives
unknown, with the budget that ran out. If the second solve of acheckruns out, the verdict isunknownand records that no counterexample exists within the bounds.
12.2 Skolemization
A conjunction or disjunction of one formula is that formula. A quantifier
is skolemized when it is an existential reached from the root through
and, not, and the left side of a negated implies only, with
no universal quantifier above it: a some with an even number of not
above it, or an all or a no with an odd number, since no x | F is
all x | not F, as Alloy writes it before Kodkod sees it
(TranslateAlloyToKodkod.visit_qt at 59ba203). one and lone
are never skolemized.
Each declaration x: m e of a skolemized quantifier becomes a fresh
relation $x of x‘s arity ($x_2, $x_3, and so on when the name is
taken), in declaration order, bounded above by the upper
approximation of e and below by nothing. The upper approximation of an
expression is what it denotes when every relation holds its upper bound and
a skolem relation stands for an earlier declaration, except that a - b
is taken as a, a ++ b as a + b, a comprehension as the product of its
declarations’ approximations, and F => a else b as a + b. Every operator
then only grows with its operands, so no instance within the bounds gives
e an atom outside it. The quantifier is
replaced by m $x and $x in e and B, where m is the declaration’s
multiplicity, one for an atom and nothing for set, and e and the body
B have the earlier declarations’ variables replaced by their relations.
A declaration over sets or relations that skolemization does not remove is
an error (logic.higher_order): the solver grounds quantifiers over atoms
only. The skolem
relations are added to the bounds after the user’s, and are part of the
instance the solver returns. The referee drops them and evaluates the
formula as the user wrote it (section 12.7).
12.3 The circuit
A boolean value is the constant true, the constant false, a variable, or a
gate. A gate is an and of two or more distinct values, sorted by number,
an xor of two distinct positive values, or a maj (at least two of three
values), shared when asked for with the same inputs. not is a sign on a
value, and or is the not of the and of the nots. Building a gate
simplifies: an and with a false input is false, true inputs are dropped,
an input together with its not gives false, a repeated input is kept once,
an and of one input is that input, and an and of none is true; xor
and maj simplify constants, equal inputs, and complementary inputs, and
canonicalize signs so that xor(not a, b) = not xor(a, b) and
maj(not a, not b, not c) = not maj(a, b, c). An existing gate with the
same kind and inputs is returned unchanged.
Variables are numbered from 1, relation by relation in bounds order, and within a relation by tuple index, one for each tuple in the upper bound and not in the lower bound. These are the primary variables. Gates are numbered after them, in the order they are first built.
An expression of arity k becomes a table: for each tuple index, a boolean
value, false when absent. A relation’s table is true on its lower bound and
its variable on the rest of its upper bound. The operators of section 3
are computed entry by entry from their definitions, with or for “some
pair”, and for “both”, and not for “not in”; closure is computed as
T = A, then T = T + T . T repeated until T covers paths of length
n. A variable bound to atom a is the table true on a alone.
A quantifier is grounded over the atoms its declaration’s table does not
make false, in index order, first declaration outermost. Each binding gives
a guard, the and of its declarations’ entries, and the body’s value under
it. all is the and over bindings of guard implies body; some is the
or of guard and body; no is the not of some. lone over values
v1, ..., vk, each a binding’s guard and body, is a sequential counter,
as Kodkod’s BooleanMatrix.lone is: with p0 false and
pi = p(i-1) or vi, it is the and over i of not (vi and p(i-1)).
one is lone and pk. A multiplicity of an expression is the same over
its table’s entries. a in b is the and over a’s entries of
ai implies bi, and a = b is that both ways, entry by entry.
A node met again with the same values of its free variables gives the same value, without being computed again (R8).
12.4 Clauses
The root value is asserted. Each gate the root reaches has the
polarities it occurs in: the root occurs positively, an input of and or
maj occurs as the gate does (or the other way round when negated), and
the inputs of xor occur in both polarities. A gate g = and(x1, ..., xm)
that occurs positively gives the clauses (not g or xi) for each i, and
negatively (g or not x1 or ... or not xm). A gate g = xor(a, b) gives
(not g or a or b) and (not g or not a or not b) positively, and
(g or not a or b) and (g or a or not b) negatively. A gate
g = maj(a, b, c) gives (not g or a or b), (not g or a or c), and
(not g or b or c) positively, and (g or not a or not b),
(g or not a or not c), and (g or not b or not c) negatively. Gates are
encoded in number order. This is Plaisted and Greenbaum’s encoding, as
Kodkod’s Bool2CNFTranslator makes it at 6e80244. It has a model
exactly when the root does, with the same primary variables, and only
those are read. If the root is a constant, no clause is made: true is
satisfied by every assignment of the primary variables, false by none.
12.5 Symmetry breaking
Atoms a and b are interchangeable when neither is an integer atom
(section 16.4) and swapping them maps every lower and upper bound
to itself. This is an equivalence relation; its classes,
each listed in atom order, are the parts of the universe.
For each part and each pair of neighbouring atoms (a, b) in it, the
predicate compares two vectors: the primary variables whose tuple the swap
moves, and the variables of the tuples they are moved to. The primary
variables are taken relation by relation, in order of arity and then
bounds declaration order, and within a relation in number order. A pair of
entries (y, x) after the pair (x, y) is left out: it can only matter
once x and y are equal, as Kodkod’s atSameIndex has it. The predicate
asks that the first vector be no greater than the second in lexicographic
order, false before true, comparing at most 20 entries. The predicate is
on by default and can be turned off. With it on, instances that differ only
by a renaming of atoms may be left out; a count of instances is meant with
it off.
12.6 The next instance
After an instance, the next is found by adding one clause that rules out its values for all primary variables, skolem relations’ included. The order instances come in is the solver’s, which is deterministic.
12.7 The referee
Every instance the solver returns is checked before it is given out
(AGENTS.md law 13): the user’s relations are given their tuple sets from
the solver, the bounds must admit that instance, and the evaluator must
find the problem’s formula, as the user wrote it, true. A failure is a bug
in Elinvar and panics with a message naming the check. When the formula as
written cannot be evaluated because a declaration over sets or relations
ranges over more than 63 tuples (enumerate.too_large), the referee
evaluates the skolemized formula instead: its witnesses are relations of
the instance, so it is still checked against what the instance holds, but
by a formula the engine wrote.
12.8 The solver
The default solver is Elinvar’s own, conflict-driven with clause learning, decided by the user on 2026-11-28. It is deterministic: variable activity breaks ties by the lower variable number, the first value tried is false, restarts follow the Luby sequence, and nothing is random. A budget is a number of conflicts, a time limit, or both; only running out can depend on the time.
12.9 The model builder
Most models are not written as bounds. The model builder of the elinvar-engine
crate (re-exported by elinvar) declares sets and relations, and a command gives each set a scope; the
builder turns them into bounds and facts (R11).
- A top-level set gets its own atoms, named after it and numbered from 0:
Person0,Person1. Top-level sets are therefore disjoint. Under scopekits upper bound is itskatoms and its lower bound is empty; with an exact scope, the lower bound is allk. Aoneset has exactly one atom whatever the scope. - A subset of a set has the parent’s atoms as its upper bound, and the fact that it is inside the parent. Subsets declared as extending the same parent are disjoint from each other, and an abstract parent with extensions is their union.
- A relation over columns of sets has the product of the columns’ upper
bounds as its upper bound, and the fact that it is inside the product of
the columns. A field, a binary relation from a domain to a range, may have
a multiplicity
mofone,lone, orsome, which addsall x: domain | m x.f. - The universe is the atoms of the top-level sets in declaration order.
The builder’s
univis the union of the top-level sets, and itsidenisidenrestricted to it, because the logic’s ownunivalso holds atoms that a set under a smaller scope leaves out. - A command needs a scope for every top-level set that is not
one: there is no default in the Rust builder (DESIGN.md section 13, open item 7). - A set’s scope makes room for the subsets declared
onebelow it, as Alloy’sScopeComputer.computeLowerBounddoes; and an abstract top-level set without a scope of its own, whose extensions are allone, holds exactly those, asderive_abstract_scopedoes. - An ordering on a top-level set makes its scope exact and gives it two
relations,
firstandnext, bounded exactly: the set’s atoms in atom order,firstthe first of them andnexteach to the one after. This is the order Alloy fixes forutil/orderingwhatever symmetry breaking says (DESIGN.md section 7.5). - An ordering on a set that extends or is
inanother gives itfirstandnextbounded above by its top-level set’s atoms,firstalone andnextevery pair, and a fact that they are a total order of the set:one first,first in s,next in s -> s,no next.first, each atom ofswith at most one before and one after it,s in first.*next, andno ^next & iden. A set that extends another has an exact size in each command, its own scope if it has one and its top-level set’s otherwise, as Alloy 6.2.0 answers forutil/ordering[exactly elem](corpus/language/ordered_subsig.als). A setinanother is exact only as Pardinus makes it (SymmetryBreaker.breakTotalOrderatd3e7aea): when its upper bound lies inside one part of the universe (section 12.5’s parts, of the bounds without the orderings’ own relations, which Alloy does not fix in advance), the set is that whole upper bound, and the part is taken, so no later ordering’s set is made exact by it. Otherwise, as beside aoneextension of its parent, its size is free. Orderings are taken in the order of the names Alloy gives their relations,alias/Ord.Next(SymmetryBreaker.sort), a library module’s own ordering beingmodule/ord, and a top-level ordered set takes its part too (corpus/language/ordered_subsig_split.als,ordered_shared_a.als,ordered_shared_z.als). An ordering on a subset of a union of sets is one on a setinanother, over the atoms of the sets’ top-level sets: over two top-level sets its upper bound lies in two parts and its size is free (ordered_union_subset.als). The order is the solver’s to find, not fixed by atoms, because the set’s atoms are not known before solving. An ordering on a set that changes over time ismodel.not_a_set. - A set that extends another may have a scope too, as in Alloy
(
ScopeComputerandBoundsComputerat59ba203). When none of the extensions under an unordered top-level set changes over time and their exact sizes fit in the top-level set, eachoneorexactly kextension gets disjoint exact atoms from its top-level set, bottom-up, and sibling non-exact extensions exclude those atoms from their upper bounds, as Alloy’sBoundsComputerassigns them. Otherwise its command has the fact that it has at mostkatoms, or exactlyk, stated asBoundsComputer.sizestates it:no s or some v1, ..., vk: s | s = v1 + ... + vk, with thevidisjoint for exactlyk,lone sandone sfor 1, andno sfor 0. A scope of at least the atoms of the set’s upper bound adds nothing, as Alloy’sBoundsComputeradds nothing whenupper.size() <= n(BoundsComputer.javaat59ba203). The atoms of the extensions with an exact scope must fit in their top-level set, which grows to hold them; and an abstract top-level set without a scope of its own, each of whose extensions has a scope or isone, holds at most their sum; and of an abstract set with a scope, all of whose extensions but one have a scope or areone, the one left has the difference, or 0 (derive_abstract_scope). Int, the set of integer atoms (section 16), is a top-level set that holds, in each command, exactly one atom for each integer of the command’s bitwidth, named by it and from the least:-8to7at the default bitwidth of 4. A bitwidth above 16 in a model withIntis an error (model.bitwidth), sinceIntwould have2^watoms; the universe’s own limit is 32 (section 16.1).
| Code | When | Message carries |
|---|---|---|
model.bitwidth | a command asks for a bitwidth above 16 in a model with Int | the bitwidth |
model.no_scope | a command leaves a top-level set without a scope | the set |
model.not_a_set | a scope is given for something that is not a top-level set of the model, or an ordering for a set that changes over time | the expression |
model.not_changing | an action’s effect names something that is not a changing relation of the model | the action, the expression |
model.changing_after_action | a changing relation is declared after an action, whose frame then misses it | the relation |
model.diff_mismatch | two models compared with diff do not declare the same signatures and fields with the same arities and mutability | the mismatched relation |
model.trivial_holds | a check assertion holds from the bounds alone without using any rule of the model | the check |
model.vacuous_premise | an implication promise’s premise is never satisfied in any allowed case within the scope | the check |
model.premise_unknown | warning: an implication promise holds, but whether its premise is ever satisfied was not settled within the budget for that question (the command’s conflict budget, at most 50,000) | the check and the conflicts spent |
model.invalid_steps | a command asks for 0 steps; a trace needs at least 1 state | the command |
model.scope_too_large | a command asks for more than 4096 non-integer atoms in total, or its relations have more than 2^24 (16,777,216) possible tuples in all, each a solver variable | the requested atom or tuple count, and the relation that passed the limit |
13. Time
Phase 3 (DESIGN.md section 8, R19 to R22).
13.1 Changing relations and traces
A relation is fixed or changing; it is declared one or the other (R19).
A trace, over one universe, is an instance of the fixed relations, a list
of L states, L at least 1, each an instance of the changing relations,
and a loop target j with 0 <= j < L. It stands for the infinite
sequence of positions 0, 1, 2, ...: position p shows state p when
p < L, and otherwise state j + (p - j) mod (L - j). After the last
state comes state j again, for ever (R21).
A trace is within bounds when its fixed instance is, and every state gives each changing relation a tuple set between that relation’s bounds.
13.2 Temporal formulas
A formula holds at a position. Everything of sections 3 to 5 holds at a position as it does in that position’s state, with the fixed relations the same at every position. A formula is true of a trace when it holds at position 0.
| Written | Holds at p when |
|---|---|
e' (an expression) | denotes, at p, what e denotes at p + 1 |
after F | F holds at p + 1 |
always F | F holds at every q >= p |
eventually F | F holds at some q >= p |
F until G | G holds at some q >= p, and F at every r with p <= r < q |
F releases G | not (not F until not G) holds |
before F | p > 0 and F holds at p - 1 |
historically F | F holds at every q <= p |
once F | F holds at some q <= p |
F since G | G holds at some q <= p, and F at every r with q < r <= p |
F triggered G | not (not F since not G) holds |
13.3 Evaluating on a lasso
The past depth of a formula, or of an expression or integer expression
evaluated on a trace, is the greatest number of past operators
(before, historically, once, since, triggered) nested in one
another in it. With past depth d and period P = L - j, whether a
formula holds at a position p >= j + d * P depends only on
(p - j) mod P. So the evaluator works on the positions 0 to N - 1,
N = j + (d + 1) * P, with the next position of N - 1 being N - P. A
future operator at p walks forward from p until a position repeats; a
past operator walks back to 0. The evaluator checks a trace as it checks an
instance (section 7), relations being looked for in
the fixed instance and in every state.
| Code | When | Message carries |
|---|---|---|
trace.no_states | a trace with no states | |
trace.loop | a loop target that is not a state | the target, L |
trace.relations | the states do not all give tuple sets to the same changing relations, or a state gives one to a fixed relation | the relation |
13.4 Finding traces
A command with changing relations or temporal operators has a limit S
on steps, 10 unless the command says otherwise, as Alloy’s is
(ScopeComputer.java, maxtrace). For L from 1 to S:
- For
L = 1, the loop target is fixed to 0. - For
L > 1, the circuit allocatesLloop-target selector variables after the primary variables, constrained so that exactly one is true, and unrolls(past_depth + 1)copies of theLstates (pos = d * L + kfor copydin0..=past_depthand statekin0..L). Stepping past stateL - 1multiplexes on the selector variables to(min(d + 1, past_depth), j); stepping back at(d, k)withd > 0chooses(d - 1, L - 1)whenj = kand(d, k - 1)otherwise. One solve rules out every loop target of lengthLwhen unsatisfiable; when satisfiable, assumptions on the selector variables in order0toL - 1find the earliest loop target, and enumeration continues in the same order.
In both cases the first trace returned is the shortest, and of those the
one that loops back earliest. A command with no changing relation solves
only L = 1.
In the circuit (section 12.3), a changing relation has one table per
state, and its primary variables come block by block, state by state, at
its place in bounds order. The value of a formula is computed per
position, on the positions of section 13.3, with and for “every” and
or for “some” over the positions the definition visits.
Skolemization (section 12.2) stops below a temporal operator and below a prime: a skolem relation is fixed, and stands for a witness at position 0.
The verdicts of section 12.1 hold with “within the bounds” read as “within
the bounds and with at most S states”: holds says no counterexample
trace exists up to S states, and vacuous that no trace of the rules
does.
13.5 Actions and frames
The model builder declares changing relations and actions (R22). A
changing set, top-level or a subset, has its atoms as a fixed set does;
which of them it holds may change. A changing relation’s facts from its
declaration, being inside its parent or its columns and its multiplicity,
hold in every state. An action
has a name, parameters each ranging over a set, a guard, and effects on
changing relations: add(r, e) gives r' = r + e, remove(r, e) gives
r' = r - e, and set(r, e) gives r' = e. Effects on one relation
combine in the order written. Every changing relation the action does not
name stays as it was: r' = r. That is the frame.
That the action happens with arguments a1, ..., ak is the formula
guard and effects and frame with the parameters bound to them. A step is
one action happening with some arguments, or a step where every changing
relation stays the same. The builder adds the fact always (some step)
when the model has actions.
Each step of a trace found is labelled with the first action, in
declaration order, and the first arguments, in tuple order, that happen at
it, or with “nothing changed”. Step k is the one out of state k: to
state k + 1, or for the last state, back to the loop target. The
evaluator decides it, at position k with the parameters bound to the
arguments.
13.6 Worked examples
Each line is a test. The universe is (A), s is a changing set, and the
trace has three states looping to state 1: s is {}, {A}, {}, so the
positions show {}, {A}, {}, {A}, {}, and so on.
| Formula | Value |
|---|---|
some s | false |
after some s | true |
eventually some s | true |
always some s | false |
always eventually some s | true |
eventually always some s | false |
no s until some s | true |
some s releases no s | false |
once some s | false |
after once some s | true |
after after before some s | true |
eventually historically no s | true |
always (some s implies before no s) | true |
after (no s since some s) | true |
some s triggered no s | true |
s' = s | false |
always not (s' = s) | true |
14. Answers
Phase 4 (DESIGN.md section 9, R23 to R26, R30 to R33): what a command returns, as data and as text.
14.1 The result
A command of the model builder returns a result. Its JSON form is version
1 of the schema in docs/schema/result-v1.json, which cargo x generate
writes and cargo x verify checks is current. Its fields:
| Field | Holds |
|---|---|
elinvar | the schema version, 1 |
command | run or check |
name | the command’s name |
verdict | found, none, counterexample, holds, proved, vacuous, or unknown |
scope | for each top-level set, the most atoms searched; and steps, the most states, for a model with changing relations |
shrunk_to | for a counterexample, the scope it was shrunk to (section 14.3) |
fully_shrunk | whether shrinking finished within its budget |
instance | the instance, without changing relations |
trace | the trace: fixed, states, loop_to, and steps, one per state: the action and its arguments, and for each changing relation the tuples it gains and loses |
broken_at | for a counterexample to always P, to a block holding only always P, or to A implies always P, the first state where P fails |
broken_witness | optional; for a broken `always all x: S |
expect | optional; the command’s expect 0 or expect 1 annotation when present |
expect_met | optional; whether the verdict met expect (null when unknown) |
note | for unknown, which budget ran out and what is known |
errors | every error, each with code, message, fix, and place |
warnings | optional; non-fatal warnings about the model or command (such as wrapped integer literals or step predicates leaving changing relations unconstrained), each with code, message, fix, and place |
stats | primary variables, gates, and conflicts |
core | optional; present when --explain / report_explained is used on a holds or vacuous check: { used, unused }, the minimal subset of named rules that suffices to rule out counterexamples; or on a run with no instance: the minimal subset that, with the run’s constraint, allows no instance, or, when the rules alone allow none, the minimal subset of them that allows none, with a note saying so |
story | the text of section 14.2 |
A field with nothing to hold is null, or an empty list. Atoms, relations,
and tuples are named, never numbered.
The rules in core carry the names the model gives them. Through the
library a fact is the name given to fact_named. In model text it is
fact F, or fact n for the nth unnamed fact. A signature’s declaration
is sig S: its parent, its children being disjoint and, if it is abstract,
covering it, and its multiplicity. A field’s type and multiplicity are
field f, and the count a scope adds (section 12.9) is scope S. The
frame of a model’s actions is actions. A transition fact in used is
split into its step guards, each named step: guard.
14.2 Stories
The text of a result is made from the data, never the other way round. Its
first line is the command, the verdict, and the size: for example check NoCycle: COUNTEREXAMPLE with Employee: 2 when shrunk to those atoms, or
run Show: found in scope Employee: 3 when an unshrunk instance is found in
that scope. Then:
- An instance: each relation the user declared with its tuples, sets as
{A, B}and tuples asA -> B, in declaration order; then each witness of a skolemized quantifier aswitness p = Person0. - A trace:
start, with the fixed relations and the changing relations of state 0 that hold tuples; then one line per step,step k + 1for the step out of statek(DESIGN.md section 9.5 numbers them so), with its action and arguments, the tuples each changing relation gains and loses, and for the last, the state it loops back to. A model without actions, such as one read from text, names no action; a step that changes nothing saysnothing changes. broken at state k, as step k + 1 beginswhen the result hasbroken_at.- For
holds,proved,vacuous, andnone, the scope searched, and forvacuous, that the rules allow no case in it.provedstates that the promise holds for any number of steps within the scope by k-induction. - For
unknown(or when an inductive check fell back to bounded traces from a possibly unreachable state), the note. - For errors, one line per error: place, code, message, and fix.
14.3 Shrinking
A counterexample from the model builder is shrunk before it is returned (R25). Smaller means fewer states, then fewer atoms, then fewer tuples.
- States: the search already returns a shortest trace (section 13.4).
- Atoms: for each top-level set in declaration order whose scope is not
exact and not
one, the check is run again with that set’s scope one less, while a counterexample exists, down to 0. - Tuples: at the scope found, without symmetry breaking, and for the number of states and loop target of the counterexample, the solver’s first counterexample becomes the current one. Then each primary variable true in the current counterexample, in number order, is asked to be false, together with every one asked before and kept; when the solver finds a counterexample so, it becomes the current one and the variable stays false.
Each step’s counterexample is refereed. Shrinking has its own budget, of
conflicts over all its solves, 1,000,000 by default; when it runs out, the
smallest counterexample so far is returned and fully_shrunk is false.
14.4 In tests
assert_holds runs a check and returns if the verdict is holds.
Otherwise it panics, and the panic’s message is the story: a
counterexample, vacuous, unknown, or the errors (R26).
15. Model text
Phase 5 (DESIGN.md section 9.4, R34): the subset of Alloy 6 that elinvar-als
reads into a model of the builder (section 12.9). A construct outside it is
an error that names it, never a wrong answer (DESIGN.md section 9.4).
15.1 What is read
| Construct | Read as |
|---|---|
//, --, /* */ comments | nothing |
module | nothing |
sig A {}, abstract sig, one sig, lone sig, some sig | a top-level set; one a one set; lone and some add the fact lone A or some A |
sig B extends A, sig B in A | an extension or a subset |
sig A, B {} | one declaration per name |
var sig | a changing set |
enum E { a, b } | an abstract set with a one extension per name |
a field f: m e or f: e with arrows | a relation of the signature and the columns of e, each the top-level signature its column ranges over; and the fact, for each this of the signature, that this.f is inside e, with m (one by default for a set, lone, some, or set) and the multiplicities of e’s arrows. e may name the signature’s own fields, read as this.g, as in addr: names -> some Target |
| fields of one name in several signatures | each its own relation; x.f picks the one whose signature is the type of x’s last column, and a use whose type cannot tell is als.unsupported |
var field | a changing relation |
a defined field, g = e | a relation of the signature and the columns of e, with the fact, for each this, that this.g = e (isIn in TranslateAlloyToKodkod.java at 59ba203). As in any field, a field name in e is read on this, so f.@f is this.f.f, and f.f joins this.f with this.f (Alloy’s name resolution 1, CompModule.java at 59ba203). It cannot be var or disj, as in Alloy |
sig A { ... } { F } | the fact `all this: A |
fact, fact name, fact "name" | a fact; a string literal here, or as the name of an assertion, is a name |
String, and a string literal "abc" in an expression | String is a top-level set, and each literal of the file a set that extends it, named "abc" with its quotes, as Alloy names its atom. Each command makes the set of a literal it reads, in the facts, the fields, or its own formula and the predicates and functions that formula calls, exactly one atom, and the set of any other literal none; String is exactly the literals the command reads, or exactly N String if N is more, as Alloy’s ScopeComputer.compute gives it at 59ba203 (corpus/language/strings.als). A scope on String that is not exact, and a declaration sig String, are als.syntax, as in Alloy. The atoms past the literals are named String2 and on, where Alloy names them "String0" and on |
private before open, pred, fun, let, sig, or a field | nothing: in Alloy it hides the declaration from a module that opens this one (Vis in Alloy.cup at 59ba203), and a model’s own declarations are all visible to it |
a number written 12, 0x0F, 0x_0F, or 0b1_01 | its value, as Alloy.lex at 59ba203 reads it: hex digits come in pairs, _ is passed over after 0x and 0b, and digits followed by a letter or _ (1_000), or a value above 2^31 - 1, is als.syntax |
pred, fun, with parameters | inlined at each use: p[a, b], a.p[b], and p with no parameters |
predicates and functions of one name, pred A.p, pred B.p, fun f[x: A], fun f[x: B], including those of two modules, such as dom of util/relation and of util/ternary | overloads, as Alloy keeps them (CompModule.addFunc at 59ba203): a call is to the one with as many parameters as arguments; among several, the one where each argument has its parameter’s arity and shares a top-level set with it in every column. A call whose arguments fit none or more than one is als.arguments. A declaration of the model’s own hides a module’s of one name and number of parameters |
a macro, let m[a, b] { F }, let m[a, b] = e, let m { F }, or let m = e, at the top of a file | each call, m[x, y], x.m[y], x.m with one parameter, or m with none, replaced by the body with each parameter bound to its argument, the arguments read where the call is: a variable of the body never captures one of an argument’s, and a variable bound around a call hides a macro of its name. An argument that is a name stands for itself, so a predicate or function passed by name is applied by p[x] in the body, as util/time’s then and while do: it is put in place of its parameter, unless the body binds a name like it, when it is bound to a fresh name as other arguments are. Its parameters have no type, so an argument may be a formula. The macros of util/time are expanded in the file that opens it. A call with the wrong number of arguments is als.arguments, and a macro that calls itself is als.unsupported |
assert name { F }, assert "name" { F } | an assertion for check |
run, check, with a name, a predicate or assertion, or a block | a command |
for N, for N but k A, exactly j B, for k A, j B | scopes of top-level sets; a set the command does not name gets N, or 3 when there is no N, as in Alloy |
n steps, m..n steps | at most n states |
expect 0, expect 1 | the expected answer, kept for the corpus: 1 is a counterexample or an instance |
| operators | those of sections 3, 4, and 13, written as in Alloy, with ! for not, && and ||, => and <=>, !=, not in and !in, a[b] for b.a, and F => G else H for formulas and expressions |
let x = e | F, let x = e { F } | F with x replaced by e |
F ; G | F and after G (Alloy.cup at 59ba203): looser than every other operator, F ; G ; H being F ; (G ; H), and looser even than a quantifier’s or let’s | body, which stops at it: all x: e | F ; G is (all x: e | F) ; G, and G cannot name x. In a block, { F ; G H } is (F ; G) and H. The grammar leaves both to its conflict resolution; Alloy 6.2.0’s answers to corpus/language/sequence.als settle them |
disj[e1, e2, ...] | no (e1 & e2) and no ((e1 + e2) & e3) and so on, which says no two share a tuple, built as visit(ExprList) in TranslateAlloyToKodkod.java at 59ba203 builds it; fewer than two arguments is als.arguments. disjoint is a name like any other, as in Alloy 6.2.0, though Alloy.lex lists it as a keyword |
an arrow with multiplicities, A m->n B, in a field, a declaration, or on the right of in | the product, and what it says of the relation r it types: each tuple of A picks out n tuples of B in r, each tuple of B m of A, and an arrow inside A or B says the same of the part of r each tuple of the other side picks out, as in (Room -> lone Key) -> Time |
disj f, g: e among a signature’s fields | for each atom of the signature, f and g hold no tuple in common |
all disj x, y: e | F | x and y differ |
univ, iden, none | the builder’s univ and iden (section 12.9), and none |
open util/ordering[S], open util/ordering[S] as o | an ordering on the signature S, top-level or not, or a subset of a union of signatures (section 12.9), with Alloy’s first, last, next, prev, nexts, prevs, lt, gt, lte, gte, larger, smaller, max, and min (util/ordering.als at the pinned commit), called as o/next or, with no declaration of the name, as next. With several orderings open, next alone means the one whose set is the type of what it meets: the last column of the left side of a join, the first column of the other side of any other operator, the parameter’s signature for a call’s argument, and the first column of the argument of min [e] and the like |
a subset of a union of signatures, sig C in A + B { ... }, and a subset of it | a relation of arity 1 over the sets of A and B, with the fact C in A + B and its multiplicity; its fields range over the same sets. A signature that extends a subset signature is an error (als.syntax), as in Alloy (CompModule.java at 59ba203) |
a field over a union of signatures, f: set A + B | a relation whose column ranges over the top-level sets of A and B |
| a field named in several signatures | the one the type of what it meets picks out, on either side of a join or a restriction and under ^, *, and ~ |
open util/relation, open util/graph[S], open util/boolean, open util/ternary, open util/natural, open util/time, open util/sequence[E], open util/seqrel[E], open util/history[Tick], with or without as | their predicates, functions, and signatures, in Elinvar’s own statement of them (crates/elinvar-als/src/modules/), with Alloy’s names and parameters (plus Elinvar’s util/history[Tick] for timestamped append-only histories, which also opens util/ordering[Tick]); called as alias/name or name, a declaration of the model’s own winning over a module’s of one name and number of parameters. The ordering a module opens for itself (util/natural’s of Natural, util/sequence’s and util/seqrel’s of SeqIdx) is the module’s own, as in Alloy: an unqualified first or next in the model means the model’s ordering when it has one. A call of an ordering’s function is one when no declaration of the name takes as many arguments, so first beside util/sequence’s first[s] is the ordering’s |
open m [A, B] as a of the model’s own module m | the module’s signatures, fields, facts, predicates, functions, and assertions, each named a/name, with the module’s parameters read as A and B, and a module it opens as b named a/b; its commands are not the model’s. The file is found beside the opening one, as Alloy finds it: the opening file’s own module name says how deep it sits. A name used without its module means the one declaration that ends in /name; a field so named among several is chosen by type |
module m [A, B] heading the model itself | A and B are signatures, unless the model declares them |
a number, #e, sum x: e | n, int[e], int e, Int[n], and Int | the integers of section 16: Int is the builder’s set of integer atoms, made the first time a model uses an integer. As in Alloy, which casts the same way (TranslateAlloyToKodkod, toInt and toSet at 59ba203), a set where an integer belongs is the sum of its integer atoms, and an integer where a set belongs is its atom |
a < b, a > b, a =< b and a <= b, a >= b, each negated by ! or not | integer comparisons (section 16.3) |
a = b, a != b | integer comparison when both sides are integers, and set equality otherwise, an integer side cast to its atom. + and - are always union and difference, of integers too, as in Alloy (ExprBinary.java at 59ba203: “these are always relational operators now”): #a = #b + 1 compares the set Int[#a] with Int[#b] + Int[1] |
for 5 Int, for 5 int | a bitwidth of 5 for the command; 4 without one, as in Alloy |
the functions and predicates of util/integer, which Alloy opens in every module, so that open util/integer adds nothing: add, plus, sub, minus, mul, div, rem, negate, signum, larger, smaller, eq, gt, lt, gte, lte, zero, pos, neg, nonpos, nonneg, max, min, next, prev, prevs, nexts, and int2elem and elem2int, the element at a place in an order and the place of an element (also qualified as int/... or integer/...), called as f[a, b], a.f[b], or a.f | their meaning in util/integer.als at 59ba203, unless the model declares the name |
a << b, a >> b, a >>> b | the shifts of section 16.2, each side read as an integer; they bind looser than + and - and tighter than the comparisons, left to right, as ShiftExprB in Alloy.cup at 59ba203 has them |
sequences: seq T in fields (f: seq T, var f: seq T) and declarations, seq/Int, for N seq (default 4, capped by bitwidth), and the functions and predicates of util/sequniv: isSeq, elems, first, last, rest, butlast, isEmpty, hasDups, inds, lastIdx, afterLastIdx, idxOf, lastIdxOf, indsOf, add, setAt, insert, delete, append, subseq (also qualified as seq/..., and after open util/sequniv or open util/sequniv as a as sequniv/... or a/...) | a relation seq/Int -> lone T covering a contiguous prefix of seq/Int from 0, with each helper defined as in util/sequniv.als at 59ba203 |
a scope on a module’s signature, as 3 msg/Tick | the scope of that signature |
open util/graph[A] and open util/graph[B], a library module opened with two lists of arguments | two modules, as Alloy makes one for each list: each copy’s declarations are named alias/name. Two opens of util/ordering on one set are one ordering |
this/A | A |
@f in a signature fact | the field f itself, not this.f |
| a file without commands | Alloy’s default command, run {} named Default, with the warning als.default_command |
| (an option, off by default) | a set Int of exactly 16 atoms in every command, the integers Alloy puts in every universe (section 10), so that univ, iden, and * range over what they do in Alloy; the comparison with Alloy reads models so |
15.2 What is not read
The unbounded 1.. steps and a growing scope on a
signature (for 1..3 A, for 1..9:2 A, which Alloy grows from solve to
solve, carrying each instance into the next: execute_greedyCommand in
TranslateAlloyToKodkod.java at 59ba203), each an error of that command
alone, when it runs, while the file’s other commands run, open of a library module other than util/ordering, util/relation,
util/graph, util/boolean, util/ternary, util/natural, util/history,
util/time, util/sequence, util/seqrel, util/integer, and util/sequniv, or of a model’s own module whose file is
not found (model text given without a file, as over MCP, has none), two sequence modules (util/sequence and util/seqrel, or one of them with two arguments, which Alloy keeps apart as two modules with a SeqIdx each), a declaration
over sets or relations that skolemization cannot remove (an error of the
logic, logic.higher_order), a field whose columns cannot be told apart by signature, an overloaded field or an ordering’s function whose meaning the type
does not settle, scopes on signatures
declared in another (which Alloy refuses too: ScopeComputer.java at 59ba203), and functions, predicates,
and macros that call themselves. Each is
als.unsupported, with the construct and the line.
15.3 Errors
| Code | When | Message carries |
|---|---|---|
als.syntax | text that is not Alloy, or not this subset’s grammar | what was expected, what was found |
als.unknown_name | a name that is no signature, field, predicate, function, parameter, or variable in scope | the name |
als.unsupported | a construct of section 15.2 | the construct |
als.sort | a formula where an expression belongs, or the other way round | what was expected |
als.duplicate | two declarations of one name | the name |
als.arguments | a predicate or function called with the wrong number of arguments, or with arguments whose types fit none or more than one of its overloads | both numbers, or the number of overloads and of those that fit |
als.no_command | a command name the file does not have | the name |
eval.result | elinvar eval is given a result it cannot read as an instance or trace of the model | what is missing |
sql.skipped | elinvar import --strict found a SQL statement or constraint the importer does not read | the skipped SQL and reason |
sql.script | elinvar accepts is given a SQL DML script containing a statement or expression it cannot read | the line number and unsupported form |
sql.database | elinvar fuzz could not run the external database command given to --against or the database rejected the schema | the command and database error |
als.int_wrap | warning: an integer literal written in the model does not fit the command’s Int bitwidth and wraps | the literal, bitwidth, range, and wrapped value |
als.unframed_var | warning: a step predicate primes some var relation(s) while leaving another var relation unconstrained | the predicate and unconstrained relation names |
als.default_command | warning: the file has no command, so Alloy’s default, run {} named Default, was run | the default command |
als.empty_by_type | warning: a join or comparison combines expressions whose column types never overlap | the operator and the disjoint types |
Every error’s place is the file, line, and column in the model text. The
errors of the logic, such as arity.mismatch, carry the place of the text
that built the node.
16. Integers
Integers are bounded and wrap around, as Alloy’s are (REQUIREMENTS.md section 6 no longer leaves them out: decided with the user on 2026-11-28, DESIGN.md section 13).
16.1 Bitwidth and integer atoms
A universe has a bitwidth w, from 1 to 32, and gives some of its atoms an
integer each. A universe made from atom names alone has bitwidth 4, as
Kodkod’s default is, and no integer atoms. The integers of bitwidth w are
those from -2^(w-1) to 2^(w-1) - 1. Each integer atom’s integer is one
of them, and no two integer atoms have the same integer. A bitwidth outside
1 to 32 is an error (universe.bitwidth), and so is an integer atom whose
integer is out of range, a second atom for one integer, or a second integer
for one atom (universe.int).
To wrap a number is to keep the w low bits of its two’s complement and
read them back as a signed number: 8 wraps to -8 at bitwidth 4, and -9 to 7.
Every integer expression denotes a wrapped number.
16.2 Integer expressions
| Expression | Denotes |
|---|---|
k, a number | k wrapped |
#e | the number of tuples of e, wrapped: at bitwidth 4, #e of 8 tuples is -8 |
sum e, e a set | the sum of the integers of e’s integer atoms, wrapped; its other atoms add nothing |
a + b, a - b, a * b | the sum, difference, and product, wrapped |
a / b, a % b, b not 0 | the quotient rounded toward zero, and the remainder a - (a / b) * b, which has the sign of a, both wrapped: -7 / 2 is -3 and -7 % 2 is -1, and -8 / -1 is -8 at bitwidth 4 |
a / 0, a % 0 | a / 0 is -1 when a is positive, 1 when it is negative, and 0 when it is 0; a % 0 is a. This is what Kodkod’s division circuit gives (TwosComplementInt.nonRestoringDivision at 6e80244), worked out bit by bit at bitwidths 3, 4, and 5 for every pair, which also agree with the row above when b is not 0 |
a << b, a >> b, a >>> b | with m the number of bits of w - 1 (2 at bitwidth 4, 3 at bitwidth 5, 0 at bitwidth 1) and n the m low bits of b read as an unsigned number: a << b is a * 2^n wrapped; a >> b is a / 2^n rounded down, keeping the sign; a >>> b is the w bits of a read as an unsigned number, divided by 2^n and rounded down, then wrapped. When n is at least w, which happens only when w is not a power of two, a << b and a >>> b are 0, and a >> b is -1 when a is negative and 0 otherwise. At bitwidth 4: 3 << 2 is -4, -8 >> 1 is -4, -8 >>> 1 is 4, 1 << 4 is 1 (n is 0), and 1 << -1 is -8 (n is 3); at bitwidth 5, 1 << 5 is 0 and 1 << 8 is 1. This is what Pardinus’s shifters give (TwosComplementInt.shl and shr at d3e7aea, which Alloy 6.2.0 runs; Kodkod’s at 6e80244 use every bit of b), and Alloy 6.2.0’s answers to corpus/language/shifts.als agree; Alloy’s >> is sha and >>> is shr (ExprBinary.Op and TranslateAlloyToKodkod.visit(ExprBinary) at 59ba203) |
-a | 0 - a, wrapped |
F => a else b | a where F is true, b where it is false |
sum x1: e1, ..., xm: em | n, and sum disj x, y: e | n, which adds n only where the variables differ (ExprQt.desugar at 59ba203) | the sum of n over the bindings of the declarations, each of one atom (section 5), wrapped; 0 when there are none |
A sum is wrapped once, at the end, which is the same as wrapping each
addition. sum e of an expression whose arity is not 1 is ill-formed
(arity.not_a_set), and so is a declaration of sum x: ... over sets or
relations (logic.higher_order).
16.3 Comparisons and the set of an integer
a = b, a < b, a =< b, a > b, and a >= b compare the values of two
integer expressions as signed numbers. Int[n] is an expression of arity
1: the integer atom whose integer is the value of n, or the empty set
when no atom has it.
16.4 Integers in the circuit
An integer expression becomes w boolean values, its bits in two’s
complement, the least significant first (section 12.3). Every operation
keeps only w bits, which wraps. Building them uses the circuit’s xor
and maj gates (section 12.3) and ite(c, x, y), which is
(c and x) or (not c and y).
- A number’s bits are constants.
a + badds bit by bit from bit 0 with a carry, first false: bitiisxor(xor(ai, bi), ci)and the next carrymaj(ai, bi, ci).a - bis the same withnot biand a first carry of true.-ais0 - a.a * bstarts from 0 and, for each bitiofbfrom 0, adds the number whose bitjisbi and a(j-i)forj >= iand false below.a / banda % bdivide the magnitudes. Withsthe sign bit ofa,tthat ofb,|a|isite(s, -a, a)onw + 1bits, so that2^(w-1)fits, and the same for|b|. Long division from the top bit of|a|down gives the magnitudesqandr: the remainder so far, shifted left with the next bit of|a|in, is compared with|b|, and where it is not less,|b|is subtracted and the quotient bit is true. Thena / bisite(xor(s, t), -q, q)anda % bisite(s, -r, r), both on theirwlow bits; and where every bit ofbis false,a / bis -1, 1, or 0 by the sign ofa, anda % bisa.a << b,a >>> b, anda >> bshift in stages, as Pardinus’s barrel shifter does: starting froma, for each bitiofbfrom 0 tom - 1(section 16.2), the value becomesite(bi, shifted, value), whereshiftedmoves every bit by2^i: for<<bitjtakes bitj - 2^i, false below; for>>>bitjtakes bitj + 2^i, false above; for>>the same with the sign bit ofaabove.#esums the entries ofe’s table, in index order, with a balanced binary tree of adders (as Kodkod’sBooleanFactory.sumdoes), each subtree wide enough for its count up towbits, zero-extended tow.sum esums, in a balanced binary tree over integer atoms in index order,iteof each atom’s entry with its integer and 0.sum x: e | nsums, in a balanced binary tree over bindings as quantifiers ground them,iteof each binding’s guard withnunder it and 0.F => a else bisitebit by bit.a = bis theandofnot xor(ai, bi)over the bits.a < bis true where the sign bits differ anda’s is true, or where they agree andais less as an unsigned number, which is decided at the highest bit where they differ.a =< bisa < b or a = b, and>and>=swap the operands.Int[n]’s entry for an integer atom is whethernequals its integer; for every other atom, false.
Integer atoms are told apart by their integers, so no two of them are
interchangeable in symmetry breaking (section 12.5), and none of them is
interchangeable with an atom that is not an integer. The upper
approximation of Int[n] in skolemization is univ, which holds every
integer atom: no relation holds just them.
Elinvar and SQL
Status: describes what is built, 2026-12-02. Covers reading a SQL schema
into a model and the verbs that work on SQL: import, accepts, fuzz,
audit, discover, and ci.
Elinvar reads the rules of a SQL database schema (keys, foreign keys,
checks, unique indexes, triggers) and writes an Alloy 6 model in Elinvar’s
subset (LOGIC.md section 15). The other verbs check
that model against scripts, a real database, a data dump, or candidate
invariants. The importer is in crates/elinvar-als/src/sql.rs; the verbs
are in the cli module of crates/elinvar. This file says what they do now. The command
line in general is DESIGN.md section 9.3,
and results as data are DESIGN.md section 9.5.
Contents: 1 Input · 2 What is read · 3 What is not read · 4 The generated model · 5 SQL in the other verbs · 6 import · 7 accepts · 8 fuzz · 9 audit · 10 discover · 11 ci · 12 Codes
1. Input
1.1 Files and directories
A schema is a .sql file or a directory. A directory is read as a list of
migrations: its regular files whose extension is sql, in any case, are
sorted by file name in byte order and joined, each preceded by a line
-- migration: NAME and followed by an empty line. A directory with no
such file is cli.input. A place in a result or a message, in JSON and in
text, names the migration file and the line in it, and so do the
comments of a generated model and the reasons in them.
--with FILE, repeatable, adds a sidecar. A sidecar whose name ends in
.sql is appended to the schema text, so it can add views and named
queries. Any other sidecar is Alloy text appended to the generated model,
so it can add promises (assert and check) and predicates. When an Alloy
sidecar contains a run or check command, the generated run Show
command is left out.
1.2 Lexing
Statements end at ;, except inside a trigger’s BEGIN ... END.
Comments are -- ... to the end of the line and /* ... */. A line that
starts with \ (a psql meta-command written by pg_dump) is passed over.
Strings are single-quoted, with '' for a quote. Identifiers may be quoted
with ", backquotes, or [ ]. Keywords are read in any case. Names are
compared without regard to case; a schema qualifier (public.users) is
dropped.
An unterminated string, or an integer that does not fit in 64 bits, is
als.syntax, and nothing is imported. So is a schema with no
CREATE TABLE.
2. What is read
2.1 Statements
| Statement | Read as |
|---|---|
CREATE [OR REPLACE] [TEMP|TEMPORARY] TABLE [IF NOT EXISTS] t (...) | a table (section 2.2, section 2.3); options after the closing parenthesis are passed over |
CREATE TYPE t AS ENUM ('a', ...) | a closed set of values for columns of type t |
CREATE DOMAIN d [AS] base_type [NOT NULL] [DEFAULT literal] [CHECK (expr)] | a reusable column type whose base kind, NOT NULL, literal DEFAULT, and CHECK constraints (with VALUE bound to the column) are inherited by columns of type d |
CREATE UNIQUE INDEX n ON t (cols) [WHERE cond] | a uniqueness rule, partial when it has WHERE (section 4.4) |
CREATE VIEW v [(cols)] AS SELECT ... | a function of the state (section 4.5); a later view of the same name replaces an earlier one |
-- name: q (or query:) on the line before a top-level SELECT | a named query, read like a view |
CREATE TRIGGER ... | with --temporal, a guard or an action on a step (section 4.7) |
ALTER TABLE | changes the table read so far (section 2.4) |
DROP TABLE, DROP INDEX, DROP TRIGGER, DROP VIEW | removes what was read so far under that name; a trigger the static shape skipped leaves the skipped list |
The rules a schema ends with are those left after every statement has been applied in order. A migrations directory therefore gives the schema of its last migration.
2.2 Columns
| Column type | Kind |
|---|---|
INT, INTEGER, INT2, INT4, INT8, BIGINT, SMALLINT, TINYINT, SERIAL, BIGSERIAL, SMALLSERIAL, NUMERIC, DECIMAL, REAL, DOUBLE [PRECISION] | integer |
TIMESTAMP, TIMESTAMPTZ, DATETIME, DATE, TIME, TIMETZ | time |
BOOL, BOOLEAN | boolean |
the name of a CREATE TYPE ... AS ENUM | closed set of its values |
the name of a CREATE DOMAIN | inherits the domain’s base kind, NOT NULL, literal DEFAULT, and CHECK constraints |
any other type (TEXT, VARCHAR(n), CHARACTER VARYING, unknown names) | text |
Lengths (n), array brackets, schema qualifiers, and WITH/WITHOUT TIME ZONE after a type are passed over. Columns of NUMERIC, DECIMAL,
REAL, and DOUBLE hold integers in the model.
| Column clause | Read as |
|---|---|
NOT NULL | the field has exactly one value |
NULL, or no clause | the field has at most one value |
PRIMARY KEY [AUTOINCREMENT] | not null and unique |
UNIQUE | unique among rows that have a value |
REFERENCES u [(c)] [ON DELETE action] | a foreign key (section 2.3) |
CHECK (expr) | a check on the row (section 2.5) |
DEFAULT literal | the value accepts, fuzz, and audit give a column an INSERT leaves out; the model itself does not use it |
GENERATED {ALWAYS|BY DEFAULT} AS IDENTITY [...] | marks the column NOT NULL and passes over sequence options |
GENERATED ALWAYS AS (expr) [STORED|VIRTUAL] | when expr is supported (section 2.5), read as a row check col IS (expr); otherwise skipped |
CONSTRAINT name | names the constraint, so ALTER TABLE ... DROP CONSTRAINT can remove it |
COLLATE x, STORAGE x, COMPRESSION x, ASC, DESC, DEFERRABLE, INITIALLY DEFERRED, INITIALLY IMMEDIATE | passed over |
2.3 Table constraints
[CONSTRAINT name] may precede each.
| Constraint | Read as |
|---|---|
PRIMARY KEY (c1, ...) | each column not null; the columns together unique |
UNIQUE (c1, ...) | the columns together unique among rows where all of them have values |
FOREIGN KEY (c1, ...) REFERENCES u [(d1, ...)] [ON DELETE action] | a foreign key; with no target columns, the primary key of u when it has as many columns |
CHECK (expr) | a check on the row |
A foreign key from one column becomes the type of the field: the field holds a row of the target table, not the target’s key value. A foreign key from several columns becomes a fact (section 4.4).
The ON DELETE actions read are CASCADE, SET NULL, RESTRICT, and
NO ACTION; the last two, and no action at all, refuse the delete of a
referenced row. Their effect is on the delete step
(section 4.6).
2.4 Changes to tables
ALTER TABLE [IF EXISTS] [ONLY] t is read with these clauses:
| Clause | Effect |
|---|---|
ADD [CONSTRAINT n] PRIMARY KEY / UNIQUE / FOREIGN KEY / CHECK | adds the constraint |
ADD [COLUMN] def | adds the column |
RENAME TO u | renames the table, and the foreign keys, indexes, and triggers that name it |
RENAME [COLUMN] a TO b | renames the column in the table’s own keys, foreign keys, checks, and indexes |
DROP CONSTRAINT n | removes the named check, foreign key, unique constraint, or primary key |
DROP [COLUMN] c | removes the column and every key, foreign key, check, and unique index that uses it |
ALTER [COLUMN] c SET NOT NULL, DROP NOT NULL | changes whether the column may be null |
ALTER [COLUMN] c SET DEFAULT literal, DROP DEFAULT | changes the default |
OWNER TO, VALIDATE, ENABLE, DISABLE, CLUSTER, REPLICA, other SET | ignored |
2.5 Expressions
Checks, partial-index filters, trigger conditions, and views use one expression language:
AND,OR,NOT, parentheses, andCASE [x] WHEN ... THEN ... [ELSE ...] END;- comparisons
=,!=,<>,<,<=,>,>=, andIS [NOT] x; x IS [NOT] NULL,x [NOT] IN (literals),x [NOT] IN (SELECT ...),x [NOT] BETWEEN lo AND hi,EXISTS (SELECT ...), and a scalar subquery;+and-of a literal,COALESCEandIFNULL;- text shapes:
GLOB,LIKE,length,char_length,trim,lower,upper,substr, compared with a literal; - SQLite dates:
strftime(format, x [, shift])anddate(...); - query parameters
:name,$name,$1,?1,?(in named queries); - literals: integers, strings,
TRUE,FALSE,NULL; Postgres casts::typeare passed over.
Integer literals must lie in -32768..32767, the largest bitwidth Elinvar has (LOGIC.md section 16). A rule that uses a larger one is not read.
3. What is not read
Every statement falls into one of three groups.
- Read: carried into the model (section 2).
- Ignored: a statement that holds no rule, so leaving it out loses
nothing. These are
CREATE INDEX(not unique),CREATE SEQUENCE,CREATE SCHEMA,CREATE EXTENSION,ALTER SEQUENCE,ALTER TYPE,ALTER SCHEMA,ALTER VIEW,ALTER FUNCTION,ALTER DATABASE, otherDROPforms,PRAGMA,BEGIN,COMMIT,END,ANALYZE,VACUUM,COMMENT,SET,GRANT,REVOKE, andSELECT set_config(...). - Skipped: a statement or clause that may hold a rule the model then lacks.
The import result lists ignored statements under ignored and skipped
ones under skipped, each with its place, its SQL text, and a reason. The
generated model carries each skipped item as a comment
-- not read: FILE:LINE: SQL -- reason.
Skipped items include, with the reasons the importer gives:
| What | Reason |
|---|---|
a statement of no known form (CREATE FUNCTION, INSERT) | statement is not read by SQL import |
CREATE TYPE that is not AS ENUM | unsupported CREATE TYPE definition (only AS ENUM is read) |
| a check, filter, or condition outside section 2.5 | unsupported CHECK expression (stopped at FILE:LINE:COL near TOKEN) and similar |
| a rule with an integer outside -32768..32767 | integer literal N exceeds Elinvar's 16-bit Int range (-32768..32767) |
GENERATED ... on a column with an unsupported expression | GENERATED column expression is not read |
a DEFAULT that is not a literal (now()), but for nextval(...) on a primary key | DEFAULT that is not a literal is not read: ... |
any other column clause, such as SQLite’s ON CONFLICT REPLACE | column clause is not read |
EXCLUDE USING ... | EXCLUDE constraint is not read |
ON DELETE SET DEFAULT, read as refusing the delete | ON DELETE SET DEFAULT is not read: ... |
| a foreign key to a table not in the schema, or to columns that cannot be found | referenced table X is not in the schema, and similar |
| a composite foreign key between columns of different kinds | composite FOREIGN KEY links columns of incompatible types |
a view or named query with GROUP BY, HAVING, ORDER BY, LIMIT (other than LIMIT 1 on a constant), outer joins, or aggregates | unsupported SELECT query in CREATE VIEW, unsupported named SELECT query |
ALTER TABLE and ALTER COLUMN clauses not in section 2.4 | unsupported ALTER TABLE clause, unsupported ALTER COLUMN clause |
CREATE TRIGGER without --temporal | triggers are not read in static mode (use --temporal) |
| a trigger outside section 4.7 | the reason names the part not read |
import --strict turns every skipped item into an error sql.skipped
(section 6). The other verbs report how many rules were not
read as unread_rules in their result, and say in their text that the
verdict does not cover them.
4. The generated model
4.1 Two shapes
Without --temporal, the model is static: each table is a signature,
each row an atom, and an instance is one state of the database.
With --temporal, the model is a model of time
(LOGIC.md section 13, DESIGN.md section 8):
the rows of each table change from state to state by insert, update, and
delete steps, and triggers constrain or extend the steps.
Every model starts with -- Generated by Elinvar from SQL DDL, then a
comment for each table or trigger the slice left out
(section 4.10). It ends with the skipped items as comments
and a command:
-- N Int fits every number in the schema (min..max)
run Show {} for 3 [but 4 steps] [, N Int] [, k S]
N is the smallest bitwidth from 4 to 16 that holds every integer literal
the model uses; the comment and N Int appear when the model uses Int.
4 steps appears in the temporal shape. A text signature with three or
more named values gets a scope of one more than their number.
4.2 Tables and columns
A table t becomes, in the static shape:
sig t {
c: one K, -- NOT NULL or PRIMARY KEY
d: lone K -- nullable
} {
...checks...
}
In the temporal shape:
sig t_row {}
var sig t in t_row { var c: one K, var d: lone K }
var sig t_retired in t_row {}
t_row holds every atom that may ever be a row of t. t holds the rows
present in a state, and t_retired the rows that have been deleted.
fact t_no_row_reuse says no atom is in both, so a deleted row’s atom is
never inserted again. fact t_domain says atoms not in t have no column
values.
--only-ruled leaves out every column no rule mentions: not in a key, a
foreign key (at either end), a check, a unique index, a trigger, or a view.
4.3 Column kinds
The type K of a column’s field is chosen from how the schema uses the
column. Columns that a rule compares with each other (in a check, a
composite foreign key, an index filter, a trigger, a trigger’s insert, or a
view) are grouped, and a group gets one type. The first case that applies
decides:
| Case | Type |
|---|---|
| a single-column foreign key | the target table’s signature (t_row in the temporal shape) |
a group of integer, time, or text columns compared by <, <=, >, >=, not with integer literals, with no fixed set of values | an ordered signature t_c_ord, or time_ord or date_ord for a group of several columns, with open util/ordering[S] as ord_S |
| an integer group, not a key, used without arithmetic, compared with a literal outside -32..31 and with at most 32 distinct cut points | an enumeration of regions enum t_c_int_enum { t_c_lt_N, t_c_eq_N, t_c_btw_N_M, t_c_gt_N }, a negative N written mN |
| a group of several closed-set columns, or of text columns | a shared enumeration of the union of their values, or a shared signature t_c_val |
a text column with a check c IN ('a', ...) at the top level, or a Postgres enum type | enum t_c_enum { t_c_a, ... } |
| an integer column | Int |
| a boolean column | enum SqlBool { SqlTrue, SqlFalse } |
| a text or time column | sig t_c_val {}, with one sig t_c_LIT extends t_c_val {} for each string literal a rule compares it with |
An enumeration from a CHECK ... IN keeps the check as a rule as well. A
text check that names a shape (GLOB, LIKE, length, and the others in
section 2.5) becomes a subset signature
sig t_c_chk_N in t_c_val {} for the values that pass it; the import
result’s sample_values gives a real value for each such subset, for
fuzz and tests --sql to write. Columns used with strftime or date
share an ordered signature of dates, with functions SqlDateFn and
SqlOrdFn for formatting and for shifting by a constant.
4.4 Rules
A check is read with SQL’s three-valued logic: a row is refused only when
the check is FALSE, and a NULL that makes it UNKNOWN lets the row through.
The formula is therefore not of “the check is FALSE”. In the static
shape checks sit in the signature’s fact block; in the temporal shape they
are fact t_checks { always { all this: t | ... } }.
| Rule | Fact |
|---|---|
unique column c | fact t_unique_c { all disj a, b: t | a.c != b.c }, with some a.c implies before the inequality when c is nullable |
| unique columns, or a composite primary key | fact t_unique_N { no disj a, b: t | a.c1 = b.c1 and ... }, where a nullable column adds some a.c and |
CREATE UNIQUE INDEX n ... [WHERE f] | fact t_uniq_n { no disj a, b: t | f(a) and f(b) and ... }; a row is covered when f is TRUE for it; ifnull(c, lit) or coalesce(c, lit) in the column list makes NULL equal to lit |
composite foreign key to u | fact t_fk_u_N { all x: t | (some x.c1 and ...) implies (some r: u | r.d1 = x.c1 and ...) } |
In the temporal shape every rule is wrapped in always, so a step that
would break one is not a step of the model.
4.5 Views and named queries
A view or named query v becomes fun v: set (K1 -> K2 ...), the set of
tuples its SELECT gives in a state, under set semantics (UNION ALL is
UNION). Supported are a projection of expressions or *, FROM with
,, JOIN, INNER JOIN, and CROSS JOIN with ON, WHERE,
DISTINCT, UNION, INTERSECT, EXCEPT, and LIMIT 1 on a constant
projection. A projected column takes its name from an alias or, in a
union, from the first arm. A named query’s parameters become the
function’s arguments: -- name: shares_of before
SELECT s.id FROM shares s WHERE s.account_id = :acct becomes
fun shares_of[acct: accounts_row]: set shares_row.
A promise in a sidecar can use a view by name. Views are also what
diff --of compares (DESIGN.md section 9.3).
4.6 Steps
In the temporal shape each table t has these predicates, on a row atom
r:
| Predicate | Meaning |
|---|---|
insert_t[r] | r is in neither t nor t_retired; t' = t + r; the new row’s columns are any values the rules allow; every other row and table stays the same |
update_t[r] | r is in t; any column of r may change; every other row and table stays the same |
delete_t[r] | r moves from t to t_retired, with the effect of each foreign key into t |
same_t | t, t_retired, and every column of t stay the same |
nothing | every table stays the same |
The effect of a foreign key from s into t on delete_t[r]:
RESTRICT, NO ACTION, or no action add the guard
no x: s | x.fk = r; CASCADE deletes the rows of s that reference r
in the same step; SET NULL clears their reference. A CASCADE reaches
every depth, as SQLite’s and Postgres’s do: the rows of s it deletes are
a set D_s, and a foreign key from u into s acts on D_s as one into
t acts on r (x.fk in D_s in place of x.fk = r). The sets are
built parents first. When the CASCADE keys reached from t form a cycle,
or a table’s CASCADE key refers to itself, only the rows that reference
r directly are reached, and a delete the cycle would carry further is
refused.
fact trace { always (nothing or (some r: t_row | insert_t[r]) or ...) }
makes every step one of these. A trigger’s guard is a conjunct of its
step (section 4.7).
4.7 Triggers
With --temporal, a trigger is read when it has this form:
CREATE TRIGGER name {BEFORE | AFTER} {INSERT | UPDATE [OF c1, ...] | DELETE}
ON t [FOR EACH ROW] [WHEN cond]
BEGIN
SELECT RAISE({ABORT | ROLLBACK | FAIL}, 'message') [FROM ...] [WHERE cond];
END;
or with a body of one INSERT INTO u [(cols)] VALUES (...). In
conditions NEW.c is the column after the step, (r.c)', and OLD.c the
column before, r.c. A subquery reads the state before the step in a
BEFORE trigger and the state after it in an AFTER trigger.
A RAISE trigger becomes a predicate name[r] that holds when the
trigger does not fire: not (WHEN and WHERE). It is a conjunct of the
step for its event. An UPDATE OF trigger fires when a listed column
changes value. A condition that is an OR at the top is split into
predicates name_branch_N, one per disjunct, so a refusal names the
branch.
An INSERT trigger makes its step, when the trigger fires, also insert a
fresh row of u: some w: u_row - u - u_retired | ..., with the listed
columns given the listed values, columns left out NULL when nullable and
unconstrained otherwise. When it does not fire, u stays the same. A
trigger whose target table the step already changes is skipped with the
reason table X is already modified in this step. A row a trigger
inserts does not fire further triggers.
Not read, each with a reason: INSTEAD OF triggers, RAISE(IGNORE),
bodies with more than one statement, EXECUTE FUNCTION and other bodies,
and triggers on tables not in the schema.
4.8 Initial states
Static models have no initial state. A temporal import starts from any
state the rules allow (--from-any, the default for import).
--from-empty adds
fact StartEmpty { no t and no t_retired and ... }
so every state is reached by steps from empty tables.
4.9 Names
SQL names become Alloy names by these rules, in order:
- Every character that is not an ASCII letter, digit, or
_becomes_; a name that starts with a digit gets a leading_. Case is kept. - A name that is an Alloy keyword gets the suffix
_sql. The keywords areabstract after all always and as assert before but check disj else enum eventually exactly expect extends fact for fun historically iden iff implies in int Int let lone module no none not once one open or pred releases run seq set sig since some steps String sum this triggered univ until var. - A column named like a variable the generated formulas bind (
a,b,d,r,w,x, andq,v, orpfollowed by digits), or like a table, gets_sql. - A name already taken gets
_2,_3, and so on.
Enumeration values are prefixed with table and column (orders_status_open
becomes orders_status_open_sql, as open is a keyword). The import
keeps the map from SQL names to Alloy names, and accepts, fuzz, and
audit use it, so their scripts and reports use SQL names.
4.10 Slicing
--tables A,B imports only some tables, like the slicing of
DESIGN.md section 7.9. The slice is the named
tables, or for a named view the tables it reads, closed under foreign
keys to their targets; in the temporal shape it also takes in the tables
the kept tables’ triggers read or write. A name that is neither a table
nor a view is als.unknown_name.
--with-referencing also adds, until nothing changes, every table with a
foreign key into the slice. Without it, those tables are listed in
outside_referencing_tables and in a model comment, since their foreign
keys could refuse a delete the slice allows. A trigger on a kept table that
writes outside the slice, or a trigger on a left-out table, is dropped and
listed in dropped_triggers as NAME (on T, writes outside slice) or
NAME (on dropped table T).
5. SQL in the other verbs
check, run, tests, eval, and diff take a .sql file or a
migrations directory wherever they take a model, and import it first.
The import is temporal when the schema creates a trigger (CREATE, then
TRIGGER within the next four words), or when an Alloy sidecar has a
temporal operator (always, after, until, …), steps, induction,
a prime, or a call insert_t[...], update_...[...], or delete_...[...]
of a step predicate; and static otherwise. Words inside comments and quoted
strings do not count. For check and run, a temporal import starts from empty
tables unless --from-any is given. The model’s bitwidth is the one of
section 4.1, unless the command sets one.
6. import
elinvar import FILE|DIR [--with FILE] [--json] [--strict]
[--temporal [--from-empty | --from-any]] [--tables A,B [--with-referencing]]
[--only-ruled]
Prints the generated model (section 4) on
standard output. When anything was skipped, ignored, left out by the
slice, or dropped, a one-line note on standard error says how many:
elinvar import: skipped N rule(s), M non-rule statement(s) ignored; slice left out referencing table(s): ...; slice dropped K trigger(s) (see comments or --json).
--from-empty and --from-any need --temporal, and only one may be
given. --with-referencing needs --tables. --strict, --temporal, and
--only-ruled are flags of import only. A flag misused is cli.usage.
With --strict, any skipped item makes the import fail: one error
sql.skipped per item, with its place, the message
not read: SQL (reason), and exit status 3. Ignored statements do not
fail it.
--json prints, per elinvar explain schema:import:
| Key | Holds |
|---|---|
elinvar | 1 |
tables | the SQL names of the imported tables |
views | the names of views and named queries, when there are any |
skipped, ignored | each item’s place, sql, and reason |
outside_referencing_tables | tables outside the slice with a foreign key into it |
dropped_triggers | triggers the slice dropped |
sample_values | a real value for each text-shape subset (section 4.3) |
model | the model text |
Errors give { elinvar, command: "import", errors, story }.
Exit status: 0 imported, 3 errors (including --strict with skipped
items).
7. accepts
elinvar accepts FILE TRACE [--with FILE] [--tables A,B [--with-referencing]] [--json]
Says whether the schema allows a script of changes, and whether every
check promise in a sidecar holds along it. FILE may also be an Alloy
model, which is the general form of this verb
(DESIGN.md section 9.3); this section is
about a .sql FILE, imported temporal and from any state.
TRACE is a result JSON when its first non-blank character is {
(unreadable JSON is eval.result), and a SQL script otherwise.
7.1 Scripts
The script is split at ; outside strings, with -- comments removed.
Each statement is one of:
INSERT INTO t [(cols)] VALUES (v, ...)with one row; without a column list the values follow the table’s column order;UPDATE t SET c = e [, ...] [WHERE w], whereeis a literal, a column, or+,-,*of those, with parentheses;DELETE FROM t [WHERE w].
w is an AND of c op literal, with op one of =, !=, <>, <,
<=, >, >=, and c IS [NOT] NULL. Values are NULL, TRUE,
FALSE, 'text', x'hex', and integers. Anything else, among it
INSERT OR ..., INSERT ... SELECT, several rows in one VALUES,
WHERE c IN (...), a SELECT, a text value for an integer column, or an
empty script, is sql.script, exit status 3, with the message naming the
line.
7.2 Judging
The script runs from empty tables. Each statement is judged against the last state the model accepted:
- An
INSERTfills columns it leaves out from theirDEFAULTliteral, and is one insert step. - An
UPDATEorDELETEthat matches several rows is one step per row, and is refused as a whole when any of its steps is refused. One that matches no row changes nothing and is allowed. AFTERtriggers that insert rows, andON DELETEactions, are applied to the state.BEFORE UPDATERAISEtriggers fire on anUPDATEthat sets a column to the value it has, as in SQLite.- A refused statement leaves the state as it was, and the script goes on.
The resulting states are refereed by the evaluator against the model
(DESIGN.md section 7.6). A refusal
names the rules that refuse it: a fact (fact users_unique_id), a field
whose multiplicity fails (field email), a foreign key
(foreign key orders.user_id -> users.id), or a trigger guard
(update_jobs: no_reopen).
7.3 Output
Text: accepts: ALLOWED (N state(s)) or accepts: REFUSED (N state(s));
then for each refused statement line L: STATEMENT: refused by RULES; the
line failed rules: ...; when some rules of the schema were not read,
warning: N rule(s) of the schema are not read; a statement they refuse is allowed here; then check NAME: holds or check NAME: BROKEN for each
promise.
--json, per elinvar explain schema:accepts: elinvar, command,
allowed, failed_rules, checks (each name, holds),
all_checks_hold, unread_rules (when at least 1), and
refused_statements (each line, statement, rules).
Exit status: 0 every statement allowed and every check holds; 1 a statement refused or a check broken; 3 errors.
8. fuzz
elinvar fuzz FILE [--against CMD] [--seed N] [--scripts N] [--length N]
[--require-coverage] [--with FILE] [--tables A,B [--with-referencing]]
[--timeout DUR] [--json]
Runs random scripts of changes against a real database and against the model, statement by statement, and reports the first statement on which they disagree.
8.1 The database
--against names the database command line, sqlite3 by default. It is
split into words without a shell, with quotes honored; an unclosed quote
or an empty command is sql.database. Three kinds are known:
| Command | How a statement is run |
|---|---|
sqlite3 ... | a template database is made once from PRAGMA foreign_keys = ON; and the schema, with -bail; each script runs on a copy, each statement with the pragma |
psql ... | with -v ON_ERROR_STOP=1, each statement runs as BEGIN; schema; earlier statements; statement; ROLLBACK; |
| anything else | the schema, the earlier statements, and the statement are sent each time |
A statement is allowed by the database when the command exits with
status 0. A database that rejects the schema, or a command that cannot be
run, is sql.database, exit status 3. Files go in a temporary directory
under the system’s temporary directory.
8.2 Scripts
The model is imported temporal, from any state, as for accepts. A
schema with no table is als.syntax. A seeded generator (SplitMix64,
--seed, default 1) writes --scripts scripts (default 100) of about
--length statements (default 8). A script first inserts rows into a
table and its foreign-key ancestors in dependency order, then inserts,
updates, and deletes rows of populated tables: updates pick rows by
primary key and try col + 1, NULL, and the values of closed sets. Up to
min(scripts / 3, 24) scripts aim at the guards found by tests, and
tables with checks or insert triggers get rows solved to pass them.
The scripts depend only on the schema, the seed, and the counts: solves
are bounded by conflicts, and --timeout can stop the planning but not
shape it. When it runs out while planning, no script runs and the verdict
is unknown.
8.3 Comparing
For each statement, the database’s answer is compared with
accepts on the earlier allowed statements followed by this one
(section 7). Both allowed: the statement joins the prefix.
Both refused: the script goes on. They differ: when the database refused,
the model allowed, and the database’s error message matches a rule that
was not read, the case is counted under explained_by_unread and the run
goes on. Otherwise the prefix is shrunk, by removing statements while the
disagreement remains, and the run stops with verdict disagreed and the
shortest script found. When --timeout runs out or the database fails
while shrinking, the script is reported as found, unshrunk, with
shrunk: false and the reason in note.
A statement the generator writes that accepts cannot read is
sql.script with the message fuzzer generated an unsupported statement; it is a bug in the generator.
8.4 Output
Verdicts: agreed, every script run without disagreement; disagreed;
unknown, when --timeout ran out, or --require-coverage was given
and some table got no row or some read rule never refused a statement.
--json, per elinvar explain schema:fuzz: verdict, against, seed,
scripts_run, statements_run, database_allowed, database_refused,
model_allowed, model_refused, rows_inserted per table,
rule_refusals per rule, rules_never_fired, unread_rules,
explained_by_unread, disagreement (script, line, statement,
database_allowed, database_error, model_allowed, model_rules,
shrunk, or null), note, and story.
Exit status: 0 agreed; 1 disagreed; 2 unknown; 3 errors.
9. audit
elinvar audit SCHEMA --data DUMP [--with FILE] [--tables A,B [--with-referencing]] [--json]
Checks the rows of a data dump, as one state, against the schema’s rules
and the single-state promises of a sidecar, with the evaluator and
without the solver. --data - reads the dump from standard input.
9.1 Reading the dump
The schema is imported temporal, from any state. The dump is split into
statements, passing over -- and /* */ comments and lines that start
with \. Read are INSERT [INTO] t [(cols)] VALUES (...), (...) [ON CONFLICT ...], with several rows, values NULL, TRUE, FALSE,
'text', x'hex', and integers, and Postgres casts and parentheses
around values removed. Columns an INSERT leaves out take their DEFAULT
literal.
| Statement | Effect |
|---|---|
INSERT into a table of the schema or slice | rows read |
INSERT into another table | warning audit.dropped_rows, with the row count and first line |
ALTER, ANALYZE, BEGIN, COMMENT, COMMIT, CREATE, DROP, END, GRANT, LOCK, PRAGMA, RELEASE, REVOKE, ROLLBACK, SAVEPOINT, SELECT, SET, START, UNLOCK, USE, VACUUM | passed over |
any other statement, such as COPY or UPDATE | warning audit.ignored_statement |
no INSERT at all | warning audit.no_rows; when the file also holds other statements, it is not a dump and is error audit.parse |
an INSERT that cannot be read, or whose value count differs from its column count | error audit.parse |
9.2 Rules
These rules are checked directly on the rows, each named in the report as
shown: NOT NULL t.c, UNIQUE t.c, CHECK enum t.c,
PRIMARY KEY t(cols), UNIQUE t(cols), UNIQUE INDEX name (partial ones
included), and FOREIGN KEY t.c -> u.id. The model’s other facts that do
not involve steps, among them checks and composite foreign keys, are
evaluated on the one state; a broken one is reported with the detail
schema rule does not hold on the dumped rows.
A promise (check command) of an Alloy sidecar is evaluated on the state
when it does not use steps, after an outer always is removed. One that
does is listed under skipped_promises with the reason
requires multiple states (uses temporal step operators).
9.3 Output
Verdicts: clean, every rule and promise holds; violations.
Text starts audit (DATA against SCHEMA): VERDICT (...) and lists each
broken rule, each promise as holds or BROKEN, skipped promises,
warnings as warning[CODE]: line N: MESSAGE, and, when rules were not
read, warning: N rule(s) of the schema were not read and could not be checked.
--json, per elinvar explain schema:audit: verdict, rows_audited,
tables (rows per table), rule_violations (each rule, table,
detail, line), promises, skipped_promises, unread_rules,
warnings (each code, message, fix, place), and story.
Exit status: 0 clean; 1 violations; 3 errors.
10. discover
elinvar discover FILE [--with FILE] [--tables A,B [--with-referencing]]
[--show-rejected] [--scope N] [--budget N] [--timeout DUR] [--json]
Tries common invariants on each table and keeps those proved for any number of steps within the scope.
10.1 Candidates
The schema is imported temporal and from empty tables. For each table in
the slice (every table without --tables) the candidates are:
| Kind | Invariant |
|---|---|
never_populated | the table is always empty |
never_deleted | no row is ever deleted |
protected_by_reference | a row is not deleted while a row of a given table references it, one candidate per single-column foreign key into the table |
always_present | a nullable column always has a value |
immutable | a column never changes after insert |
immutable_once_set | a nullable column never changes once it has a value |
never_cleared | a nullable column never goes from a value to NULL |
non_decreasing | an integer column, not a key or foreign key, never decreases |
unique | a column is unique across live rows, except a table’s sole primary key |
at_most_one_open | at most one row per key has its marker column NULL: for each partial unique index WHERE c IS NULL, and for nullable columns that look like markers (the table has at most 6 columns, or the name contains ended, closed, revoked, deleted, archived, completed, cancelled, canceled, expired, removed, finished, or stopped), keyed by the other columns that are not unique |
A table proved never_populated gets no other candidate. A proved
candidate leaves out the ones it implies: never_deleted leaves out
protected_by_reference; immutable leaves out immutable_once_set,
never_cleared, and non_decreasing; immutable_once_set leaves out
never_cleared and non_decreasing; unique leaves out
at_most_one_open on the same single key.
10.2 Proof
Each candidate is an assert checked by k-induction with k = 1
(DESIGN.md section 7.6) at
--scope (default 3), with at most --budget conflicts (default 200000)
per candidate; --timeout limits the whole run. Only proved candidates
are kept as invariants. Each is given the rules it rests on, from a
minimal unsatisfiable core taken without StartEmpty at a scope of at
most 2. With --show-rejected, a candidate that is not proved is
listed with the reason counterexample and the counterexample, or
not_inductive.
Candidates may be checked in parallel; the output is in candidate order and does not depend on the number of threads.
10.3 Output
Text: discover: proved N invariant(s) across T table(s) (scope S; checked C candidate(s)), then per table a sentence for each invariant and
rests on: ..., then, with --show-rejected, a not proved: section.
--json, per elinvar explain schema:discover: tables, scope,
candidates_checked, candidates_unfinished, unread_rules,
invariants (each table, column, kind, sentence, formula,
rules), rejected (with --show-rejected; each also reason and
counterexample), and story.
Exit status: 0 every candidate finished; 2 some did not finish within the budget or time; 3 errors.
11. ci
elinvar ci [MANIFEST] [--timeout DUR] [--junit | --sarif | --json]
Runs the entries of a manifest, elinvar.toml by default, under one
shared time limit, and compares each entry’s verdict with the one it
expects.
11.1 The manifest
The manifest is a small subset of TOML: key = value lines, #
comments, and array-of-table headers. Values are strings in " or ',
lists of strings, true, false, and integers. Top-level keys, before
the first entry, set defaults: timeout (a duration such as 60s), and
scope, steps, and budget (integers of at least 1).
| Entry | Keys | Default expect | Verdicts |
|---|---|---|---|
[[check]] | name file command with tables with_referencing expect induction scope steps budget explain | holds | the check’s verdict; holds also matches proved |
[[run]] | name file command with tables with_referencing expect scope steps budget | found | the run’s verdict |
[[accepts]] | name file trace with tables with_referencing expect | allowed | allowed, refused |
[[diff]] | name old new migration of with tables with_referencing ignore_unread expect scope steps budget | equivalent | the diff’s verdict |
[[discover]] | name file with tables with_referencing scope budget expect | completed | completed, unknown |
[[tests]] | name file with tables with_referencing allow_dead scope steps budget expect | passed | passed, failed, unknown |
file, old, new, trace, migration, and with are paths relative
to the manifest’s directory; a directory is read as migrations
(section 1.1). A [[diff]] with migration
compares old with old followed by the migration. An entry without
name is named KIND#N, N its position from 1. A check or run on
a file with several commands takes the worst verdict among them.
An unknown section or key, a value of the wrong type, or a manifest with
no entry is ci.manifest, exit status 3. A missing manifest file is
cli.input. An entry that cannot run (a missing file, a missing required
key, a model with errors) is not a manifest error: the entry has actual
verdict error and fails.
11.2 Running
Entries run in order. Each gets the time left of the shared limit
(--timeout, else the manifest’s timeout, else none); when none is
left, the remaining entries are unknown with the message
shared CI timeout exhausted. An entry passes when its actual verdict
matches expect, is unknown when its verdict is unknown and expect
is not, and fails otherwise.
11.3 Output
Markdown by default: a table of entry, kind, expected, actual, result, and
time, a line verdict: VERDICT (P passed, F failed, U unknown, T ms), and
the message of each entry that did not pass. --junit writes JUnit XML,
--sarif SARIF 2.1.0; only one may be given, and neither with --json.
--json, per elinvar explain schema:ci: manifest, verdict
(passed, failed, unknown), passed, failed, unknown,
elapsed_ms, entries (each name, kind, file, expected,
actual, outcome, elapsed_ms, message), and markdown.
Exit status: 0 every entry passed; 1 an entry failed; 2 none failed and one is unknown; 3 manifest or argument errors.
12. Codes
The codes of this file, all explained by elinvar explain CODE and listed
in CODES.md. Errors end a verb with exit status 3; warnings do
not change the verdict.
| Code | Kind | When |
|---|---|---|
sql.skipped | error | import --strict met a statement or clause it does not read; diff of two SQL schemas whose unread rules differ, unless --ignore-unread |
sql.script | error | accepts was given a SQL script with a statement or value it cannot read; fuzz generated such a statement |
sql.database | error | fuzz could not run the --against command, the command was malformed, or the database rejected the schema |
audit.parse | error | audit met an unreadable INSERT or value, or a file that is not a dump |
audit.dropped_rows | warning | the dump inserts rows into a table not in the schema or slice |
audit.ignored_statement | warning | the dump has a statement that is neither an INSERT nor one passed over |
audit.no_rows | warning | the dump has no INSERT |
ci.manifest | error | the manifest cannot be parsed, has an unknown section or key or a value of the wrong type, or has no entry |
Other codes these verbs give: als.syntax (a schema that cannot be
lexed or has no table), als.unknown_name (--tables names an unknown
table), eval.result (an unreadable result JSON given to accepts),
cli.usage (a flag misused), and cli.input (a file that cannot be read).
The corpus
Status: phases 1 to 5 built, 2026-11-29; counts updated 2026-12-03. Every file of Alloy’s example corpus is read and all 224 commands Alloy answers agree with Alloy 6.2.0, the planted holes among them, and so do the 183 commands of the language cases (section 4); twelve models are also translated in Rust (section 6), two of them temporal; seven planted holes are found, the README’s sharing example among them.
Elinvar never runs Alloy to build or test (AGENTS.md law 2), so part of its evidence is a corpus of models with answers that Alloy gave once and that are kept in the repository (R16, DESIGN.md section 10). This file says where the models come from, which are used when, how the expected answers are made, and what a planted hole is.
Contents: 1 Sources · 2 Inventory · 3 Layout · 4 Expected answers · 5 Planted holes · 6 The first ten
1. Sources
| Source | Commit | Models |
|---|---|---|
| Alloy | 59ba203 (6.2.0) | org.alloytools.alloy.extra/extra/models/: 83 .als files |
| Elinvar | planted holes (section 5) | |
| Elinvar | language cases: one model per construct of the model text, its commands chosen so that a wrong reading changes an answer (LOGIC.md section 15) |
cargo x fetch checks Alloy out under target/upstream/alloy/. The
repository has 97 .als files in all at that commit. The other 14 are the
11 library modules in org.alloytools.alloy.core/src/main/resources/models/util/,
which models open and which matter in phase 5, two files of the command
line module, and one test resource.
Kodkod’s and Pardinus’s own tests are Java programs that build formulas through the API, not models. They are a source of cases for spec tests, read and rewritten by hand, and are not inventoried here yet.
2. Inventory
The 83 models, by what they need. The split was made by a scan of each file
with comments removed: commands are lines starting with run or check,
with or without a label before them, integers are any of #, Int, int,
sum, time is var or a temporal keyword, and modules are open lines. A scan can be wrong.
Whoever translates a model reads all of it, and corrects its row if it was
wrong.
| Group | Files | Disposition |
|---|---|---|
| static, no integers, opens no module | 33 | translate, phase 2 |
| static, no integers, opens a module | 23 | translate, phase 2 after the first group; a model that opens util/ordering is translated with the order fixed by exact bounds, as Alloy fixes it (DESIGN.md section 7.5) |
| changing relations and temporal formulas | 4 | translate, phase 3 |
| integers | 17 | read and compared once bounded integers were added (LOGIC.md section 16) |
| no command | 6 | skip: nothing to compare. Two are modules that other models open |
Static, no integers, opens no module (33):
book/appendixA/:addressBook1,closure,distribution,prison,properties,ring,spanning,tree,tube,undirectedbook/chapter2/:addressBook1a,1e,1g,2a,2b,2c,2d,2ebook/chapter4/:filesystem,grandpa1,grandpa2,grandpa3,lightsbook/chapter5/:addressBook,lists,sets1,sets2book/chapter6/:mediaAssets,memory/abstractMemory,memory/cacheMemoryexamples/systems/:file_system,marksweepgcexamples/toys/:ceilingsAndFloors
Static, no integers, opens a module (23):
util/ordering:book/appendixE/p300-hotel,p303-hotel,p306-hotel;book/chapter2/addressBook3ato3d;book/chapter6/hotel1tohotel4,ringElection1,ringElection2;examples/algorithms/dijkstra;examples/case_studies/firewire;examples/tutorial/farmerutil/orderingwithutil/graphorutil/boolean:examples/algorithms/opt_spantree,s_ringlead,stable_orient_ringutil/relation:examples/case_studies/com,examples/toys/numbering- other models of the corpus:
book/chapter6/memory/checkCache,checkFixedSize
Time (4): examples/temporal/ buffer, trash, and with util/ordering,
leader, leader_events.
Integers (17): book/chapter2/ addressBook1b, 1c, 1d, 1f, 1h;
examples/algorithms/ messaging, peterson, ringlead,
stable_mutex_ring, stable_ringlead; examples/case_studies/ chord,
chord2, chordbugmodel; examples/puzzles/handshake;
examples/systems/ javatypes_soundness, lists, views.
No command (6): book/appendixA/ addressBook2, barbers, phones;
book/chapter6/memory/ fixedSizeMemory, fixedSizeMemory_H;
examples/case_studies/ins.
The first ten (phase 2’s exit criterion) are chosen from the first group
when phase 2 starts, after each candidate is read in full. Three things
found while reading book/appendixA/ bear on the choice:
- Eight of its ten models are exercise skeletons, with predicates left
empty for the reader to fill in. They test scopes and bounds and little
else.
distributionandpropertiesstate something. - Those two quantify over relations (
all s: set univ, p, q: univ->univ), so they need skolemization (DESIGN.md section 7.2), and overuniv, so they need the integer atoms of section 4. tubehas three unconstrained relations over eleven stations. Its verdict can be compared; its instances cannot be counted.
So the first ten should lean on chapters 4 and 5, which state real
constraints over signatures, with distribution and properties for
skolemization.
3. Layout
corpus/holes/hierarchy.als planted holes, Elinvar's own, as Alloy
corpus/holes/access.als text with `expect` lines
corpus/holes/sharing.als the README's example, a trace
corpus/holes/frame-*.als frames over part of a field, one row,
or a changing set, which slicing once
took for whole frames (2026-12-02)
corpus/language/*.als language cases: `;`, macros, defined
fields, `disj[...]`, number literals,
`private` and string names, `sum disj`
crates/elinvar-engine/tests/corpus.rs Alloy's models in Rust, each citing its
.als file at the pinned commit, with its
expected answers and where they come from
crates/elinvar-engine/tests/holes.rs the planted holes in Rust
Alloy’s .als files are not copied: the terms of Alloy’s LICENSE at
6.2.0 are unclear, so AGENTS.md law 39 treats them as incompatible
(DESIGN.md section 13). cargo x fetch puts them in target/upstream/ for
reading.
From phase 5, crates/elinvar-als/tests/text.rs also reads eight of these
models straight from target/upstream/, unmodified, and checks they give
the same verdicts as their Rust translations; the planted holes are read as
text too. Before cargo x fetch, cargo x test skips the models it cannot
find, and cargo x corpus fails on them, so it never reports agreement on
the planted holes alone.
cargo x test runs every corpus command but those marked slow.
cargo x corpus builds in release mode and runs all of them, slow ones
included, printing each command’s verdict, size, and time; cargo x bench corpus sets those times beside a local baseline (R29). From phase 5 it
also reads each .als directly and compares the two translations with each
other. For that comparison the reader is told to add the 16 atoms of
section 4, which a hand translation adds where they matter. Whether
elinvar-als adds them for a user by default is a difference from Alloy
either way, and is decided when phase 5 specifies the subset
(LOGIC.md section 10).
4. Expected answers
cargo x oracle runs Alloy 6.2.0 (its release jar, checked against a
pinned SHA-256) on every model of extra/models/, every planted hole, and
every language case,
one command at a time, and writes each command’s answer to
corpus/expected.txt: SAT for an instance or a counterexample, UNSAT for
none. It first ran on 2026-11-28, with a JDK unpacked under
target/oracle/. Its last run, on 2026-12-03, has 411 rows: 407 commands
answered, 183 of them the language cases’, and 4 that are ERROR in Alloy itself (the file s_ringlead,
which Alloy does not compile, the file ins, which has no commands, and the
two commands of temporal/trash that ask for unbounded steps, for 1.. steps, which REQUIREMENTS.md section 6 leaves out). A command that leaves
no answer is an ERROR row of its own, and the oracle goes on to the next;
until 2026-12-02 it stopped there instead, and five bounded commands of
temporal/trash that follow the first unbounded one went uncompared.
When Alloy gives no answer, the oracle prints the first line of its
message. cargo x oracle --only FILE runs one model, named as
corpus/expected.txt names it, and keeps every other row, which is how a
new language case gets its answers without a full run.
cargo x corpus compares every command of every model with those answers
(crates/elinvar-als/tests/text.rs, agrees_with_alloy), reading them with
Alloy’s 16 integer atoms in every universe, a model’s own modules read
beside it, and a budget of 2,000,000 conflicts per command: all 346 agree,
none disagrees, and none runs out of budget. A command of a model Elinvar
reads with no row in corpus/expected.txt fails the comparison, so the
answers cannot fall behind the corpus.
The Rust translations of corpus.rs also say where their expected answers
came from, before the oracle ran: the model’s own expect line, its
authors’ comment, or reasoning written beside it. Every one agrees with the
oracle.
corpus/expected.txt is tab-separated, one row per command: file, 0-based
command index, label, answer (SAT, UNSAT, or ERROR), and Alloy’s time
in milliseconds (JVM startup included):
book/chapter4/grandpa1.als 0 NoSelfFather UNSAT 275
examples/toys/ceilingsAndFloors.als 4 BelowToo"" UNSAT 2823
cargo x bench corpus reads those Alloy times and prints them beside
Elinvar’s times and the local baseline (R29). What the oracle does not write
is instance counts with symmetry breaking off: Alloy’s exec writes each
solution as a file, which makes large counts slow to gather; counts are
compared with brute force instead (DESIGN.md section 10).
The oracle needs Java and the Alloy release, fetched by the verb and checked against a pinned hash. It is the one place Java runs (AGENTS.md law 2). CI never runs it; CI compares against the committed files.
What “the same answer” means:
- Verdicts match. Alloy has two answers and Elinvar has more
(DESIGN.md section 7.6): Alloy’s “an instance exists” is
foundfor arunandcounterexamplefor acheck; Alloy’s “none” isnonefor arun, and for acheckeitherholdsorvacuous, which Alloy does not tell apart.unknownmatches nothing and fails the comparison. - Counts match with symmetry breaking off on both sides. With it on, the two tools may keep different representatives, so only verdicts are compared.
- A total order from
util/orderingis fixed on Alloy’s side even with symmetry breaking off, so the Rust translation fixes it too, with exact bounds in atom order (DESIGN.md section 7.5). Otherwise Elinvar would count every order where Alloy counts one. - The universe matches. Alloy puts 16 integer atoms in every command’s
universe (LOGIC.md section 10). A Rust translation of a model that
mentions
univ,iden, or*declares 16 extra atoms in a set of their own with an exact bound, so both sides range over the same number of atoms. A model that mentions none of the three does not need them: atoms no relation can hold do not change a verdict or a count. - Skolem relations count. Alloy’s enumeration tells apart two instances
that differ only in a witness: its blocking clause covers every primary
variable, and a skolem relation has them (LOGIC.md section 10). So a
count agrees only if both sides skolemize the same quantifiers, and
Alloy’s rewriting of
no,one, andlonedecides where some of them are. How that is handled is open (DESIGN.md section 13, item 9).
An expected answer changes only through cargo x oracle (AGENTS.md law 30),
and a change is reviewed like a change to a test.
5. Planted holes
A planted hole is a model written for Elinvar with a known way to break its promise (R17). Its expected answer is a counterexample, and where it is known, the fewest steps and atoms that show it. If Elinvar reports no counterexample, Elinvar is wrong.
The first is the README’s sharing example: share, end the follow, leave a note (DESIGN.md section 9.4). It is phase 3’s exit criterion.
Rules for the set:
- Each hole has a sibling with the hole fixed, whose expected verdict is “holds”. A checker that reports a counterexample for everything fails the siblings.
- Static holes come first (phase 2): a constraint that was meant and not written, such as a hierarchy that allows a cycle, or a permission that outlives its group.
- Every wrong “no counterexample” ever found in Elinvar becomes a planted hole, with the commit that fixed it (AGENTS.md law 28).
- Holes are also written as
.als, socargo x oracleconfirms that Alloy finds each one. A hole that uses something Alloy lacks is tested by the referee, brute force, and its sibling alone.
The agent suite retells these as prose (DESIGN.md section 9.8).
6. The first ten
The phase 2 and 3 Rust translations, by file under
org.alloytools.alloy.extra/extra/models/, with the source of each expected
answer. Every command agrees; times are from cargo x bench corpus on an
Apple M-series laptop on 2026-11-29, release build.
| Model | Commands | Expected answers from | Slowest |
|---|---|---|---|
book/chapter4/grandpa1 | 3 | comments in the file | under 1 ms |
book/chapter4/grandpa2 | 2 | comments in the file | under 1 ms |
book/chapter4/grandpa3 | 3 | comments in the file | under 1 ms |
book/chapter4/filesystem | 3 | comments in the file | under 1 ms |
book/chapter5/sets1 | 1 | reasoning in corpus.rs | under 1 ms |
book/chapter5/sets2 | 1 | reasoning in corpus.rs | 0.1 s |
book/chapter5/lists | 1 | reasoning in corpus.rs; vacuous, where Alloy says only “no counterexample” | under 1 ms |
examples/toys/ceilingsAndFloors | 5 | expect lines | 0.8 s at scope 10, 3 ms at 6 |
book/chapter2/addressBook1a | 1 | an empty predicate: any case | under 1 ms |
examples/systems/marksweepgc | 3 | expect lines | 1 ms |
examples/temporal/trash | 8 | reasoning in corpus.rs; its two for 1.. steps commands, which ask for unbounded traces, are run with 10 steps | 0.2 s |
examples/temporal/buffer | 5 | reasoning in corpus.rs | 3.8 s |
Read as text only, unmodified, since util/ordering is read (LOGIC.md
section 15.1), in crates/elinvar-als/tests/text.rs:
| Model | Commands | Expected answers from | Agrees |
|---|---|---|---|
examples/tutorial/farmer | 2 | expect lines | yes |
examples/algorithms/dijkstra | 3 | expect lines | two of three; see below |
examples/temporal/leader | 4 | reasoning in text.rs | yes |
examples/temporal/leader_events | 4 | reasoning in text.rs | yes |
dijkstra’s run ShowDijkstra for 5 State, 2 Process, 2 Mutex expect 1
is wrong in the file itself. Elinvar finds no instance, and so does Alloy
6.2.0, which reports that the command “was not satisfied against
expectation”. The file’s own check DijkstraPreventsDeadlocks ... expect 0 implies the same, and lock ordering rules a deadlock out by hand: a
process waits only for a mutex above every one it holds.
The oracle also found bugs in Elinvar’s reading of model text, now fixed, each a constraint the text says and the reader dropped:
- In a signature’s fact, a field of an ancestor signature was read as the
whole relation, not as
this.f. Onexamples/systems/file_system.alsthat madecheck$1hold where Alloy finds a counterexample: a wrong “holds”. The testinherited_fields_in_signature_factsfailed before the fix (AGENTS.md law 28). - An arrow’s multiplicity in a quantifier’s declaration (
some tree: Node lone -> Node) anddisjamong a signature’s fields were read as nothing. Onexamples/case_studies/firewire.alsthat gave instances and counterexamples Alloy does not have. A counterexample from a model with a dropped constraint is a real counterexample to the weaker model, which is why the referee could not catch it; the oracle could.
All remaining models that open util/ordering, util/graph, util/boolean,
util/relation, or local modules (hotel1 to hotel4, the appendix E hotels,
addressBook3a to 3d, ringElection1 and 2, firewire, and the 17
integer models) now read unmodified and agree with Alloy in agrees_with_alloy.
The three checks of buffer (0.5 to 3.8 s each in a release build; Alloy
takes 11 to 73 s) are marked slow, so cargo x test skips them and
cargo x corpus runs them. ceilingsAndFloors at scope 10 runs in under
1 s and is part of cargo x test.
Error codes
Generated by cargo x generate from the code tables of elinvar-logic,
elinvar-engine, elinvar-als, and elinvar; do not edit. Each is specified in LOGIC.md, and every
error carries its code, a message with the names and numbers involved, its
fix, and its place (AGENTS.md law 21).
| Code | When | Fix |
|---|---|---|
universe.empty | a universe with no atoms | give the universe at least one atom |
universe.duplicate_atom | two atoms with one name | give every atom of a universe its own name |
universe.bitwidth | a bitwidth outside 1 to 32 (LOGIC.md 16.1) | give a bitwidth from 1 to 32 |
universe.int | an integer atom whose integer is outside the bitwidth’s range, or two integers for one atom, or two atoms for one integer (LOGIC.md 16.1) | give each integer atom one integer, within the bitwidth’s range, and each integer at most one atom |
universe.unknown_atom | a tuple names an atom the universe lacks | name only atoms of the universe, or add the atom to it |
universe.capacity | the number of tuples of an arity, n^k, is more than 2^64 - 1 | use fewer atoms, or relations and expressions of smaller arity |
tuples.arity | a tuple set is given a tuple of another arity | give a tuple set only tuples of its own arity |
tuples.other_universe | a tuple set is given a tuple, or combined with a tuple set, over a different universe | build every tuple and tuple set from the same universe |
tuples.index | a tuple set is given an index of no tuple of its arity | give an index below n^k for n atoms and arity k |
bounds.arity | a bound whose arity is not the relation’s | give the relation bounds of its own arity |
bounds.lower_outside_upper | a lower bound with a tuple the upper bound lacks | add the tuple to the upper bound, or remove it from the lower bound |
bounds.other_universe | a tuple set over a different universe | build the bounds from tuple sets over the bounds’ own universe |
bounds.duplicate_relation | bounds are given for a relation that has them | bound each relation once |
bounds.duplicate_name | two relations of one bounds have one name | give each relation its own name |
instance.arity | a tuple set whose arity is not the relation’s | give the relation a tuple set of its own arity |
instance.other_universe | a tuple set over a different universe | build the instance from tuple sets over its own universe |
instance.duplicate_relation | a tuple set is given for a relation that has one | give each relation one tuple set |
instance.duplicate_name | two relations of one instance have one name | give each relation its own name |
arity.zero | a relation or a tuple of arity 0 | give it an arity of 1 or more |
arity.mismatch | an operator that needs equal arities is given unequal ones | make both sides the same arity, for example by joining one side with a relation |
arity.join | a join of two expressions of arity 1 | to ask whether two sets meet, write some (a & b) |
arity.not_binary | transpose or closure on an expression of arity other than 2 | apply it to a binary relation |
arity.not_a_set | the set side of a restriction, or a declaration’s expression, of arity other than 1 | use an expression of arity 1 there |
logic.free_variable | a formula with a free variable is evaluated, run, or checked | use the variable only inside the quantifier or comprehension that declares it |
logic.no_declarations | a quantifier or a comprehension with no declarations | declare at least one variable |
logic.rebound_variable | a variable is declared where it is already bound | declare a new variable instead of reusing one that is in scope |
logic.higher_order | a declaration over sets or relations where only atoms are declared: in a comprehension, or in a quantifier skolemization cannot remove | declare atoms there, or move the quantifier over sets to the outside of the formula, where it becomes a relation |
logic.unbound_relation | a formula is run or checked and uses a relation the bounds lack | give the relation bounds |
instance.missing_relation | a formula is evaluated and uses a relation the instance lacks | give the relation a tuple set in the instance |
trace.no_states | a trace with no states | give the trace at least one state |
trace.loop | a loop target that is not a state | loop back to one of the trace’s states, from 0 |
trace.relations | the states disagree about which changing relations they give, or give a fixed one | give every state the same changing relations, and fixed relations in the fixed instance |
enumerate.too_large | brute-force enumeration over more free tuples than its cap | shrink the upper bounds, raise the cap, or use the solver |
model.bitwidth | a command asks for a bitwidth above 16 in a model with integers, whose Int set would have 2^w atoms | give the command a bitwidth from 1 to 16 with bitwidth |
model.no_scope | a command leaves a top-level set without a scope | give the set a scope with scope, scope_of, or exactly |
model.not_a_set | a scope is given for something that is not a top-level set of the model, or an ordering for a set that changes over time | give scopes only to the model’s top-level sets |
model.not_changing | an action’s effect names something that is not a changing relation of the model | name a relation declared with changing_field, changing_relation, or changing_subset |
model.changing_after_action | a changing relation is declared after an action, so that action’s frame misses it | declare every changing relation before the first action |
model.diff_mismatch | two models being compared with diff do not declare the same signatures and fields with the same arities and mutability | compare models that share the same signatures, fields, arities, and var declarations |
model.trivial_holds | a check assertion holds from the bounds alone without using any rule of the model | check whether the promise is a tautology or restates a definition rather than testing a rule |
model.vacuous_premise | an implication promise’s premise is never satisfied in any allowed case within the scope | increase the scope or steps, or inspect why the premise can never happen |
model.premise_unknown | warning: a check of an implication holds, but whether its premise is ever satisfied was not settled within the budget for that question, so the holds may be vacuous | raise --budget or --timeout, or lower the scope, and check again; or run the premise to see a case of it |
model.invalid_steps | a command asks for 0 steps; a trace needs at least 1 state | use at least 1 step (but 1 steps or --steps 1) |
model.scope_too_large | a command asks for more atoms, or more possible tuples, than the bounded checker supports | lower the command’s scope (at most 4096 non-integer atoms, and 16777216 possible tuples over all relations) |
als.syntax | text that is not Alloy, or not this subset’s grammar | write the model in the subset of Alloy 6 that LOGIC.md section 15 lists |
als.unknown_name | a name that is no signature, field, predicate, function, parameter, or variable in scope | declare the name, or fix its spelling |
als.unsupported | a construct outside the subset of LOGIC.md section 15.2 | rewrite the model without it; LOGIC.md section 15.2 lists what is not read |
als.sort | a formula where an expression belongs, or the other way round | write an expression where a set or relation is wanted, and a formula where true or false is |
als.duplicate | two declarations of one name | give each signature, field, predicate, function, and assertion its own name |
als.arguments | a predicate or function called with the wrong number of arguments, or with arguments whose types fit none or more than one of its overloads | pass one argument per parameter, of the types of the declaration meant |
als.no_command | a command name the file does not have | name a command of the file, or give none to run them all |
eval.result | elinvar eval is given a result it cannot read as an instance or trace of the model | give the JSON of one result of elinvar check --json or elinvar run --json for this model |
sql.skipped | SQL import with --strict encountered a statement or constraint it does not read | rewrite or remove the unsupported SQL rule, or drop --strict to inspect the skipped comments |
sql.script | elinvar accepts is given a SQL DML script containing a statement or expression it cannot read | use single-row INSERT INTO t (cols) VALUES (...), UPDATE t SET ... WHERE ..., and DELETE FROM t WHERE ... statements with literal or simple arithmetic values |
sql.database | elinvar fuzz could not run the external database command given to --against or the database rejected the schema | check that --against names an installed database CLI (for example --against sqlite3) and that the schema loads without error |
als.int_wrap | warning: an integer literal written in the model does not fit the command’s Int bitwidth and wraps | increase the command’s Int bitwidth (for example but 6 Int), or use a smaller literal |
als.unframed_var | warning: a step predicate updates some changing (var) relations while leaving others unconstrained | add r' = r (or another constraint) in the step predicate for each changing relation it should leave unchanged |
als.default_command | warning: the file has no run or check command, so Alloy’s default command, run {} named Default, was run, which only shows the rules allow some case | add the command meant, such as check Name for 4 for a promise or run Name for 4 for an example |
als.empty_by_type | warning: a join, intersection, or comparison combines expressions whose column types never overlap | check the column types on both sides; the join or intersection is always empty, or the comparison is trivially decided by types |
cli.usage | a verb was given a flag, argument, or value it does not take, or a verb that does not exist | read the verb’s --help (or elinvar --help for the verbs), and pass what it lists |
cli.steps_ignored | warning: --steps (or the steps argument) was given for a model where nothing changes, so there is no trace for it to bound | drop --steps, or declare what changes with var |
cli.state_past_end | warning: --state K (or state) is at or past the number of states in the trace; the trace loops, so K is read as the state the loop reaches there (LOGIC.md section 13.1) | give a state from 0 to one less than the number of states; a static instance has only state 0 |
cli.input | an input named on the command line cannot be read: a missing or unreadable file, a directory with no .sql files, stdin that fails, or a result that is not JSON | check the path and its permissions; - reads stdin, and a directory is read as its .sql files in name order |
audit.parse | a SQL data dump passed to elinvar audit --data has an unreadable INSERT statement or value | check the SQL dump syntax and pass INSERT statements from sqlite3 .dump or pg_dump --inserts |
audit.dropped_rows | a SQL dump passed to elinvar audit --data inserts rows into a table that is not in the audited schema, or not in its --tables slice; those rows are not audited | add the table to the schema or to --tables, or remove its rows from the dump if they do not belong to this database |
audit.ignored_statement | a SQL dump passed to elinvar audit --data has a statement that is neither an INSERT nor one that carries no rows (such as COPY, UPDATE, or text that is not SQL); it is not read | dump with sqlite3 DB .dump or pg_dump --inserts, which write every row as an INSERT |
audit.no_rows | a SQL dump passed to elinvar audit --data has no INSERT statement, so the audit read no row and its clean says nothing about any data | check that the file is the dump of the database meant; an empty database needs no audit |
ci.manifest | a CI manifest passed to elinvar ci cannot be parsed or has an invalid entry | check the manifest TOML fields ([[check]], [[run]], [[accepts]], [[diff]], [[discover]], [[tests]]) and referenced file paths |