Start here

Lion documentation

Everything Lion can do, organized by what you need right now: to learn, to get a job done, to look something up, or to understand why.

Lion is a small Lisp whose programs are JSON. It evaluates on Effect, edits as a graph, runs from the command line, and includes a Datalog-style logic database.

These docs follow the Diátaxis framework. There are four kinds of documentation, each written for a different need, and they are kept apart so each one can do its own job. Tutorials teach and how-to guides direct; both are practical. Reference and explanation inform; both are theoretical.

Learning-oriented

Tutorials

Lessons that build something real, one working step at a time.

Task-oriented

How-to guides

Directions for getting a specific job done.

Understanding-oriented

Explanation

Background, reasoning, and the design choices behind Lion.

Information-oriented

Reference

Exact descriptions of every form, function, and command.

Tutorials4Learning-oriented
How-to guides27Task-oriented
Reference10Information-oriented
Explanation6Understanding-oriented
Live examples314Verified on every build

Self-hosted in Lion

Every page, metric, guideline, and README is computed from Lion programs in docs-model/ and checked by Lion Datalog rules on every build.

Where to start

Every example is live

A program with a result under it is a live example. Edit the program and it runs again; press ⌘/Ctrl + Enter to run it at once, or Reset to bring back the original.

["number/multiply", ["number/add", 1, 2], 4]
result
12

Examples run in your browser on the same evaluator as @lionlang/core. Each one starts from the standard library, a fresh environment, and an empty logic database, so examples never affect each other. The results printed on this page were computed by that evaluator when the docs were built.

Press / anywhere to search. Search finds documents, sections, and every form and function by name.

Tutorial · learning-oriented

Your first Lion program

Build a small checkout calculator, one working step at a time, and learn how Lion reads JSON as code along the way.

In this tutorial we will build a checkout calculator: given a cart total, it applies a discount for large orders and reports what the customer pays. Each step adds one idea and runs right here, so you can see every result as you go. You don't need to install anything.

Step 1: Write a value

Every Lion program is JSON. Start with the simplest program there is, a number. Edit it to any other number and watch the result follow.

42
result
42

A record is a program too. Lion evaluates each of its values and keeps its keys:

{"item": "lamp", "price": 120, "inStock": true}
result
{"item":"lamp","price":120,"inStock":true}

Numbers, booleans, null, and records of them come back as they are.

Step 2: Call a function

An array is a call. Its first element names the function, and the rest are its arguments. Add two prices:

["number/add", 120, 35]
result
155

The name number/add comes from Lion's standard library, which groups functions by module: number/, string/, array/, and so on.

Step 3: Nest calls

An argument can be another call. Lion evaluates the inner call first and passes its result on. Here is the cart total with 10% taken off:

["number/multiply",
  ["number/add", 120, 35],
  0.9]
result
139.5

Step 4: Name a value

To use the total more than once, give it a name with define. To run several steps in order, wrap them in begin, which returns the last result:

["begin",
  ["define", "total", ["number/add", 120, 35]],
  ["number/multiply", "total", 0.9]]
result
139.5

Notice that the string "total" now stands for 155. A string that names something evaluates to what it names.

Step 5: Write a function

A lambda is a function you write yourself: a list of parameter names and a body. Define one that applies a discount rate to any amount:

["begin",
  ["define", "discounted",
    ["lambda", ["amount", "rate"],
      ["number/multiply", "amount", ["number/subtract", 1, "rate"]]]],
  ["discounted", 155, 0.1]]
result
139.5

Change 0.1 to 0.25 and the result changes with it.

Step 6: Make a decision

Only large orders get the discount. cond checks conditions in order and returns the result next to the first one that holds:

["begin",
  ["define", "total", 155],
  ["cond",
    [["number/greaterThan", "total", 100], "discount"],
    ["else", "full price"]]]
result
"discount"

Try a total of 80.

Step 7: Put it together

Now combine everything into the calculator. A function that takes a list of prices adds them up, works out the discount, and returns a record, so the result shows each part of the checkout:

["begin",
  ["define", "rate",
    ["lambda", ["total"],
      ["cond",
        [["number/greaterThan", "total", 100], 0.1],
        ["else", 0]]]],
  ["define", "receipt",
    ["lambda", ["total"],
      {"total": "total",
       "discount": ["number/multiply", "total", ["rate", "total"]],
       "pay": ["number/multiply", "total", ["number/subtract", 1, ["rate", "total"]]]}]],
  ["define", "checkout",
    ["lambda", ["prices"],
      ["receipt", ["aggregate/sum", "prices"]]]],
  ["checkout", ["array/make", 120, 35]]]
result
{"total":155,"discount":15.5,"pay":139.5}

Change the prices in ["array/make", 120, 35] to 40, 35 and the discount disappears.

What we built

We wrote a working program in plain JSON. Along the way we used values, calls, names, functions, decisions, and records, which is most of the core language. Because the program is JSON, you could store it in a database, send it over HTTP, or have another program write it.

Next, the tutorial Build a family tree uses the same JSON to ask questions of a logic database. To look up the forms used here, see Special forms; to learn how names work, read Names, scope, and environments.

Tutorial · learning-oriented

Build a family tree

Store facts about a family, then ask Lion's logic database to work out grandparents, ancestors, and more, all in JSON.

In this tutorial we will record a small family and let Lion's logic database answer questions about it: who is whose grandparent, who descends from whom, and who has no children yet. At the end we will protect the tree from impossible data.

Each step shows the whole program so far, because every example runs on its own. New lines are at the end.

Step 1: Declare a relation and add facts

A relation is a table with named columns. Declare parent, then add four facts to it. The fact form returns the facts it added:

["begin",
  ["relation", "parent", ["parent", "child"]],
  ["fact",
    ["parent", "ada", "bea"],
    ["parent", "ada", "cal"],
    ["parent", "bea", "dot"],
    ["parent", "dot", "eli"]]]
result
[
  ["parent","ada","bea"],
  ["parent","ada","cal"],
  ["parent","bea","dot"],
  ["parent","dot","eli"]
]

Step 2: Ask a question

A query asks for every way to fill in the strings that start with ?. Those are logic variables. Ask who Ada's children are:

["begin",
  ["relation", "parent", ["parent", "child"]],
  ["fact",
    ["parent", "ada", "bea"],
    ["parent", "ada", "cal"],
    ["parent", "bea", "dot"],
    ["parent", "dot", "eli"]],
  ["query", ["parent", "ada", "?child"]]]
result
[{"child":"bea"},{"child":"cal"}]

There is one answer per child, keyed by the variable's name. Try ["parent", "?who", "dot"] to ask who Dot's parent is.

Step 3: Write a rule

A rule derives new facts. A grandparent is a parent of a parent, so the rule says: ?g is a grandparent of ?c when ?g is a parent of some ?p and ?p is a parent of ?c.

["begin",
  ["relation", "parent", ["parent", "child"]],
  ["relation", "grandparent", ["grandparent", "child"]],
  ["fact",
    ["parent", "ada", "bea"],
    ["parent", "ada", "cal"],
    ["parent", "bea", "dot"],
    ["parent", "dot", "eli"]],
  ["rule", ["grandparent", "?g", "?c"],
    ["parent", "?g", "?p"],
    ["parent", "?p", "?c"]],
  ["query", ["grandparent", "?g", "?c"]]]
result
[{"g":"ada","c":"dot"},{"g":"bea","c":"eli"}]

Step 4: Follow the line all the way back

An ancestor is a parent, or an ancestor of a parent. A relation can refer to itself, so two rules cover both cases:

["begin",
  ["relation", "parent", ["parent", "child"]],
  ["relation", "ancestor", ["ancestor", "person"]],
  ["fact",
    ["parent", "ada", "bea"],
    ["parent", "ada", "cal"],
    ["parent", "bea", "dot"],
    ["parent", "dot", "eli"]],
  ["rule", ["ancestor", "?a", "?p"], ["parent", "?a", "?p"]],
  ["rule", ["ancestor", "?a", "?p"],
    ["ancestor", "?a", "?mid"],
    ["parent", "?mid", "?p"]],
  ["query", ["ancestor", "?who", "eli"], {"order": "who"}]]
result
[{"who":"ada"},{"who":"bea"},{"who":"dot"}]

Eli's ancestors come back sorted, because the query asked for {"order": "who"}.

Step 5: Ask what is missing

Who has no children? Declare who is in the family, then use not to keep only the people with no parent fact of their own. ?_ means "anything, I don't care what":

["begin",
  ["relation", "person", ["name"]],
  ["relation", "parent", ["parent", "child"]],
  ["relation", "childless", ["name"]],
  ["fact", ["person", "ada"], ["person", "bea"], ["person", "cal"],
    ["person", "dot"], ["person", "eli"]],
  ["fact",
    ["parent", "ada", "bea"],
    ["parent", "ada", "cal"],
    ["parent", "bea", "dot"],
    ["parent", "dot", "eli"]],
  ["rule", ["childless", "?p"],
    ["person", "?p"],
    ["not", ["parent", "?p", "?_"]]],
  ["query", ["childless", "?name"]]]
result
[{"name":"cal"},{"name":"eli"}]

Step 6: Count descendants

A rule can count. Put aggregate/count in the rule's head, and Lion counts the matches for each ancestor:

["begin",
  ["relation", "parent", ["parent", "child"]],
  ["relation", "ancestor", ["ancestor", "person"]],
  ["relation", "descendants", ["ancestor", "count"]],
  ["fact",
    ["parent", "ada", "bea"],
    ["parent", "ada", "cal"],
    ["parent", "bea", "dot"],
    ["parent", "dot", "eli"]],
  ["rule", ["ancestor", "?a", "?p"], ["parent", "?a", "?p"]],
  ["rule", ["ancestor", "?a", "?p"],
    ["ancestor", "?a", "?mid"],
    ["parent", "?mid", "?p"]],
  ["rule", ["descendants", "?a", ["aggregate/count", "?p"]],
    ["ancestor", "?a", "?p"]],
  ["query", ["descendants", "?ancestor", "?count"], {"order": "-count"}]]
result
[
  {"ancestor":"ada","count":4},
  {"ancestor":"bea","count":2},
  {"ancestor":"dot","count":1}
]

Step 7: Collect answers into a list

A query gives one record per answer. To put answers inside a value of our own, we use find: it takes a template and a goal, and returns the template's value for every match, as a sorted list. Here the template is a pair, a person and the list of their children, and that list is a find too:

["begin",
  ["relation", "person", ["name"]],
  ["relation", "parent", ["parent", "child"]],
  ["fact", ["person", "ada"], ["person", "bea"], ["person", "cal"],
    ["person", "dot"], ["person", "eli"]],
  ["fact",
    ["parent", "ada", "bea"],
    ["parent", "ada", "cal"],
    ["parent", "bea", "dot"],
    ["parent", "dot", "eli"]],
  ["find",
    ["array/make", "?p", ["find", "?child", ["parent", "?p", "?child"]]],
    ["person", "?p"]]]
result
[
  ["ada",["bea","cal"]],
  ["bea",["dot"]],
  ["cal",[]],
  ["dot",["eli"]],
  ["eli",[]]
]

The inner find is asked once for each person. Cal and Eli have no children, so they get an empty list instead of being left out, which the count in step 6 could not do.

Step 8: Ask why

why explains a fact: which rule produced it, and from which facts. Ask why Ada is an ancestor of Eli:

["begin",
  ["relation", "parent", ["parent", "child"]],
  ["relation", "ancestor", ["ancestor", "person"]],
  ["fact",
    ["parent", "ada", "bea"],
    ["parent", "bea", "dot"],
    ["parent", "dot", "eli"]],
  ["rule", ["ancestor", "?a", "?p"], ["parent", "?a", "?p"]],
  ["rule", ["ancestor", "?a", "?p"],
    ["ancestor", "?a", "?mid"],
    ["parent", "?mid", "?p"]],
  ["why", ["ancestor", "ada", "eli"]]]
result
{
  "fact": ["ancestor","ada","eli"],
  "rule": [
    "rule",
    ["ancestor","?a","?p"],
    ["ancestor","?a","?mid"],
    ["parent","?mid","?p"]
  ],
  "because": [
    {
      "fact": ["ancestor","ada","dot"],
      "rule": [
        "rule",
        ["ancestor","?a","?p"],
        ["ancestor","?a","?mid"],
        ["parent","?mid","?p"]
      ],
      "because": [
        {
          "fact": ["ancestor","ada","bea"],
          "rule": ["rule",["ancestor","?a","?p"],["parent","?a","?p"]],
          "because": [{"fact":["parent","ada","bea"],"given":true}]
        },
        {"fact":["parent","bea","dot"],"given":true}
      ]
    },
    {"fact":["parent","dot","eli"],"given":true}
  ]
}

Read it from the outside in: Ada is an ancestor of Eli because she is an ancestor of Dot, who is Eli's parent, and so on down to facts that were given.

Step 9: Protect the tree

Nobody can be their own ancestor. An invariant tells the database a question that must never have an answer. Add it, then try a fact that would make Eli Ada's parent:

["begin",
  ["relation", "parent", ["parent", "child"]],
  ["relation", "ancestor", ["ancestor", "person"]],
  ["fact",
    ["parent", "ada", "bea"],
    ["parent", "bea", "dot"],
    ["parent", "dot", "eli"]],
  ["rule", ["ancestor", "?a", "?p"], ["parent", "?a", "?p"]],
  ["rule", ["ancestor", "?a", "?p"],
    ["ancestor", "?a", "?mid"],
    ["parent", "?mid", "?p"]],
  ["invariant", ["ancestor", "?x", "?x"], {"assert": "none"}],
  ["fact", ["parent", "eli", "ada"]]]
error
LogicError: Adding this fact breaks an invariant, so nothing changed. The invariant expected no answers but found 4, such as {"x":"ada"}: ["ancestor","?x","?x"].

The database refuses the fact and tells us why: with it, Ada would be her own ancestor. The tree stays as it was. Change the last fact to ["parent", "eli", "fay"] and the program succeeds.

What we built

We stored facts, derived new ones with rules, followed a relationship through any number of generations, asked about what was missing, counted, collected answers into lists, explained an answer, and guarded the data with an invariant. Every part was plain JSON.

Next, Run an order desk keeps changing data consistent over time. For every logic form and its exact rules, see Logic forms; to learn how the database computes answers, read How Lion answers logic questions.

Tutorial · learning-oriented

Run an order desk

Track orders whose status changes over time, keep the data consistent with an invariant, and save the whole desk as a Lion program.

In this tutorial we will run a small order desk. Orders change status as they move along, the desk refuses changes that would leave the data inconsistent, and at the end we save everything to a file. We will build on the logic forms from Build a family tree.

Step 1: Keep one row per order

Each order has an id, a customer, a status, and an amount. Give the relation a key, {"key": "id"}, so it holds at most one row per id:

["begin",
  ["relation", "order", ["id", "customer", "status", "amount"], {"key": "id"}],
  ["fact",
    ["order", 1, "ana", "open", 30],
    ["order", 2, "ana", "open", 20],
    ["order", 3, "bo", "open", 50]],
  ["query", ["order", "?id", "?customer", "?status", "?amount"], {"order": "id"}]]
result
[
  {"id":1,"customer":"ana","status":"open","amount":30},
  {"id":2,"customer":"ana","status":"open","amount":20},
  {"id":3,"customer":"bo","status":"open","amount":50}
]

Step 2: Change an order's status

To move order 1 along, add a fact with the same id. Because id is the key, the new row replaces the old one instead of sitting next to it:

["begin",
  ["relation", "order", ["id", "customer", "status", "amount"], {"key": "id"}],
  ["fact",
    ["order", 1, "ana", "open", 30],
    ["order", 2, "ana", "open", 20],
    ["order", 3, "bo", "open", 50]],
  ["fact", ["order", 1, "ana", "paid", 30]],
  ["query", ["order", "?id", "?customer", "?status", "?amount"], {"order": "id"}]]
result
[
  {"id":1,"customer":"ana","status":"paid","amount":30},
  {"id":2,"customer":"ana","status":"open","amount":20},
  {"id":3,"customer":"bo","status":"open","amount":50}
]

Step 3: Total what each customer owes

A rule with aggregate/sum in its head adds up the amounts of each customer's open orders:

["begin",
  ["relation", "order", ["id", "customer", "status", "amount"], {"key": "id"}],
  ["relation", "owed", ["customer", "total"]],
  ["fact",
    ["order", 1, "ana", "paid", 30],
    ["order", 2, "ana", "open", 20],
    ["order", 3, "bo", "open", 50]],
  ["rule", ["owed", "?c", ["aggregate/sum", "?amount"]],
    ["order", "?_", "?c", "open", "?amount"]],
  ["query", ["owed", "?customer", "?total"], {"order": "customer"}]]
result
[{"customer":"ana","total":20},{"customer":"bo","total":50}]

Change order 3 to "paid", and Bo drops out of the answer.

Step 4: Refuse to ship without an address

An order must not ship to a customer without an address. Store addresses, and add an invariant: a question that must never have an answer. Then try to ship Bo's order:

["begin",
  ["relation", "order", ["id", "customer", "status", "amount"], {"key": "id"}],
  ["relation", "address", ["customer", "street"], {"key": "customer"}],
  ["fact",
    ["order", 1, "ana", "paid", 30],
    ["order", 3, "bo", "open", 50]],
  ["fact", ["address", "ana", "1 Elm St"]],
  ["invariant",
    ["and", ["order", "?id", "?c", "shipped", "?_"], ["not", ["address", "?c", "?_"]]],
    {"assert": "none"}],
  ["fact", ["order", 3, "bo", "shipped", 50]]]
error
LogicError: Adding this fact breaks an invariant, so nothing changed. The invariant expected no answers but found 1, such as {"id":3,"c":"bo"}: ["and",["order","?id","?c","shipped","?_"],["not",["address","?c","?_"]]].

The desk refuses: the change would ship order 3 to a customer with no address. Nothing changed, so order 3 is still open.

Step 5: Make both changes at once

Bo sends an address. A single fact form can add the address and ship the order together. The invariant is checked once the whole form is done, so this succeeds:

["begin",
  ["relation", "order", ["id", "customer", "status", "amount"], {"key": "id"}],
  ["relation", "address", ["customer", "street"], {"key": "customer"}],
  ["fact",
    ["order", 1, "ana", "paid", 30],
    ["order", 3, "bo", "open", 50]],
  ["fact", ["address", "ana", "1 Elm St"]],
  ["invariant",
    ["and", ["order", "?id", "?c", "shipped", "?_"], ["not", ["address", "?c", "?_"]]],
    {"assert": "none"}],
  ["fact", ["address", "bo", "9 Oak Ave"], ["order", 3, "bo", "shipped", 50]],
  ["query", ["order", "?id", "?customer", "?status", "?_"], {"order": "id"}]]
result
[
  {"id":1,"customer":"ana","status":"paid"},
  {"id":3,"customer":"bo","status":"shipped"}
]

Step 6: Save the desk

["snapshot"] writes the whole database as a Lion program: its relations, facts, and invariant. Running that program rebuilds the desk exactly.

["begin",
  ["relation", "order", ["id", "customer", "status", "amount"], {"key": "id"}],
  ["relation", "address", ["customer", "street"], {"key": "customer"}],
  ["fact", ["order", 1, "ana", "paid", 30], ["order", 3, "bo", "shipped", 50]],
  ["fact", ["address", "ana", "1 Elm St"], ["address", "bo", "9 Oak Ave"]],
  ["invariant",
    ["and", ["order", "?id", "?c", "shipped", "?_"], ["not", ["address", "?c", "?_"]]],
    {"assert": "none"}],
  ["snapshot"]]
result
[
  "begin",
  [
    "relation",
    "order",
    ["id","customer","status","amount"],
    {"key":["id"]}
  ],
  [
    "relation",
    "address",
    ["customer","street"],
    {"key":["customer"]}
  ],
  [
    "fact",
    ["order",1,"ana","paid",30],
    ["order",3,"bo","shipped",50],
    ["address","ana","1 Elm St"],
    ["address","bo","9 Oak Ave"]
  ],
  [
    "invariant",
    [
      "and",
      ["order","?id","?c","shipped","?_"],
      ["not",["address","?c","?_"]]
    ],
    {"assert":"none"}
  ]
]

On your own machine, the lion command does this for you. Save the program from Step 5 as desk.json and run it with a database file; later programs then run against the saved desk, and the invariant still guards it:

bun add --dev @lionlang/cli
bun run lion desk.json --database store.json

What we built

We kept one row per order with a key, changed statuses by adding facts, totaled what customers owe, refused an inconsistent change with an invariant, made two changes together, and saved the desk as a Lion program.

To use these features in your own project, see Enforce rules on your data and Save and load a logic database. To understand why a change is all or nothing, read One set of rules for every feature.

Tutorial · learning-oriented

Sort an inbox

Describe the orders you expect with a schema, find what is wrong with the ones that do not fit, and let rules take the good ones apart.

In this tutorial we will sort an inbox of orders that arrive as JSON. Some are well formed and some are not. We will say what an order must be, see exactly where a bad one goes wrong, and write rules that keep the good ones and take them apart. We will build on the logic forms from Build a family tree.

Step 1: Say what an order is

A schema says what a value must be, and anything can be one. Write the record we expect, with a schema in place of each value: a function such as value/integer? for a value it accepts, and schema/anyOf for a choice. schema/fits? asks whether a value fits:

["begin",
  ["define", "Order",
    {"id": "value/integer?",
     "status": ["schema/anyOf", "open", "shipped"],
     "lines": ["schema/arrayOf",
       {"sku": "value/string?", "qty": "value/integer?"}]}],
  ["define", "mail",
    ["quote", {"id": 1, "status": "open", "lines": [{"sku": "tea", "qty": 2}]}]],
  ["schema/fits?", "mail", "Order"]]
result
true

The order fits: it has the three keys, and each value fits the schema under its key.

Step 2: Find what is wrong

The next order in the mail is a mess. schema/problems lists every place where a value does not fit:

["begin",
  ["define", "Order",
    {"id": "value/integer?",
     "status": ["schema/anyOf", "open", "shipped"],
     "lines": ["schema/arrayOf",
       {"sku": "value/string?", "qty": "value/integer?"}]}],
  ["define", "mail",
    ["quote", {"id": "2", "status": "opne", "lines": [{"sku": "tea"}], "gift": true}]],
  ["schema/problems", "mail", "Order"]]
result
[
  {"path":["gift"],"found":true},
  {"path":["id"],"expected":"value/integer?","found":"2"},
  {"path":["lines",0,"qty"],"expected":"value/integer?"},
  {
    "path": ["status"],
    "expected": ["schema/anyOf","open","shipped"],
    "found": "opne"
  }
]

There are four. Each has the path to the part that is wrong. The id and the status have the wrong value, so they show what was expected and what was found. The first line has no qty, so it shows only what was expected. And gift is a key the schema does not name, so it shows only what was found: a record fits a record with the same keys.

Step 3: Give the schemas names

schema declares a schema under a name, the way relation declares a relation. The name is then a predicate, and other schemas can use it. Let us also ask for more: a quantity must be above zero, which a lambda can say, and an order may have a note, which schema/optional allows:

["begin",
  ["schema", "Line",
    {"sku": "value/string?",
     "qty": ["schema/allOf", "value/integer?",
       ["lambda", ["n"], ["number/greaterThan", "n", 0]]]}],
  ["schema", "Order",
    {"id": "value/integer?",
     "status": ["schema/anyOf", "open", "shipped"],
     "lines": ["schema/arrayOf", "Line"],
     "note": ["schema/optional", "value/string?"]}],
  {"with a note": ["Order",
     ["quote", {"id": 1, "status": "open", "lines": [], "note": "gift"}]],
   "no tea": ["Order",
     ["quote", {"id": 1, "status": "open", "lines": [{"sku": "tea", "qty": 0}]}]]}]
result
{"with a note":true,"no tea":false}

Change the 0 to a 3, and the second order fits too.

Step 4: Keep the orders that fit

Now put the mail in a relation, one document per row. A relation call takes a schema for each column, so ["inbox", "Order"] would ask for the rows that are orders. We want more than that: the id and the status of each. A logic variable in a schema takes the value it meets, so a record with variables in it is a pattern. schema/allOf asks for both at once, and schema/open lets the pattern name only the keys it wants:

["begin",
  ["schema", "Line",
    {"sku": "value/string?",
     "qty": ["schema/allOf", "value/integer?",
       ["lambda", ["n"], ["number/greaterThan", "n", 0]]]}],
  ["schema", "Order",
    {"id": "value/integer?",
     "status": ["schema/anyOf", "open", "shipped"],
     "lines": ["schema/arrayOf", "Line"]}],
  ["relation", "inbox", ["doc"]],
  ["relation", "order", ["id", "status"], {"key": "id"}],
  ["fact",
    ["inbox", ["quote", {"id": 1, "status": "open",
      "lines": [{"sku": "tea", "qty": 2}, {"sku": "cup", "qty": 1}]}]],
    ["inbox", ["quote", {"id": 2, "status": "opne", "lines": []}]],
    ["inbox", ["quote", {"id": 3, "status": "shipped",
      "lines": [{"sku": "tea", "qty": 5}]}]]],
  ["rule", ["order", "?id", "?status"],
    ["inbox", ["schema/allOf", "Order",
      ["schema/open", {"id": "?id", "status": "?status"}]]]],
  ["query", ["order", "?id", "?status"], {"order": "id"}]]
result
[{"id":1,"status":"open"},{"id":3,"status":"shipped"}]

Orders 1 and 3 are kept. Order 2 says "opne", so it is not an order, and the rule passes over it.

Step 5: Say why the rest was rejected

A document that was passed over should not vanish. schema/problems gives a list, and in turns a list into rows, so a second rule records each problem of each document:

["begin",
  ["schema", "Line",
    {"sku": "value/string?",
     "qty": ["schema/allOf", "value/integer?",
       ["lambda", ["n"], ["number/greaterThan", "n", 0]]]}],
  ["schema", "Order",
    {"id": "value/integer?",
     "status": ["schema/anyOf", "open", "shipped"],
     "lines": ["schema/arrayOf", "Line"]}],
  ["relation", "inbox", ["doc"]],
  ["relation", "rejected", ["id", "where"]],
  ["fact",
    ["inbox", ["quote", {"id": 1, "status": "open",
      "lines": [{"sku": "tea", "qty": 2}, {"sku": "cup", "qty": 1}]}]],
    ["inbox", ["quote", {"id": 2, "status": "opne", "lines": []}]],
    ["inbox", ["quote", {"id": 4, "status": "open",
      "lines": [{"sku": "tea", "qty": 0}]}]]],
  ["rule", ["rejected", "?id", ["object/get", "?problem", "path"]],
    ["inbox", "?doc"],
    ["schema/fits?", "?doc", ["schema/open", {"id": "?id"}]],
    ["in", "?problem", ["schema/problems", "?doc", "Order"]]],
  ["query", ["rejected", "?id", "?where"], {"order": "id"}]]
result
[{"id":2,"where":["status"]},{"id":4,"where":["lines",0,"qty"]}]

Order 1 has no problems, so it has no rows. Here schema/fits? is a goal of its own: it checks a value that another goal bound, and binds ?id from it.

Step 6: Take the lines apart

Each order holds a list of lines. The element of in can be a pattern too, so one goal takes the list out of the order and the next takes each line apart. With the lines as rows, an aggregate can total the units of each product:

["begin",
  ["schema", "Line",
    {"sku": "value/string?",
     "qty": ["schema/allOf", "value/integer?",
       ["lambda", ["n"], ["number/greaterThan", "n", 0]]]}],
  ["schema", "Order",
    {"id": "value/integer?",
     "status": ["schema/anyOf", "open", "shipped"],
     "lines": ["schema/arrayOf", "Line"]}],
  ["relation", "inbox", ["doc"]],
  ["relation", "line", ["order", "sku", "qty"]],
  ["relation", "units", ["sku", "total"]],
  ["fact",
    ["inbox", ["quote", {"id": 1, "status": "open",
      "lines": [{"sku": "tea", "qty": 2}, {"sku": "cup", "qty": 1}]}]],
    ["inbox", ["quote", {"id": 2, "status": "opne", "lines": []}]],
    ["inbox", ["quote", {"id": 3, "status": "shipped",
      "lines": [{"sku": "tea", "qty": 5}]}]]],
  ["rule", ["line", "?order", "?sku", "?qty"],
    ["inbox", ["schema/allOf", "Order",
      ["schema/open", {"id": "?order", "lines": "?lines"}]]],
    ["in", {"sku": "?sku", "qty": "?qty"}, "?lines"]],
  ["rule", ["units", "?sku", ["aggregate/sum", "?qty"]],
    ["line", "?order", "?sku", "?qty"]],
  {"lines": ["find", ["array/make", "?order", "?sku", "?qty"],
     ["line", "?order", "?sku", "?qty"]],
   "units": ["query", ["units", "?sku", "?total"], {"order": "sku"}]}]
result
{
  "lines": [[1,"cup",1],[1,"tea",2],[3,"tea",5]],
  "units": [{"sku":"cup","total":1},{"sku":"tea","total":7}]
}

Step 7: Guard the shelf

The sorted orders live in a relation of their own. To make sure nothing else ever puts a bad row there, give the relation a schema. Every row, taken as a record of its columns, must then fit it, and a change that would add a row that does not is refused:

["begin",
  ["schema", "Shelved",
    {"id": "value/integer?", "status": ["schema/anyOf", "open", "shipped"]}],
  ["relation", "order", ["id", "status"], {"key": "id", "schema": "Shelved"}],
  ["fact", ["order", 1, "open"], ["order", 3, "shipped"]],
  ["fact", ["order", 2, "opne"]]]
error
LogicError: Adding this fact breaks an invariant, so nothing changed. The invariant expected no answers but found 1, such as {"id":2,"status":"opne"}: ["and",["order","?id","?status"],["not",["Shelved",{"id":"?id","status":"?status"}]]]. {"id":2,"status":"opne"} does not fit "Shelved": "status" must fit ["schema/anyOf","open","shipped"] but is "opne".

The message says which row does not fit, and where. Nothing changed: orders 1 and 3 are still on the shelf, and order 2 was not added.

What we built

We described an order with a schema, listed the problems of one that did not fit, named our schemas, kept the documents that fit with a rule, recorded why the others were rejected, took a list inside each order apart into rows, and guarded a relation with a schema.

To use these features in your own project, see Check the shape of data and Take data apart. For every rule in one place, read What fits a schema and Patterns in the reference. To understand why checking and taking apart are one thing, read One set of rules for every feature.

How-to guide · task-oriented

Run Lion from TypeScript

Evaluate Lion programs inside your own application, give them your values and functions, and handle their results and errors.

This guide shows how to evaluate Lion from a TypeScript or JavaScript project with @lionlang/core. It assumes you know the basics of Effect; every evaluation is an Effect you run.

Install the package

bun add @lionlang/core effect

Evaluate a program

Pass the program and an environment to run. The standard library, stdlib, is the usual environment. A program can be any JSON value, so it can come straight from JSON.parse, a database, or a request body.

import { Effect } from "effect";
import { run } from "@lionlang/core/evaluation/evaluate";
import { stdlib } from "@lionlang/core/modules";

const program = JSON.parse('["number/add", 1, 2]');
const result = await Effect.runPromise(run(program, stdlib));
// => 3

Give programs your own values and functions

Spread stdlib into an object and add names. Any value can be bound. A function can return a plain value or an Effect; Lion waits for an Effect to finish.

const env = {
  ...stdlib,
  taxRate: 0.08,
  "shop/price": (sku: string) => Effect.succeed(sku === "lamp" ? 120 : 35),
};

await Effect.runPromise(
  run(["number/multiply", ["shop/price", "lamp"], ["number/add", 1, "taxRate"]], env)
);
// => 129.6

Prefix your names with a module, as the standard library does, so they never collide with Lion's names or with strings in your data.

Handle errors

A failed evaluation is a typed failure, not a thrown exception. Run with Effect.runPromiseExit, or catch by tag:

const safe = run(["number/add", "one", 2], stdlib).pipe(
  Effect.catchTag("LogicError", (error) => Effect.succeed(`Bad input: ${error.message}`))
);

See Errors for every error a program can fail with.

Keep a logic database between runs

Each run starts with an empty logic database. To keep relations, facts, rules, and invariants across runs, create a LogicDatabase and pass it to each run:

import { LogicDatabase } from "@lionlang/core/logic/database";

const database = new LogicDatabase();
await Effect.runPromise(run(["begin",
  ["relation", "edge", ["from", "to"]],
  ["fact", ["edge", "a", "b"]]], stdlib, { database }));

await Effect.runPromise(run(["query", ["edge", "a", "?to"]], stdlib, { database }));
// => [{ to: "b" }]

Later runs see the database's relations by name, so they can query edge without declaring it again. Names you bind in the environment win over relations with the same name.

How-to guide · task-oriented

Run programs from the command line

Evaluate Lion files with the lion command, keep a logic database in a file between runs, and open the graph editor.

This guide shows how to use the lion command from @lionlang/cli.

Install the command

bun add --dev @lionlang/cli

In a project, run it with bun run lion. Installed globally, it is just lion.

Evaluate a file, inline expression, or standard input

Pass a JSON file, pass --eval (-e) for a quick one-liner, or pipe JSON into standard input (explicitly with - or implicitly when piped). Inject top-level JSON inputs with repeatable --bind (-b) or --bind-file flags, keeping exact numbers intact:

bun run lion add.json
bun run lion -e '["number/add", 1, 2]'
bun run lion -b tax=0.07 --bind-file order=order.json price.json
echo '["number/add", 1, 2]' | bun run lion -

If the input is not valid JSON, or the program fails, lion prints the error and exits with status 1.

Check a program without running it

lion check reports malformed forms, misspelled names, wrong-arity calls, invalid relation/query/invariant options, unsafe rule heads or find templates, logic variables in ground facts, unreachable or non-exhaustive match cases, unreachable cond branches after else, duplicate lambda parameters, near-miss bare call heads, and Lion lints with JSON pointers. Pass --database or --bind/--bind-file to validate against external relations, schemas, and inputs read-only:

bun run lion check program.json
bun run lion check --database store.json -e '["query", ["edge", "a", "?to"]]'
bun run lion check --bind-file order=order.json price.json

Keep and inspect a logic database in a file

Add --database with a path. Pass multiple step files to run them atomically in one invocation, pass --read-only (-r) for exploratory runs without touching disk, or run lion inspect to summarize a database's relations, schemas, invariants, and counts without reading the raw snapshot:

bun run lion 00-core.json 01-frame.json 02-facts.json --database store.json
bun run lion checks.json --database store.json
bun run lion --read-only --database store.json -e '["begin", ["fact", ["edge", "a", "z"]], ["find", "?x", ["path", "a", "?x"]]]'
bun run lion inspect store.json --derived
  • A database file that does not exist yet starts empty.
  • The file is a snapshot: an ordinary Lion program, one form and one fact per line, so it diffs well in version control.
  • Read-only queries that make no committed changes do not rewrite an existing database file, so parallel queries stay fast and safe.
  • If any program fails, for example because it would break an invariant, the file is left as it was.
  • Running the same setup again keeps one copy of each rule and invariant.

Open the graph editor

bun run lion repl
bun run lion repl --host 0.0.0.0 --port 8080

The editor listens on 127.0.0.1:3000 unless you pass --host or --port. Open the address it prints, then open a .json program.

How-to guide · task-oriented

Branch on a value's shape

Choose what to do with a value based on its type or its structure, with match and cond.

This guide shows how to pick a branch based on what a value is. Use match when the choice depends on the value's type or structure, and cond when it depends on conditions you compute. The patterns of match are schemas.

Branch on a value's type

Give match the value, then pairs of a schema and a function, then a fallback function. A predicate is a schema: the first one that returns true picks its function, which receives the value:

["begin",
  ["define", "describe",
    ["lambda", ["value"],
      ["match", "value",
        ["value/number?", ["lambda", ["n"], "a number"]],
        ["value/string?", ["lambda", ["s"], ["string/concat", "a string: ", "s"]]],
        ["value/array?", ["lambda", ["xs"], "a list"]],
        ["lambda", ["other"], "something else"]]]],
  ["array/map", ["quote", [7, "hi", [1, 2], null]], "describe"]]
result
["a number","a string: hi","a list","something else"]

Branch on a record's structure

A record is a schema too. A record fits it when it has the same keys, with a value that fits the schema under each. A plain value fits a value equal to it, so a field can pick the branch. Records nest, and schema/open fits a record whatever other keys it has:

["begin",
  ["define", "route",
    ["lambda", ["message"],
      ["match", "message",
        [{"type": "order", "order": {"id": "value/number?"}},
         ["lambda", ["m"], ["object/get-path", "m", "order.id"]]],
        [{"type": ["schema/anyOf", "ping", "hello"]},
         ["lambda", ["m"], "pong"]],
        [["schema/open", {"type": "note"}],
         ["lambda", ["m"], ["object/get", "m", "text"]]],
        ["lambda", ["m"], "unknown message"]]]],
  ["array/map",
    ["quote", [
      {"type": "order", "order": {"id": 42}},
      {"type": "ping"},
      {"type": "note", "text": "call back", "from": "ada"},
      {"type": "order", "order": {"id": "x"}}]],
    "route"]]
result
[42,"pong","call back","unknown message"]

A predicate that fails, or returns something other than true, counts as no match, so a pattern never crashes on data of the wrong type. A string in a pattern is a name first, as everywhere: "order" is the string unless something is bound to order, and ["quote", "order"] is always the string.

Branch on computed conditions

When the choice depends on comparisons, list condition and result pairs in cond, with an optional else at the end:

["begin",
  ["define", "grade",
    ["lambda", ["score"],
      ["cond",
        [["number/greaterThanOrEqualTo", "score", 90], "A"],
        [["number/greaterThanOrEqualTo", "score", 75], "B"],
        ["else", "C"]]]],
  ["array/map", ["array/make", 95, 80, 40], "grade"]]
result
["A","B","C"]

Without an else, a cond with no matching condition returns null. Conditions use JavaScript truthiness: false, null, 0, and "" do not match, and every list and record does.

How-to guide · task-oriented

Transform lists

Make lists, map over them, filter them, flatten them, and fold them into a single value.

This guide shows how to work with lists using the array module and lambdas.

Make a list

An array in a program is a call, so [1, 2, 3] on its own fails: 1 is not a function. Make a list with array/make, which evaluates its arguments, or with quote, which takes the list as written:

{"made": ["array/make", 1, ["number/add", 1, 1], 3],
 "quoted": ["quote", [1, ["number/add", 1, 1], 3]],
 "range": ["array/range", 0, 5]}
result
{
  "made": [1,2,3],
  "quoted": [1,["number/add",1,1],3],
  "range": [0,1,2,3,4]
}

Change every item

Pass a list and a function to array/map:

["array/map", ["array/range", 1, 6],
  ["lambda", ["n"], ["number/multiply", "n", "n"]]]
result
[1,4,9,16,25]

Keep some items

Pass a list and a predicate to array/filter. Its function gives true or false, as a condition does:

["array/filter", ["array/range", 1, 11],
  ["lambda", ["n"], ["number/greaterThan", "n", 6]]]
result
[7,8,9,10]

Reverse and sort

array/reverse puts items in reverse order. array/sort puts items in ascending canonical order, or stably sorts by a two-argument predicate that says when the first item comes before the second:

{"reversed": ["array/reverse", ["array/make", "a", "b", "c"]],
 "sorted": ["array/sort", ["array/make", 3, 1, 4, 1, 5]],
 "descending": ["array/sort", ["array/make", 3, 1, 4, 1, 5], "number/greaterThan"]}
result
{
  "reversed": ["c","b","a"],
  "sorted": [1,1,3,4,5],
  "descending": [5,4,3,1,1]
}

Combine items into one value

array/reduce takes a list, a starting value, and a function of the running value and the next item:

["array/reduce", ["array/make", 3, 9, 4], 0,
  ["lambda", ["sum", "n"], ["number/add", "sum", "n"]]]
result
16

For sums, counts, and other common totals, the aggregate module is shorter: ["aggregate/sum", list].

Take lists apart

{"first": ["array/head", ["array/make", "a", "b", "c"]],
 "rest": ["array/tail", ["array/make", "a", "b", "c"]],
 "length": ["array/length", ["array/make", "a", "b", "c"]],
 "hasB": ["array/includes?", ["array/make", "a", "b", "c"], "b"],
 "joined": ["array/concat", ["array/make", 1], ["array/make", 2, 3]]}
result
{
  "first": "a",
  "rest": ["b","c"],
  "length": 3,
  "hasB": true,
  "joined": [1,2,3]
}

An empty list has no first item and no rest, so array/head and array/tail fail on one, as Scheme's car and cdr do. Ask for its length first, or use array/slice, which gives what part there is:

["array/head", ["array/make"]]
error
LogicError: "array/head" takes a list that is not empty as argument 1 but got [].
["begin",
  ["define", "first", ["lambda", ["items", "otherwise"],
    ["cond", [["number/equals?", ["array/length", "items"], 0], "otherwise"],
             ["else", ["array/head", "items"]]]]],
  {"of a list": ["first", ["array/make", "a", "b"], "none"],
   "of an empty one": ["first", ["array/make"], "none"],
   "a slice": ["array/slice", ["array/make"], 0, 1]}]
result
{"of a list":"a","of an empty one":"none","a slice":[]}

How-to guide · task-oriented

Build and run code as data

Hold a program as data, assemble one from parts, and run it with eval.

This guide shows how to treat Lion code as a value: keep it from running with quote, build it with ordinary functions, and run it with eval.

Hold code without running it

quote returns its argument exactly as written:

["quote", ["number/add", 1, 2]]
result
["number/add",1,2]

Run code you hold

eval evaluates its argument, then evaluates the result as a program:

["begin",
  ["define", "formula", ["quote", ["number/multiply", "price", 2]]],
  ["define", "price", 21],
  ["eval", "formula"]]
result
42

The code runs where eval is, so it sees the names defined there, including price, defined after the formula.

Assemble a program from parts

A program is a list, so build it with list functions. Here a list of numbers becomes a chain of additions:

["begin",
  ["define", "program",
    ["array/reduce", ["array/make", 2, 3, 4], 0,
      ["lambda", ["code", "n"],
        ["array/make", ["quote", "number/add"], "code", "n"]]]],
  {"program": "program", "result": ["eval", "program"]}]
result
{
  "program": ["number/add",["number/add",["number/add",0,2],3],4],
  "result": 9
}

The name is quoted because array/make evaluates its arguments: unquoted, "number/add" would become the function itself, which is not JSON, so eval would refuse the program.

Keep programs in records

Records evaluate their values, so quote programs you store as configuration and run the one you need:

["begin",
  ["define", "rules", {
    "short": ["quote", ["number/lessThan", ["string/length", "name"], 5]],
    "long": ["quote", ["number/greaterThan", ["string/length", "name"], 8]]}],
  ["define", "name", "Lion"],
  {"short": ["eval", ["object/get", "rules", "short"]],
   "long": ["eval", ["object/get", "rules", "long"]]}]
result
{"short":true,"long":false}

How-to guide · task-oriented

Query with conditions and computed values

Narrow answers with comparisons, compute new values in rules and queries, choose between values, combine alternatives, and look inside lists.

This guide shows how to go beyond matching facts: filter answers with conditions, compute values, accept alternatives, and match items of a list.

Filter answers with a condition

Call a function that answers true or false on a logic variable, and it becomes a filter. Combine goals with and:

["begin",
  ["relation", "order", ["id", "amount"]],
  ["fact", ["order", 1, 30], ["order", 2, 120], ["order", 3, 75]],
  ["query",
    ["and", ["order", "?id", "?amount"], ["number/greaterThan", "?amount", 50]],
    {"order": "id"}]]
result
[{"id":2,"amount":120},{"id":3,"amount":75}]

A filter runs as soon as its variables are bound, so it can come before the goal that binds them. Filters that are ready together run in the order written. When some values would make a filter fail, put a guard before it:

["begin",
  ["relation", "reading", ["sensor", "value"]],
  ["fact", ["reading", "s1", 21], ["reading", "s2", "offline"], ["reading", "s3", 34]],
  ["query",
    ["and", ["reading", "?sensor", "?value"],
      ["value/number?", "?value"],
      ["number/greaterThan", "?value", 30]]]]
result
[{"sensor":"s3","value":34}]

Compute a value

Use = to bind a variable to a computed value:

["begin",
  ["relation", "order", ["id", "amount"]],
  ["fact", ["order", 1, 30], ["order", 2, 120]],
  ["query",
    ["and", ["order", "?id", "?amount"],
      ["=", "?withTax", ["number/multiply", "?amount", 1.25]]],
    {"order": "id"}]]
result
[
  {"id":1,"amount":30,"withTax":37.5},
  {"id":2,"amount":120,"withTax":150}
]

In a rule, a computed value can also go straight into the head:

["begin",
  ["relation", "user", ["id", "first", "last"]],
  ["relation", "fullName", ["id", "name"]],
  ["fact", ["user", 1, "Ada", "Lovelace"], ["user", 2, "Alan", "Turing"]],
  ["rule", ["fullName", "?id", ["string/concat", ["string/concat", "?first", " "], "?last"]],
    ["user", "?id", "?first", "?last"]],
  ["query", ["fullName", "?id", "?name"], {"order": "id"}]]
result
[{"id":1,"name":"Ada Lovelace"},{"id":2,"name":"Alan Turing"}]

Choose between values

cond, match, and records work on logic variables too. Each waits until its variables are bound, then computes what it would with the values in place:

["begin",
  ["relation", "order", ["id", "amount"]],
  ["fact", ["order", 1, 30], ["order", 2, 120]],
  ["query",
    ["and", ["order", "?id", "?amount"],
      ["=", "?summary",
        {"size": ["cond", [["number/greaterThan", "?amount", 100], "large"], ["else", "small"]],
         "withTax": ["number/multiply", "?amount", 1.25]}]],
    {"order": "id"}]]
result
[
  {"id":1,"amount":30,"summary":{"size":"small","withTax":37.5}},
  {"id":2,"amount":120,"summary":{"size":"large","withTax":150}}
]

Your own lambdas work the same way, including ones that branch or call themselves:

["begin",
  ["define", "factorial",
    ["lambda", ["n"],
      ["cond", [["number/lessThan", "n", 2], 1],
        ["else", ["number/multiply", "n", ["factorial", ["number/subtract", "n", 1]]]]]]],
  ["query",
    ["and", ["in", "?n", ["array/range", 1, 6]], ["=", "?f", ["factorial", "?n"]]]]]
result
[
  {"n":1,"f":1},
  {"n":2,"f":2},
  {"n":3,"f":6},
  {"n":4,"f":24},
  {"n":5,"f":120}
]

Leave answers out

not takes any goal: a relation call, a filter, or goals combined with and and or:

["begin",
  ["relation", "order", ["id", "amount"]],
  ["relation", "refunded", ["id"]],
  ["fact", ["order", 1, 30], ["order", 2, 120], ["order", 3, 75]],
  ["fact", ["refunded", 3]],
  ["query",
    ["and", ["order", "?id", "?amount"],
      ["not", ["or", ["refunded", "?id"], ["number/lessThan", "?amount", 50]]]]]]
result
[{"id":2,"amount":120}]

Accept alternatives

or holds when any of its goals does:

["begin",
  ["relation", "order", ["id", "status"]],
  ["fact", ["order", 1, "open"], ["order", 2, "paid"], ["order", 3, "held"]],
  ["query",
    ["or", ["order", "?id", "open"], ["order", "?id", "held"]],
    {"order": "id"}]]
result
[{"id":1},{"id":3}]

Match items of a list

When a fact holds a list, in binds a variable to each item:

["begin",
  ["relation", "post", ["id", "tags"]],
  ["fact",
    ["post", "p1", ["array/make", "lisp", "json"]],
    ["post", "p2", ["array/make", "json", "logic"]]],
  ["query",
    ["and", ["post", "?post", "?tags"], ["in", "json", "?tags"]],
    {"order": "post"}]]
result
[
  {"post":"p1","tags":["lisp","json"]},
  {"post":"p2","tags":["json","logic"]}
]

With an unbound first argument, in binds it to each item; with a bound one, it tests membership, as above.

Keep goals safe

Every variable in a filter, a computed value, or a not must be bound by a relation, =, in, or a schema/fits? whose schema lists the values it allows somewhere in the same goal. Otherwise there would be infinitely many answers, so Lion refuses the goal and names the variable:

["query", ["number/greaterThan", "?amount", 50]]
error
LogicError: Unsafe goal ["number/greaterThan","?amount",50]: ?amount must first be bound by a relation, "=", "in", or "schema/fits?", or typed by a schema that says what kind its values are, such as value/integer?.

How-to guide · task-oriented

Use answers as values

Ask the database from any expression: collect answers into a list with find, test a goal in cond, and use a relation as a predicate.

This guide shows how to use what the database knows inside ordinary expressions, in plain code and inside rules.

Collect answers into a list

find takes a template and a goal, and returns the template's value for every match of the goal, sorted:

["begin",
  ["relation", "score", ["player", "points"]],
  ["fact", ["score", "ana", 12], ["score", "bo", 30], ["score", "cy", 30]],
  {"players": ["find", "?player", ["score", "?player", "?_"]],
   "by points": ["find", ["array/make", "?points", "?player"], ["score", "?player", "?points"]],
   "best": ["aggregate/max", ["find", "?points", ["score", "?_", "?points"]]]}]
result
{
  "players": ["ana","bo","cy"],
  "by points": [[12,"ana"],[30,"bo"],[30,"cy"]],
  "best": 30
}

The result is a plain list, so every list function works on it. Where query returns one record per answer for you to read, find returns exactly the values you ask for.

Test a goal

A goal is true when it has a match and false when it has none. Use it wherever a value is needed, such as a cond condition or a value of a record:

["begin",
  ["relation", "member", ["name", "plan"]],
  ["relation", "blocked", ["name"]],
  ["fact", ["member", "ana", "pro"], ["member", "bo", "free"]],
  ["fact", ["blocked", "bo"]],
  ["define", "access",
    ["lambda", ["who"],
      ["cond",
        [["blocked", "who"], "none"],
        [["member", "who", "pro"], "full"],
        [["member", "who", "?_"], "limited"],
        ["else", "guest"]]]],
  {"ana": ["access", "ana"],
   "bo": ["access", "bo"],
   "zed": ["access", "zed"],
   "anyone blocked": ["blocked", "?_"]}]
result
{"ana":"full","bo":"none","zed":"guest","anyone blocked":true}

A goal with a variable asks whether anything matches. Give a variable a name when the goal joins on it, as in ["and", ["member", "?m", "pro"], ["blocked", "?m"]].

Use a relation as a predicate

A relation is a function that builds a goal, so it works as the predicate of match and of functions that take one:

["begin",
  ["relation", "vowel", ["letter"]],
  ["fact", ["vowel", "a"], ["vowel", "e"], ["vowel", "i"], ["vowel", "o"], ["vowel", "u"]],
  {"flags": ["array/map", ["array/make", "l", "i", "o", "n"], "vowel"],
   "kind": ["match", "o",
     ["vowel", ["lambda", ["letter"], "a vowel"]],
     ["lambda", ["letter"], "a consonant"]]}]
result
{"flags":[false,true,true,false],"kind":"a vowel"}

Ask from inside a rule

In a rule or query the same expressions are asked once for each answer, with the answer's variables in place. A variable that only the question mentions, such as ?child here, belongs to the question:

["begin",
  ["relation", "person", ["name"]],
  ["relation", "parent", ["parent", "child"]],
  ["relation", "profile", ["name", "summary"]],
  ["fact", ["person", "ada"], ["person", "ben"], ["person", "cy"]],
  ["fact", ["parent", "ada", "ben"], ["parent", "ada", "cy"]],
  ["rule",
    ["profile", "?p",
      {"children": ["find", "?child", ["parent", "?p", "?child"]],
       "kind": ["cond", [["parent", "?p", "?_"], "has children"], ["else", "no children"]]}],
    ["person", "?p"]],
  ["query", ["profile", "?name", "?summary"], {"order": "name"}]]
result
[
  {
    "name": "ada",
    "summary": {"children":["ben","cy"],"kind":"has children"}
  },
  {"name":"ben","summary":{"children":[],"kind":"no children"}},
  {"name":"cy","summary":{"children":[],"kind":"no children"}}
]

A lambda that asks works in both places, because its body is asked wherever it runs:

["begin",
  ["relation", "person", ["name"]],
  ["relation", "parent", ["parent", "child"]],
  ["fact", ["person", "ada"], ["person", "ben"]],
  ["fact", ["parent", "ada", "ben"], ["parent", "ada", "cy"]],
  ["define", "children", ["lambda", ["p"], ["find", "?c", ["parent", "p", "?c"]]]],
  {"in plain code": ["children", "ada"],
   "in a query":
     ["query", ["and", ["person", "?p"], ["=", "?kids", ["children", "?p"]]], {"order": "p"}]}]
result
{
  "in plain code": ["ben","cy"],
  "in a query": [{"p":"ada","kids":["ben","cy"]},{"p":"ben","kids":[]}]
}

Keep a goal as a goal

define, and, or, not, and lambdas do not ask a goal: they keep it, so you can name goals and build bigger ones. Here the program's result is the goal itself:

["begin",
  ["relation", "member", ["name", "plan"]],
  ["define", "is-pro", ["member", "?who", "pro"]],
  ["and", "is-pro", ["not", ["member", "?who", "free"]]]]
result
["and",["member","?who","pro"],["not",["member","?who","free"]]]

A goal is asked only where a value is needed. A record holds values, so it asks. To get a goal's truth on its own, give the goal to value/identity:

["begin",
  ["relation", "member", ["name", "plan"]],
  ["fact", ["member", "ana", "pro"]],
  ["define", "is-pro", ["member", "?who", "pro"]],
  {"in a record": "is-pro",
   "its truth": ["value/identity", "is-pro"],
   "its answers": ["query", "is-pro"]}]
result
{
  "in a record": true,
  "its truth": true,
  "its answers": [{"who":"ana"}]
}

Ask what would hold after a change

assuming asks a question of the database as it would be after some fact, retract, and rule forms, and leaves the database as it is. In a rule it is asked for each answer, so a rule can try a change for every candidate. Here each shift that, given to one more person, would cover every day with two people:

["begin",
  ["relation", "person", ["name"]],
  ["relation", "day", ["name"]],
  ["relation", "shift", ["person", "day"]],
  ["relation", "short", ["day"]],
  ["relation", "fixes", ["person", "day"]],
  ["fact", ["person", "ana"], ["person", "bo"], ["person", "cy"], ["day", "mon"], ["day", "tue"]],
  ["fact", ["shift", "ana", "mon"], ["shift", "bo", "mon"], ["shift", "ana", "tue"]],
  ["rule", ["short", "?d"],
    ["day", "?d"],
    ["number/lessThan", ["aggregate/count", ["find", "?p", ["shift", "?p", "?d"]]], 2]],
  ["rule", ["fixes", "?p", "?d"],
    ["person", "?p"], ["short", "?d"], ["not", ["shift", "?p", "?d"]],
    ["assuming", ["fact", ["shift", "?p", "?d"]], ["not", ["short", "?_"]]]],
  {"short now": ["find", "?d", ["short", "?d"]],
   "who would fix it": ["query", ["fixes", "?person", "?day"], {"order": "person"}]}]
result
{
  "short now": ["tue"],
  "who would fix it": [{"person":"bo","day":"tue"},{"person":"cy","day":"tue"}]
}

How-to guide · task-oriented

Sort, page, and check query answers

Order answers by one or more variables, take a page of them, and make a query fail when it finds too few or too many.

This guide shows how to use query options, the record after a query's goal.

Sort answers

Give "order" a variable name, or a list of them to break ties. A leading - sorts that variable from largest to smallest:

["begin",
  ["relation", "score", ["player", "points"]],
  ["fact", ["score", "ana", 12], ["score", "bo", 30], ["score", "cy", 30], ["score", "dee", 7]],
  ["query", ["score", "?player", "?points"], {"order": ["-points", "player"]}]]
result
[
  {"player":"bo","points":30},
  {"player":"cy","points":30},
  {"player":"ana","points":12},
  {"player":"dee","points":7}
]

Take a page

"offset" skips answers and "limit" caps how many come back. Sort first, so pages are stable:

["begin",
  ["relation", "score", ["player", "points"]],
  ["fact", ["score", "ana", 12], ["score", "bo", 30], ["score", "cy", 30], ["score", "dee", 7]],
  ["query", ["score", "?player", "?points"], {"order": "-points", "offset": 1, "limit": 2}]]
result
[{"player":"cy","points":30},{"player":"ana","points":12}]

Fail when there are no answers, or some

"assert": "some" makes the query fail when it has no answers, and "assert": "none" when it has any. Use it to stop a program early when data is not as expected:

["begin",
  ["relation", "score", ["player", "points"]],
  ["fact", ["score", "ana", 12]],
  ["query", ["score", "?player", "?points"], {"assert": "none"}]]
error
LogicError: The query expected no answers but found 1, such as {"player":"ana","points":12}: ["score","?player","?points"].

The assertion sees every answer, before offset and limit. To keep a check like this in force after every change, use an invariant.

  • Query options describes each option and the order of values across types.

How-to guide · task-oriented

Follow relationships of any length

Derive paths, reachability, and hierarchies with recursive rules, and write them so queries stay fast.

This guide shows how to follow a relationship through any number of steps, such as routes through a network or managers up an org chart.

Write the two rules

A path is an edge, or a path followed by an edge. Write one rule for each case:

["begin",
  ["relation", "edge", ["from", "to"]],
  ["relation", "path", ["from", "to"]],
  ["fact", ["edge", "a", "b"], ["edge", "b", "c"], ["edge", "c", "d"]],
  ["rule", ["path", "?x", "?y"], ["edge", "?x", "?y"]],
  ["rule", ["path", "?x", "?z"], ["path", "?x", "?y"], ["edge", "?y", "?z"]],
  ["query", ["path", "a", "?to"], {"order": "to"}]]
result
[{"to":"b"},{"to":"c"},{"to":"d"}]

Cycles are fine: evaluation stops when no new facts appear.

Put the recursion first when you ask from a known start

When a query gives the start, as in ["path", "a", "?to"], Lion only derives what that query can reach. Writing the recursive goal first, ["path", "?x", "?y"], ["edge", "?y", "?z"], keeps every step anchored at that start. This query along a 3,000-node chain stays fast:

["begin",
  ["relation", "edge", ["from", "to"]],
  ["relation", "path", ["from", "to"]],
  ["rule", ["edge", "?n", ["number/add", "?n", 1]], ["in", "?n", ["array/range", 0, 3000]]],
  ["rule", ["path", "?x", "?y"], ["edge", "?x", "?y"]],
  ["rule", ["path", "?x", "?z"], ["path", "?x", "?y"], ["edge", "?y", "?z"]],
  ["query", ["path", 2997, "?to"]]]
result
[{"to":2998},{"to":2999},{"to":3000}]

Written the other way, ["edge", "?x", "?y"], ["path", "?y", "?z"], the rule asks about every node along the way, which can cost as much as deriving every path. Goal-directed evaluation explains why.

Carry a value along the path

A recursive rule cannot compute a value in its head that its own body then reads to compute the next, because that could go on forever. To carry a distance or a route, aggregate it with aggregate/min, aggregate/max, aggregate/shortest, or aggregate/union, whose values only move one way:

["begin",
  ["relation", "road", ["from", "to", "km"]],
  ["relation", "dist", ["to", "km"]],
  ["fact", ["road", "a", "b", 4], ["road", "a", "c", 1], ["road", "c", "b", 2], ["road", "b", "d", 5]],
  ["rule", ["dist", "?to", ["aggregate/min", "?km"]], ["road", "a", "?to", "?km"]],
  ["rule", ["dist", "?to", ["aggregate/min", ["number/add", "?d", "?km"]]],
    ["dist", "?via", "?d"], ["road", "?via", "?to", "?km"]],
  ["query", ["dist", "?to", "?km"], {"order": "km"}]]
result
[{"to":"c","km":1},{"to":"b","km":3},{"to":"d","km":8}]

For weighted shortest paths with the route itself, graph/shortestPath is simpler.

How-to guide · task-oriented

Find what is missing

Ask for things that have no matching fact, such as customers without orders or tasks without an owner.

This guide shows how to use not to find what lacks something.

Keep only what has no match

Start from a relation that lists every candidate, then rule out the ones that have a match. ?_ stands for any value:

["begin",
  ["relation", "customer", ["name"]],
  ["relation", "order", ["id", "customer"]],
  ["fact", ["customer", "ana"], ["customer", "bo"], ["customer", "cy"]],
  ["fact", ["order", 1, "ana"], ["order", 2, "cy"]],
  ["query", ["and", ["customer", "?name"], ["not", ["order", "?_", "?name"]]]]]
result
[{"name":"bo"}]

Name the result with a rule

To reuse the answer, derive it into a relation of its own:

["begin",
  ["relation", "task", ["id"]],
  ["relation", "owner", ["task", "person"]],
  ["relation", "unowned", ["task"]],
  ["fact", ["task", 1], ["task", 2], ["task", 3]],
  ["fact", ["owner", 2, "ana"]],
  ["rule", ["unowned", "?t"], ["task", "?t"], ["not", ["owner", "?t", "?_"]]],
  ["query", ["unowned", "?task"], {"order": "task"}]]
result
[{"task":1},{"task":3}]

Rule out a combination

The goal under not is a question of its own, so it can join relations. A variable that appears nowhere else in the query, such as ?paper here, belongs to the question: it is not part of the answer. This finds the authors none of whose papers is cited:

["begin",
  ["relation", "author", ["person", "paper"]],
  ["relation", "cites", ["paper", "cited"]],
  ["fact", ["author", "ann", "p1"], ["author", "bob", "p2"], ["author", "cyd", "p3"]],
  ["fact", ["cites", "p1", "p3"], ["cites", "p3", "p1"]],
  ["query",
    ["and", ["author", "?person", "?_"],
      ["not", ["and", ["author", "?person", "?paper"], ["cites", "?_", "?paper"]]]]]]
result
[{"person":"bob"}]

Give a filter its variables

A relation goal can find values for a variable, but a filter cannot: it needs every variable it mentions. Here nothing binds ?amount, so Lion refuses the query:

["begin",
  ["relation", "order", ["id", "amount"]],
  ["query", ["and", ["order", "?id", "?_"], ["not", ["number/greaterThan", "?amount", 100]]]]]
error
LogicError: Unsafe goal ["not",["number/greaterThan","?amount",100]]: ?amount must first be bound by a relation, "=", "in", or "schema/fits?", or typed by a schema that says what kind its values are, such as value/integer?.

Recurse through negation with well-founded semantics

In plain Datalog rules, a pure not goal can recurse through its own relation. Lion evaluates such cycles under three-valued well-founded semantics (Van Gelder's alternating fixpoint): a positive atom matches definitely true rows, not matches definitely false rows, and cyclic rows that are neither true nor false stay undecided:

["begin",
  ["relation", "move", ["from", "to"]],
  ["relation", "pos", ["node"]],
  ["relation", "win", ["node"]],
  ["fact",
    ["move", "a", "b"], ["move", "b", "a"], ["move", "b", "c"],
    ["move", "c", "d"], ["move", "e", "f"], ["move", "f", "g"], ["move", "g", "e"]],
  ["rule", ["pos", "?x"], ["move", "?x", "?_"]],
  ["rule", ["pos", "?y"], ["move", "?_", "?y"]],
  ["rule", ["win", "?x"], ["move", "?x", "?y"], ["not", ["win", "?y"]]],
  {"won": ["find", "?x", ["win", "?x"]],
   "lost": ["find", "?x", ["and", ["pos", "?x"], ["not", ["win", "?x"]]]],
   "drawn": ["find", "?x", ["and", ["pos", "?x"], ["boolean/not", ["win", "?x"]], ["boolean/not", ["not", ["win", "?x"]]]]]}]
result
{"won":["c"],"lost":["d"],"drawn":["a","b","e","f","g"]}

Other questions (find, why, assuming, goals used as values, or negation mixed with aggregation or existential rules) still cannot go through recursion. See Logic database guarantees.

How-to guide · task-oriented

Say that something exists

Write rules that say a value exists without saying what it is, read the unknowns they invent, keep only known answers, and make unknowns one with a key or an equality rule.

This guide shows how to say that something exists when nobody has said what it is, such as a mother for every person or a lead for every team, and how to work with the values Lion invents for it.

Write a rule that invents

List a variable of the head in exists. The head then holds for some value of it that nobody has given, and the rule invents that value, an unknown:

["begin",
  ["relation", "person", ["name"]],
  ["relation", "mother", ["child", "mother"]],
  ["fact", ["person", "ada"], ["person", "ben"], ["person", "cy"]],
  ["fact", ["mother", "ada", "eve"]],
  ["rule", ["exists", ["?m"], ["mother", "?c", "?m"]], ["person", "?c"]],
  ["query", ["mother", "?child", "?mother"], {"order": "child"}]]
result
[
  {"child":"ada","mother":"eve"},
  {"child":"ben","mother":["some","?m",["mother","ben","?m"]]},
  {"child":"cy","mother":["some","?m",["mother","cy","?m"]]}
]

The rule invents only for an answer whose head does not hold already. Ada has a mother, so it invents nothing for her. Without exists, a head variable that the body never binds is an error, and the message suggests exists.

Rules that invent wait until every rule that invents nothing has finished. Here the rule that reads birth records is written after the rule that invents, and still gives ben his mother first, so nothing is invented for him:

["begin",
  ["relation", "person", ["name"]],
  ["relation", "birth", ["child", "mother", "year"]],
  ["relation", "mother", ["child", "mother"]],
  ["fact", ["person", "ada"], ["person", "ben"]],
  ["fact", ["birth", "ben", "fay", 1990]],
  ["rule", ["exists", ["?m"], ["mother", "?c", "?m"]], ["person", "?c"]],
  ["rule", ["mother", "?c", "?m"], ["birth", "?c", "?m", "?_"]],
  ["query", ["mother", "?child", "?mother"], {"order": "child"}]]
result
[
  {"child":"ada","mother":["some","?m",["mother","ada","?m"]]},
  {"child":"ben","mother":"fay"}
]

So the result never depends on the order rules or facts were added in.

Read an unknown

An unknown is written ["some", "?m", ["mother", "ben", "?m"]]: the value ?m stands for in a row ["mother", "ben", ?m]. That form is ordinary Lion. Evaluating it gives the same unknown, so a program can write one to put it in a fact, look it up, or compare it:

["begin",
  ["relation", "person", ["name"]],
  ["relation", "mother", ["child", "mother"]],
  ["relation", "tall", ["name"]],
  ["fact", ["person", "ada"], ["person", "ben"]],
  ["fact", ["mother", "ada", "eve"]],
  ["rule", ["exists", ["?m"], ["mother", "?c", "?m"]], ["person", "?c"]],
  ["fact", ["tall", ["some", "?m", ["mother", "ben", "?m"]]]],
  {"ben's mother is it": ["mother", "ben", ["some", "?m", ["mother", "ben", "?m"]]],
   "children of tall mothers": ["find", "?c", ["and", ["mother", "?c", "?m"], ["tall", "?m"]]],
   "is it eve": ["=", ["some", "?m", ["mother", "ben", "?m"]], "eve"],
   "unknown?": ["find", ["array/make", "?c", ["value/unknown?", "?m"]], ["mother", "?c", "?m"]]}]
result
{
  "ben's mother is it": true,
  "children of tall mothers": ["ben"],
  "is it eve": false,
  "unknown?": [["ada",false],["ben",true]]
}

An unknown equals itself and nothing else, as a string does, and two unknowns are the same when they are written the same way. It sorts after every record. A function that needs a number or a string fails on one, as it does on any value of the wrong kind.

Keep only known answers

value/unknown? is true for an unknown, so ["not", ["value/unknown?", "?m"]] keeps only the answers whose values were given. Lion stays closed-world: not holds for anything that is not known, so ben's unknown mother is not eve:

["begin",
  ["relation", "person", ["name"]],
  ["relation", "mother", ["child", "mother"]],
  ["fact", ["person", "ada"], ["person", "ben"]],
  ["fact", ["mother", "ada", "eve"]],
  ["rule", ["exists", ["?m"], ["mother", "?c", "?m"]], ["person", "?c"]],
  {"known": ["query", ["and", ["mother", "?child", "?m"], ["not", ["value/unknown?", "?m"]]]],
   "not eve": ["find", "?child", ["and", ["mother", "?child", "?m"], ["not", ["=", "?m", "eve"]]]]}]
result
{"known":[{"child":"ada","m":"eve"}],"not eve":["ben"]}

That ben's unknown mother is not eve is an assumption: she may be. why marks what rests on one with "assumed": true, so it tells an answer that holds whatever an unknown is from one that only holds as far as is known. See Explain a result.

["begin",
  ["relation", "person", ["name"]],
  ["relation", "mother", ["child", "mother"]],
  ["fact", ["person", "ada"], ["person", "ben"]],
  ["fact", ["mother", "ada", "eve"]],
  ["rule", ["exists", ["?m"], ["mother", "?c", "?m"]], ["person", "?c"]],
  {"is ben's mother eve": ["why", ["mother", "ben", "eve"]],
   "is ada's mother fay": ["why", ["mother", "ada", "fay"]]}]
result
{
  "is ben's mother eve": {
    "absent": ["mother","ben","eve"],
    "assumed": true,
    "because": [
      {
        "rule": [
          "rule",
          ["exists",["?m"],["mother","?c","?m"]],
          ["person","?c"]
        ],
        "but": {
          "fact": ["mother","ben",["some","?m",["mother","ben","?m"]]],
          "rule": [
            "rule",
            ["exists",["?m"],["mother","?c","?m"]],
            ["person","?c"]
          ],
          "because": [{"fact":["person","ben"],"given":true}]
        }
      }
    ]
  },
  "is ada's mother fay": {
    "absent": ["mother","ada","fay"],
    "because": [
      {
        "rule": [
          "rule",
          ["exists",["?m"],["mother","?c","?m"]],
          ["person","?c"]
        ],
        "but": {"fact":["mother","ada","eve"],"given":true}
      }
    ]
  }
}

Ask whether something exists

exists is also a goal: it holds when its goal holds for some value of each variable it lists. Those variables are its own wherever it stands, so they never appear in an answer. It is a question, so it works in plain code, in a query or rule, under not, and in a find:

["begin",
  ["relation", "person", ["name"]],
  ["relation", "mother", ["child", "mother"]],
  ["relation", "tall", ["name"]],
  ["fact", ["person", "ada"], ["person", "ben"], ["person", "cy"]],
  ["fact", ["mother", "ada", "eve"], ["mother", "ben", "fay"], ["tall", "eve"]],
  {"has a tall mother": ["query",
     ["and", ["person", "?p"], ["exists", ["?m"], ["and", ["mother", "?p", "?m"], ["tall", "?m"]]]]],
   "has no mother": ["find", "?p",
     ["and", ["person", "?p"], ["not", ["exists", ["?m"], ["mother", "?p", "?m"]]]]],
   "anyone with a mother": ["exists", ["?c", "?m"], ["mother", "?c", "?m"]]}]
result
{
  "has a tall mother": [{"p":"ada"}],
  "has no mother": ["cy"],
  "anyone with a mother": true
}

Invent one value for several rows

A head can be an and of relation calls, which adds a row to each. Under exists, one unknown is in every row, and the goal of its some is the whole and. Here every team has a lead who is on the staff. The web team's lead already is, so nothing is invented for it:

["begin",
  ["relation", "team", ["name"]],
  ["relation", "lead", ["team", "person"]],
  ["relation", "staff", ["person"]],
  ["fact", ["team", "web"], ["team", "data"]],
  ["fact", ["lead", "web", "ana"], ["staff", "ana"]],
  ["rule", ["exists", ["?p"], ["and", ["lead", "?t", "?p"], ["staff", "?p"]]], ["team", "?t"]],
  {"leads": ["query", ["lead", "?team", "?person"], {"order": "team"}],
   "staff": ["find", "?p", ["staff", "?p"]]}]
result
{
  "leads": [
    {
      "team": "data",
      "person": ["some","?p",["and",["lead","data","?p"],["staff","?p"]]]
    },
    {"team":"web","person":"ana"}
  ],
  "staff": [
    "ana",
    ["some","?p",["and",["lead","data","?p"],["staff","?p"]]]
  ]
}

With several variables, exists invents an unknown for each. The goal of each some mentions the others, which are its own too:

["begin",
  ["relation", "person", ["name"]],
  ["relation", "parents", ["child", "father", "mother"]],
  ["fact", ["person", "ann"]],
  ["rule", ["exists", ["?f", "?m"], ["parents", "?c", "?f", "?m"]], ["person", "?c"]],
  ["query", ["parents", "?child", "?father", "?mother"]]]
result
[
  {
    "child": "ann",
    "father": ["some","?f",["parents","ann","?f","?m"]],
    "mother": ["some","?m",["parents","ann","?f","?m"]]
  }
]

Make unknowns one with a key

A key says a relation has one row per key. When two rows have the same key and differ only where one holds an unknown that the relation's rules invented, the unknown takes the other row's value: a given value, or, when both are invented unknowns, the one that nests fewer unknowns, and of those the one that sorts first. Here every person has a mother and twins share one, so ben and cy get one unknown mother:

["begin",
  ["relation", "person", ["name"]],
  ["relation", "twin", ["a", "b"]],
  ["relation", "mother", ["child", "mother"], {"key": "child"}],
  ["fact", ["person", "ben"], ["person", "cy"], ["person", "dee"]],
  ["fact", ["twin", "ben", "cy"]],
  ["rule", ["exists", ["?m"], ["mother", "?c", "?m"]], ["person", "?c"]],
  ["rule", ["mother", "?b", "?m"], ["twin", "?a", "?b"], ["mother", "?a", "?m"]],
  ["rule", ["mother", "?a", "?m"], ["twin", "?a", "?b"], ["mother", "?b", "?m"]],
  {"mothers": ["query", ["mother", "?child", "?mother"], {"order": "child"}],
   "why cy": ["why", ["mother", "cy", ["some", "?m", ["mother", "ben", "?m"]]]]}]
result
{
  "mothers": [
    {"child":"ben","mother":["some","?m",["mother","ben","?m"]]},
    {"child":"cy","mother":["some","?m",["mother","ben","?m"]]},
    {"child":"dee","mother":["some","?m",["mother","dee","?m"]]}
  ],
  "why cy": {
    "fact": ["mother","cy",["some","?m",["mother","ben","?m"]]],
    "rule": [
      "rule",
      ["mother","?b","?m"],
      ["twin","?a","?b"],
      ["mother","?a","?m"]
    ],
    "because": [
      {"fact":["twin","ben","cy"],"given":true},
      {
        "fact": ["mother","ben",["some","?m",["mother","ben","?m"]]],
        "rule": [
          "rule",
          ["exists",["?m"],["mother","?c","?m"]],
          ["person","?c"]
        ],
        "because": [{"fact":["person","ben"],"given":true}]
      }
    ]
  }
}

Two different values that nobody invented, such as two given mothers, are still an error. An unknown that a fact holds is given, not invented, so a key never changes it.

A key can also make an invented unknown equal to a value that was given. Here every person's mother is a woman, and the key says ada's one mother is fay, so the unknown woman the rule invents for ada is fay, and fay is a woman. why explains such a row by the rule that invented it, with a same premise that says what the key made its unknown equal to:

["begin",
  ["relation", "person", ["name"]],
  ["relation", "woman", ["name"]],
  ["relation", "mother", ["child", "mother"], {"key": "child"}],
  ["fact", ["person", "ada"], ["mother", "ada", "fay"]],
  ["rule", ["exists", ["?m"], ["and", ["mother", "?c", "?m"], ["woman", "?m"]]], ["person", "?c"]],
  {"mothers": ["find", ["array/make", "?c", "?m"], ["mother", "?c", "?m"]],
   "women": ["find", "?w", ["woman", "?w"]],
   "why fay": ["why", ["woman", "fay"]]}]
result
{
  "mothers": [["ada","fay"]],
  "women": ["fay"],
  "why fay": {
    "fact": ["woman","fay"],
    "rule": [
      "rule",
      [
        "exists",
        ["?m"],
        ["and",["mother","?c","?m"],["woman","?m"]]
      ],
      ["person","?c"]
    ],
    "because": [
      {"fact":["person","ada"],"given":true},
      {
        "same": [
          [
            "some",
            "?m",
            ["and",["mother","ada","?m"],["woman","?m"]]
          ],
          "fay"
        ]
      }
    ]
  }
}

Say that two values are the same

A rule's head can be ["=", a, b]: an equality rule. Whenever its body holds, the two sides are one value. While the relations its body reads are derived, an unknown that a rule invented takes the value on the other side, as it does under a key. Here twins share a mother, and a registered mother is the one a person has:

["begin",
  ["relation", "person", ["name"]],
  ["relation", "twin", ["a", "b"]],
  ["relation", "mother", ["child", "mother"]],
  ["relation", "registered", ["child", "mother"]],
  ["fact", ["person", "ben"], ["person", "cy"], ["person", "dee"], ["twin", "ben", "cy"]],
  ["fact", ["registered", "dee", "eve"]],
  ["rule", ["exists", ["?m"], ["mother", "?c", "?m"]], ["person", "?c"]],
  ["rule", ["=", "?m1", "?m2"], ["twin", "?a", "?b"], ["mother", "?a", "?m1"], ["mother", "?b", "?m2"]],
  ["rule", ["=", "?m", "?r"], ["mother", "?c", "?m"], ["registered", "?c", "?r"]],
  {"mothers": ["query", ["mother", "?child", "?mother"], {"order": "child"}],
   "why cy": ["why", ["mother", "cy", ["some", "?m", ["mother", "ben", "?m"]]]]}]
result
{
  "mothers": [
    {"child":"ben","mother":["some","?m",["mother","ben","?m"]]},
    {"child":"cy","mother":["some","?m",["mother","ben","?m"]]},
    {"child":"dee","mother":"eve"}
  ],
  "why cy": {
    "fact": ["mother","cy",["some","?m",["mother","ben","?m"]]],
    "rule": [
      "rule",
      ["exists",["?m"],["mother","?c","?m"]],
      ["person","?c"]
    ],
    "because": [
      {"fact":["person","cy"],"given":true},
      {
        "same": [
          ["some","?m",["mother","cy","?m"]],
          ["some","?m",["mother","ben","?m"]]
        ]
      }
    ]
  }
}

An equality rule also holds as the invariant it stands for, ["and", goal, ..., ["not", ["=", a, b]]]. A rule that does not hold is not added, and a change that leaves two different known values under it is refused, in an invariant's words. A body that reads only facts has no unknowns to make one, so there the rule is only that check:

["begin",
  ["relation", "email", ["person", "address"]],
  ["rule", ["=", "?a", "?b"], ["email", "?p", "?a"], ["email", "?p", "?b"]],
  ["fact", ["email", "ann", "a@x"]],
  ["fact", ["email", "ann", "ann@y"]]]
error
LogicError: Adding this fact breaks an invariant, so nothing changed. The invariant expected no answers but found 2, such as {"p":"ann","a":"a@x","b":"ann@y"}: ["and",["email","?p","?a"],["email","?p","?b"],["not",["=","?a","?b"]]].

Making an unknown one with a value changes every row that holds it, including rows of relations derived from those rows. So the relations of a rule that invents an unknown an equality rule can meet are derived together with every relation the equality rule reads, and the rule runs with them. An unknown can reach the rule through any number of relations between them. Here it reaches the rule through listed, which copies mother:

["begin",
  ["relation", "person", ["name"]],
  ["relation", "birth", ["child", "mother"]],
  ["relation", "mother", ["child", "mother"]],
  ["relation", "listed", ["child", "mother"]],
  ["fact", ["person", "ben"], ["person", "cy"], ["birth", "ben", "fay"]],
  ["rule", ["exists", ["?m"], ["mother", "?c", "?m"]], ["person", "?c"]],
  ["rule", ["listed", "?c", "?m"], ["mother", "?c", "?m"]],
  ["rule", ["=", "?m", "?n"], ["listed", "?c", "?m"], ["birth", "?c", "?n"]],
  {"mothers": ["query", ["mother", "?child", "?mother"], {"order": "child"}],
   "listed": ["query", ["listed", "?child", "?mother"], {"order": "child"}]}]
result
{
  "mothers": [
    {"child":"ben","mother":"fay"},
    {"child":"cy","mother":["some","?m",["mother","cy","?m"]]}
  ],
  "listed": [
    {"child":"ben","mother":"fay"},
    {"child":"cy","mother":["some","?m",["mother","cy","?m"]]}
  ]
}

When unknowns nest, the one kept is the one that nests fewer unknowns, and of those the one that sorts first. Here every person has a mother, cy's mother has a mother of her own, and two equality rules make all three one. Cy's grandmother is written ["some", "?g", ...], so she sorts before both mothers, but she nests cy's mother, so a mother is kept: ben's, which sorts first of the two. Which equality rule comes first does not matter:

["begin",
  ["relation", "person", ["name"]],
  ["relation", "mother", ["child", "mother"]],
  ["relation", "grandmother", ["parent", "grandmother"]],
  ["fact", ["person", "ben"], ["person", "cy"]],
  ["rule", ["exists", ["?m"], ["mother", "?c", "?m"]], ["person", "?c"]],
  ["rule", ["exists", ["?g"], ["grandmother", "?p", "?g"]], ["mother", "cy", "?p"]],
  ["rule", ["=", "?a", "?b"], ["grandmother", "?_", "?a"], ["mother", "ben", "?b"]],
  ["rule", ["=", "?a", "?b"], ["mother", "ben", "?a"], ["mother", "cy", "?b"], ["grandmother", "?_", "?_"]],
  ["query", ["mother", "?child", "?mother"], {"order": "child"}]]
result
[
  {"child":"ben","mother":["some","?m",["mother","ben","?m"]]},
  {"child":"cy","mother":["some","?m",["mother","ben","?m"]]}
]

A question about those relations, such as a goal under not, would then go through recursion, so Lion refuses it when the rule is added, whatever the facts. Here whether ben's unknown mother is fay would decide whether ben is private, and that decides whether anything says she is fay:

["begin",
  ["relation", "person", ["name"]],
  ["relation", "birth", ["child", "mother"]],
  ["relation", "mother", ["child", "mother"]],
  ["relation", "private", ["child"]],
  ["relation", "listed", ["child", "mother"]],
  ["rule", ["exists", ["?m"], ["mother", "?c", "?m"]], ["person", "?c"]],
  ["rule", ["private", "?c"], ["mother", "?c", "?m"], ["birth", "?c", "?m"]],
  ["rule", ["listed", "?c", "?m"], ["mother", "?c", "?m"], ["not", ["private", "?c"]]],
  ["rule", ["=", "?m", "?n"], ["listed", "?c", "?m"], ["birth", "?c", "?n"]]]
error
LogicError: Rule ["rule",["listed","?c","?m"],["mother","?c","?m"],["not",["private","?c"]]] asks about "private", which depends on "listed". A question, such as a find or a goal used as a value, cannot go through recursion.

Lion follows each value through the columns of the rules, so a question beside the unknowns, about columns no invented value reaches, is allowed. An unknown that a fact holds is a stated value, and no equality rule changes it; the invariant reports such a pair.

State that something exists in a fact

A fact can hold exists too. It adds the row with an unknown in it, the very row a rule with that head would invent. A fact states rows, so it adds the row whether or not the head holds already. why and retract take exists the same way:

["begin",
  ["relation", "mother", ["child", "mother"]],
  ["fact", ["exists", ["?m"], ["mother", "ben", "?m"]]],
  {"rows": ["query", ["mother", "?child", "?mother"]],
   "why": ["why", ["exists", ["?m"], ["mother", "ben", "?m"]]]}]
result
{
  "rows": [{"child":"ben","mother":["some","?m",["mother","ben","?m"]]}],
  "why": {
    "fact": ["mother","ben",["some","?m",["mother","ben","?m"]]],
    "given": true
  }
}

A snapshot writes an unknown as its some form, and a rule that invents with its exists head, so a saved database keeps both. See Save and load a logic database.

Keep inventions finite

Rules that invent can recurse, as long as what they invent never flows back into inventing more. "Every person has a mother" with "every mother is a person" would invent mothers without end, so Lion refuses the rule that closes the loop. The message names the rule that would invent:

["begin",
  ["relation", "person", ["name"]],
  ["relation", "mother", ["child", "mother"]],
  ["rule", ["exists", ["?m"], ["mother", "?p", "?m"]], ["person", "?p"]],
  ["rule", ["person", "?m"], ["mother", "?p", "?m"]]]
error
LogicError: Rule ["rule",["exists",["?m"],["mother","?p","?m"]],["person","?p"]] invents a value for "?m" in its head while recursing, which may never finish. Invent the value in a rule that does not recurse.

Invent the value in a rule that does not recurse. A rule that invents also cannot aggregate. See Termination for the rule.

How-to guide · task-oriented

Summarize groups of facts

Count, total, average, and collect values per group, like GROUP BY in SQL.

This guide shows how to compute totals per group with aggregates in a rule's head.

Group and total

Put an aggregate such as ["aggregate/sum", "?amount"] in a column of the head. The head's other columns are the group:

["begin",
  ["relation", "order", ["id", "customer", "amount"]],
  ["relation", "spend", ["customer", "total", "orders"]],
  ["fact", ["order", 1, "ana", 30], ["order", 2, "ana", 20], ["order", 3, "bo", 50]],
  ["rule", ["spend", "?c", ["aggregate/sum", "?amount"], ["aggregate/count", "?id"]],
    ["order", "?id", "?c", "?amount"]],
  ["query", ["spend", "?customer", "?total", "?orders"], {"order": "customer"}]]
result
[
  {"customer":"ana","total":50,"orders":2},
  {"customer":"bo","total":50,"orders":1}
]

A group only exists when something matches, so a count is never 0; the next section reports zeros. The argument can also be a constant: ["aggregate/count", 1] counts the matches.

Count what may be nothing

Give the aggregate a find. It lists what a goal matches for each customer, and a list can be empty:

["begin",
  ["relation", "customer", ["name"]],
  ["relation", "order", ["id", "customer", "amount"]],
  ["relation", "activity", ["customer", "orders", "total"]],
  ["fact", ["customer", "ana"], ["customer", "bo"], ["customer", "cy"]],
  ["fact", ["order", 1, "ana", 30], ["order", 2, "ana", 20], ["order", 3, "bo", 50]],
  ["rule",
    ["activity", "?c",
      ["aggregate/count", ["find", "?id", ["order", "?id", "?c", "?_"]]],
      ["aggregate/sum", ["find", "?amount", ["order", "?_", "?c", "?amount"]]]],
    ["customer", "?c"]],
  ["query", ["activity", "?customer", "?orders", "?total"], {"order": "customer"}]]
result
[
  {"customer":"ana","orders":2,"total":50},
  {"customer":"bo","orders":1,"total":50},
  {"customer":"cy","orders":0,"total":0}
]

The same works without a rule, in a query or in plain code:

["begin",
  ["relation", "order", ["id", "customer", "amount"]],
  ["fact", ["order", 1, "ana", 30], ["order", 2, "ana", 20], ["order", 3, "bo", 50]],
  {"orders": ["aggregate/count", ["find", "?id", ["order", "?id", "?_", "?_"]]],
   "largest": ["aggregate/max", ["find", "?amount", ["order", "?_", "?_", "?amount"]]],
   "customers": ["aggregate/unique", ["find", "?c", ["order", "?_", "?c", "?_"]]]}]
result
{"orders":3,"largest":50,"customers":["ana","bo"]}

Pick the aggregate you need

["begin",
  ["relation", "reading", ["sensor", "n", "value"]],
  ["relation", "stats",
    ["sensor", "count", "unique", "sum", "mean", "min", "max", "values", "distinct"]],
  ["fact",
    ["reading", "s1", 1, 3], ["reading", "s1", 2, 6], ["reading", "s1", 3, 3],
    ["reading", "s2", 1, 9]],
  ["rule", ["stats", "?s",
      ["aggregate/count", "?v"], ["aggregate/countUnique", "?v"],
      ["aggregate/sum", "?v"], ["aggregate/mean", "?v"],
      ["aggregate/min", "?v"], ["aggregate/max", "?v"],
      ["aggregate/collect", "?v"], ["aggregate/unique", "?v"]],
    ["reading", "?s", "?_", "?v"]],
  ["query",
    ["stats", "?sensor", "?count", "?unique", "?sum", "?mean", "?min", "?max", "?values", "?distinct"],
    {"order": "sensor"}]]
result
[
  {
    "sensor": "s1",
    "count": 3,
    "unique": 2,
    "sum": 12,
    "mean": 4,
    "min": 3,
    "max": 6,
    "values": [3,3,6],
    "distinct": [3,6]
  },
  {
    "sensor": "s2",
    "count": 1,
    "unique": 1,
    "sum": 9,
    "mean": 9,
    "min": 9,
    "max": 9,
    "values": [9],
    "distinct": [9]
  }
]

Each reading has a number, n. Facts are a set, so without it the two readings of 3 from s1 would be a single fact and would count once. Every match of a rule's body counts once, so give repeated values something that tells them apart.

Aggregate computed values

An aggregate can combine a computed value:

["begin",
  ["relation", "line", ["order", "price", "quantity"]],
  ["relation", "total", ["order", "amount"]],
  ["fact", ["line", 1, 10, 3], ["line", 1, 5, 2], ["line", 2, 8, 1]],
  ["rule", ["total", "?o", ["aggregate/sum", ["number/multiply", "?price", "?quantity"]]],
    ["line", "?o", "?price", "?quantity"]],
  ["query", ["total", "?order", "?amount"], {"order": "order"}]]
result
[{"order":1,"amount":40},{"order":2,"amount":8}]

Summarize each fact's own list

An aggregate call combines a rule's matches only as a whole argument of the head, and only when its argument is not a find. Anywhere else, in a body or inside another call, it combines the list it is given, once for each match:

["begin",
  ["relation", "cart", ["id", "prices", "shipping"]],
  ["relation", "due", ["id", "amount"]],
  ["fact", ["cart", 1, ["array/make", 10, 5], 4], ["cart", 2, ["array/make", 8], 0]],
  ["rule", ["due", "?id", ["number/add", ["aggregate/sum", "?prices"], "?shipping"]],
    ["cart", "?id", "?prices", "?shipping"]],
  ["query", ["due", "?id", "?amount"], {"order": "id"}]]
result
[{"id":1,"amount":19},{"id":2,"amount":8}]

Summarize a plain list

Outside a rule, every aggregate function combines a list right away. Numbers are exact, so a sum or a mean is the exact one: the mean of 3, 1, and 3 is the fraction 7/3, which no decimal writes, so JSON cannot hold it. Write it as text with number/toString, or round it to some places with number/round:

{"sum": ["aggregate/sum", ["array/make", 3, 1, 3]],
 "mean": ["number/toString", ["aggregate/mean", ["array/make", 3, 1, 3]]],
 "mean to two places": ["number/round", ["aggregate/mean", ["array/make", 3, 1, 3]], 2],
 "unique": ["aggregate/unique", ["array/make", 3, 1, 3]]}
result
{"sum":7,"mean":"7/3","mean to two places":2.33,"unique":[1,3]}

How-to guide · task-oriented

Answer graph questions

Find shortest routes, rank nodes, group connected nodes, detect cycles, and order dependencies with the graph module.

This guide shows how to run classic graph algorithms over an edge relation with the graph module. Each algorithm is called like a relation, so its rows work in queries, rules, not, and aggregates.

Find shortest routes

Give graph/shortestPath an edge relation and a start node, then one term each for the destination, the cost, and the path. A third edge column is the weight:

["begin",
  ["relation", "road", ["from", "to", "km"]],
  ["fact", ["road", "a", "b", 4], ["road", "a", "c", 1], ["road", "c", "b", 2], ["road", "b", "d", 5]],
  ["query", ["graph/shortestPath", "road", "a", "?to", "?km", "?path"]]]
result
[
  {"to":"a","km":0,"path":["a"]},
  {"to":"c","km":1,"path":["a","c"]},
  {"to":"b","km":3,"path":["a","c","b"]},
  {"to":"d","km":8,"path":["a","c","b","d"]}
]

To ask about one destination, give it as a value: ["graph/shortestPath", "road", "a", "d", "?km", "?_"]. Without a weight column, every edge costs 1.

Start from every node a goal finds

The start can be a variable that another goal binds. The algorithm then runs once for each start:

["begin",
  ["relation", "road", ["from", "to", "km"]],
  ["relation", "depot", ["at"]],
  ["fact", ["road", "a", "b", 4], ["road", "a", "c", 1], ["road", "c", "b", 2], ["road", "b", "d", 5]],
  ["fact", ["depot", "a"], ["depot", "c"]],
  ["query",
    ["and", ["depot", "?from"],
      ["graph/shortestPath", "road", "?from", "d", "?km", "?path"]],
    {"order": "from"}]]
result
[
  {"from":"a","km":8,"path":["a","c","b","d"]},
  {"from":"c","km":7,"path":["c","b","d"]}
]

Rank nodes

["begin",
  ["relation", "link", ["from", "to"]],
  ["fact", ["link", "a", "b"], ["link", "b", "c"], ["link", "c", "a"], ["link", "d", "c"]],
  ["query", ["graph/pageRank", "link", "?page", "?rank"], {"order": "-rank"}]]
result
[
  {"page":"c","rank":0.332604},
  {"page":"a","rank":0.320214},
  {"page":"b","rank":0.309682},
  {"page":"d","rank":0.0375}
]

Group connected nodes

graph/components ignores edge direction; graph/stronglyConnected follows it. Groups are named after their smallest node:

["begin",
  ["relation", "edge", ["from", "to"]],
  ["fact", ["edge", "a", "b"], ["edge", "b", "a"], ["edge", "b", "c"], ["edge", "x", "y"]],
  {"connected": ["query", ["graph/components", "edge", "?node", "?group"], {"order": "node"}],
   "strong": ["query", ["graph/stronglyConnected", "edge", "?node", "?group"], {"order": "node"}]}]
result
{
  "connected": [
    {"node":"a","group":"a"},
    {"node":"b","group":"a"},
    {"node":"c","group":"a"},
    {"node":"x","group":"x"},
    {"node":"y","group":"x"}
  ],
  "strong": [
    {"node":"a","group":"a"},
    {"node":"b","group":"a"},
    {"node":"c","group":"c"},
    {"node":"x","group":"x"},
    {"node":"y","group":"y"}
  ]
}

Order dependencies

graph/topologicalOrder numbers nodes so every edge points forward, or fails with an error that names a cycle:

["begin",
  ["relation", "before", ["first", "then"]],
  ["fact", ["before", "socks", "shoes"], ["before", "pants", "shoes"], ["before", "shirt", "tie"]],
  ["query", ["graph/topologicalOrder", "before", "?step", "?position"], {"order": "position"}]]
result
[
  {"step":"pants","position":0},
  {"step":"shirt","position":1},
  {"step":"socks","position":2},
  {"step":"shoes","position":3},
  {"step":"tie","position":4}
]

Use results in rules

Algorithm rows can feed rules. Here, nodes far from the start are flagged:

["begin",
  ["relation", "road", ["from", "to", "km"]],
  ["relation", "remote", ["place"]],
  ["fact", ["road", "a", "b", 4], ["road", "a", "c", 1], ["road", "c", "b", 2], ["road", "b", "d", 5]],
  ["rule", ["remote", "?p"],
    ["graph/shortestPath", "road", "a", "?p", "?km", "?_"],
    ["number/greaterThan", "?km", 5]],
  ["query", ["remote", "?place"]]]
result
[{"place":"d"}]

An algorithm runs once its input relation is complete, the first time a goal asks for its rows. So it cannot be part of a recursive cycle, and its relation cannot have facts or rules of its own.

How-to guide · task-oriented

Enforce rules on your data

State conditions your data must always meet, and have the database refuse any change that would break them.

This guide shows how to keep a logic database consistent with invariants. An invariant is a query assertion the database keeps: after every change, it asks the question again, and a change that breaks the answer is refused.

Forbid a situation

Write a goal that describes the bad situation, and assert it has "none" answers:

["begin",
  ["relation", "order", ["id", "status"], {"key": "id"}],
  ["relation", "cancelled", ["id"]],
  ["fact", ["order", 1, "open"], ["order", 2, "shipped"]],
  ["invariant",
    ["and", ["order", "?id", "shipped"], ["cancelled", "?id"]],
    {"assert": "none"}],
  ["fact", ["cancelled", 2]]]
error
LogicError: Adding this fact breaks an invariant, so nothing changed. The invariant expected no answers but found 1, such as {"id":2}: ["and",["order","?id","shipped"],["cancelled","?id"]].

The error names the invariant and one answer that breaks it, here order 2.

Require something to exist

Assert "some" to require at least one answer at all times, such as at least one admin:

["begin",
  ["relation", "role", ["user", "name"]],
  ["fact", ["role", "ana", "admin"], ["role", "bo", "admin"]],
  ["invariant", ["role", "?_", "admin"], {"assert": "some"}],
  ["retract", ["role", "ana", "admin"]],
  ["retract", ["role", "bo", "admin"]]]
error
LogicError: Retracting this fact breaks an invariant, so nothing changed. The invariant expected at least one answer but found none: ["role","?_","admin"].

Retracting Ana's role is fine; retracting the last admin is refused.

Check derived data

An invariant can ask anything a query can, including relations that rules derive, not, aggregates, and graph algorithms. Here no customer may owe more than 100:

["begin",
  ["relation", "order", ["id", "customer", "amount"]],
  ["relation", "owed", ["customer", "total"]],
  ["rule", ["owed", "?c", ["aggregate/sum", "?a"]], ["order", "?_", "?c", "?a"]],
  ["invariant",
    ["and", ["owed", "?c", "?total"], ["number/greaterThan", "?total", 100]],
    {"assert": "none"}],
  ["fact", ["order", 1, "ana", 60]],
  ["fact", ["order", 2, "ana", 50]]]
error
LogicError: Adding this fact breaks an invariant, so nothing changed. The invariant expected no answers but found 1, such as {"c":"ana","total":110}: ["and",["owed","?c","?total"],["number/greaterThan","?total",100]].

Make changes that only hold together

Each fact, retract, or rule form is checked once it has made all of its changes. Put changes that only satisfy the invariants together in one form:

["begin",
  ["relation", "employee", ["name"]],
  ["relation", "manager", ["employee", "manager"], {"key": "employee"}],
  ["invariant",
    ["and", ["employee", "?e"], ["not", ["manager", "?e", "?_"]], ["not", ["manager", "?_", "?e"]]],
    {"assert": "none"}],
  ["fact", ["employee", "ana"], ["employee", "bo"], ["manager", "bo", "ana"]],
  ["query", ["manager", "?employee", "?manager"]]]
result
[{"employee":"bo","manager":"ana"}]

Separate forms in a begin are separate changes, each checked on its own.

Check the shape of each row

A condition on a single row, such as "the status is one of these", is a schema. The relation option "schema" keeps it as an invariant for you; see Check the shape of data. Checking a write costs what its new rows cost: an invariant is asked again only after a change to a relation it reads, and one that says no row of a relation fails a test is asked about the new rows alone. An invariant that calls a function from the host is asked in full every time, unless the function says it reads only its arguments.

["begin",
  ["schema", "Order",
    ["schema/open", {"id": "value/integer?", "status": ["schema/anyOf", "open", "paid", "shipped"]}]],
  ["relation", "order", ["id", "customer", "status"], {"key": "id", "schema": "Order"}],
  ["fact", ["order", 1, "ana", "open"]],
  ["fact", ["order", 2, "bo", "lost"]]]
error
LogicError: Adding this fact breaks an invariant, so nothing changed. The invariant expected no answers but found 1, such as {"id":2,"customer":"bo","status":"lost"}: ["and",["order","?id","?customer","?status"],["not",["Order",{"id":"?id","customer":"?customer","status":"?status"}]]]. {"id":2,"customer":"bo","status":"lost"} does not fit "Order": "status" must fit ["schema/anyOf","open","paid","shipped"] but is "lost".

Enforce transitions between states

Inside an invariant, ["was", goal] reads goal in the state before the change while plain goals read the state after, expressing two-state action invariants such as monotonic epochs or finite-state machine transitions:

["begin",
  ["relation", "epoch", ["k", "n"], {"key": "k"}],
  ["fact", ["epoch", "node-1", 5]],
  ["invariant",
    ["and",
      ["was", ["epoch", "?k", "?old"]],
      ["epoch", "?k", "?new"],
      ["number/lessThan", "?new", "?old"]],
    {"assert": "none"}],
  ["fact", ["epoch", "node-1", 7]],
  ["fact", ["epoch", "node-1", 4]]]
error
LogicError: Adding this fact breaks an invariant, so nothing changed. The invariant expected no answers but found 1, such as {"k":"node-1","old":7,"new":4}: ["and",["was",["epoch","?k","?old"]],["epoch","?k","?new"],["number/lessThan","?new","?old"]].

Advancing from 5 to 7 passes; regressing from 7 to 4 fails and rolls back so "node-1" stays at 7.

Keep invariants across runs

Invariants live in the database, so they persist wherever it does: in a shared LogicDatabase from TypeScript, and in a --database file on the command line. Snapshots save them, and running a setup again adds no second copy.

How-to guide · task-oriented

Solve for values and prove rules

Let a schema type a variable no goal binds, and Lion solves for the values that meet your filters, says whether one exists, or proves that none does, for every number; what it cannot decide waits for the values it lists.

This guide shows how to ask about every value of a type, not only the values your facts hold. A variable that a schema such as value/integer? types, and that no relation goal binds, is solved for: the filters about it become constraints, and Lion works out exactly which numbers meet them.

Solve for the values that meet some filters

Type the variable with schema/fits?, then filter it as you would a bound one. When the filters leave finitely many whole numbers, each is an answer:

{"between": ["find", "?x",
   ["and", ["schema/fits?", "?x", "value/integer?"],
     ["number/greaterThan", "?x", 2], ["number/lessThan", "?x", 6]]],
 "solved for": ["find", "?x",
   ["and", ["schema/fits?", "?x", "value/integer?"],
     ["=", 7, ["number/add", ["number/multiply", 2, "?x"], 1]]]],
 "pairs": ["find", ["array/make", "?x", "?y"],
   ["and", ["schema/fits?", "?x", "value/integer?"], ["schema/fits?", "?y", "value/integer?"],
     ["number/greaterThanOrEqualTo", "?x", 0], ["number/greaterThanOrEqualTo", "?y", 0],
     ["=", ["number/add", "?x", "?y"], 3]]]}
result
{
  "between": [3,4,5],
  "solved for": [3],
  "pairs": [[0,3],[1,2],[2,1],[3,0]]
}

The filters can add, subtract, multiply and divide by known numbers, take number/floor, number/ceiling, number/round, and number/remainder by a known non-zero divisor, check value/integer?, compare, and use number/min, number/max, number/absolute, cond, and match. value/number? types a variable that may be any number.

As with values a schema lists, a find gives one value for every match, so a value the solver works out counts even when the template leaves it out. A rule gives each row once:

["begin",
  ["relation", "sign", ["s"]],
  ["rule", ["sign", "?s"], ["schema/fits?", "?x", "value/integer?"],
    ["=", "?s", ["cond", [["number/greaterThan", "?x", 0], "positive"], ["else", "not positive"]]]],
  {"each match": ["find", "?s",
     ["and", ["schema/fits?", "?x", "value/integer?"],
       ["number/greaterThanOrEqualTo", "?x", -1], ["number/lessThanOrEqualTo", "?x", 2],
       ["=", "?s", ["cond", [["number/greaterThan", "?x", 0], "positive"], ["else", "not positive"]]]]],
   "each row": ["find", "?s", ["sign", "?s"]]}]
result
{
  "each match": ["not positive","not positive","positive","positive"],
  "each row": ["not positive","positive"]
}

Ask whether a value exists, or prove that none does

When there are infinitely many values, they cannot each be an answer, but exists can still ask whether there is one, and not whether there is none. Lion decides it for every number, not only the ones it tried:

{"an odd number above 10": ["query",
   ["exists", ["?n", "?k"],
     ["and", ["schema/fits?", "?n", "value/integer?"], ["number/greaterThan", "?n", 10],
       ["=", ["number/subtract", "?n", ["number/multiply", 2, "?k"]], 1],
       ["schema/fits?", "?k", "value/integer?"]]]],
 "no whole number doubles to 7": ["query",
   ["not", ["exists", ["?n"],
     ["and", ["schema/fits?", "?n", "value/integer?"],
       ["=", ["number/multiply", 2, "?n"], 7]]]]]}
result
{
  "an odd number above 10": [{}],
  "no whole number doubles to 7": [{}]
}

Each query gives [{}] when its goal holds and [] when it does not.

Reason about remainders, rounding, and lists

The solver decides number/floor, number/ceiling, number/round, number/remainder by a known non-zero divisor, and value/integer? on any number, as well as lambdas with local define, match, and recursion over bounded lists:

{"even numbers stay even after +2": ["query",
   ["not", ["exists", ["?n"],
     ["and", ["schema/fits?", "?n", "value/integer?"],
       ["=", ["number/remainder", "?n", 2], 0],
       ["not", ["=", ["number/remainder", ["number/add", "?n", 2], 2], 0]]]]]],
 "half a whole number is whole iff even": ["query",
   ["not", ["exists", ["?n"],
     ["and", ["schema/fits?", "?n", "value/integer?"],
       ["=", ["number/remainder", "?n", 2], 0],
       ["not", ["value/integer?", ["number/divide", "?n", 2]]]]]]],
 "floor is at most ceiling": ["query",
   ["not", ["exists", ["?x"],
     ["and", ["schema/fits?", "?x", "value/number?"],
       ["number/greaterThan", ["number/floor", "?x"], ["number/ceiling", "?x"]]]]]],
 "sort preserves length for every list up to 3": ["query",
   ["not", ["exists", ["?xs"],
     ["and", ["schema/fits?", "?xs", ["schema/arrayOf", "value/integer?", 3]],
       ["not", ["=", ["array/length", ["array/sort", "?xs"]], ["array/length", "?xs"]]]]]]]}
result
{
  "even numbers stay even after +2": [{}],
  "half a whole number is whole iff even": [{}],
  "floor is at most ceiling": [{}],
  "sort preserves length for every list up to 3": [{}]
}

Solve quadratics and reason about records, aggregates, and units

The solver cancels higher-degree polynomial terms automatically and solves univariate quadratic equations and inequalities exactly (including integer root bracketing). It also reasons symbolically over object/set, object/merge, object/remove, object/entries, func/partial, guarded schema/assert and contracted lambdas, array/at, array/indexOf, array/find, aggregate/*, and quantity/*:

{"integer roots of x^2 - 5x + 6 = 0": ["find", "?x",
   ["and", ["schema/fits?", "?x", "value/integer?"],
     ["=", ["number/add", ["number/subtract", ["number/power", "?x", 2], ["number/multiply", 5, "?x"]], 6], 0]]],
 "sum of first n odd numbers step": ["query",
   ["not", ["exists", ["?n"],
     ["and", ["schema/fits?", "?n", "value/integer?"], ["number/greaterThanOrEqualTo", "?n", 0],
       ["not", ["=", ["number/add", ["number/power", "?n", 2], ["number/add", ["number/multiply", 2, "?n"], 1]],
                     ["number/power", ["number/add", "?n", 1], 2]]]]]]],
 "object/set preserves count": ["query",
   ["not", ["exists", ["?s", "?d"],
     ["and", ["schema/fits?", "?s", {"n": "value/integer?"}], ["schema/fits?", "?d", "value/integer?"],
       ["not", ["=", ["object/get", ["object/set", "?s", "n", ["number/add", ["object/get", "?s", "n"], "?d"]], "n"],
                     ["number/add", ["object/get", "?s", "n"], "?d"]]]]]]],
 "mean lies between min and max": ["query",
   ["not", ["exists", ["?a", "?b"],
     ["and", ["schema/fits?", "?a", "value/integer?"], ["schema/fits?", "?b", "value/integer?"],
       ["not", ["number/lessThanOrEqualTo",
         ["aggregate/min", ["array/make", "?a", "?b"]],
         ["aggregate/mean", ["array/make", "?a", "?b"]]]]]]]]}
result
{
  "integer roots of x^2 - 5x + 6 = 0": [2,3],
  "sum of first n odd numbers step": [{}],
  "object/set preserves count": [{}],
  "mean lies between min and max": [{}]
}

Prove something about decimals

Numbers are exact, in the solver and in plain code alike, so what the solver proves about decimals holds of what plain code computes. No number between 0 and 1 changes when 0.2 is added and taken away, and plain code gives 0.1 back:

{"proved": ["query", ["not", ["exists", ["?x"],
   ["and", ["schema/fits?", "?x", "value/number?"],
     ["number/greaterThan", "?x", 0], ["number/lessThan", "?x", 1],
     ["not", ["number/equals?", ["number/subtract", ["number/add", "?x", 0.2], 0.2], "?x"]]]]]],
 "in plain code": ["number/subtract", ["number/add", 0.1, 0.2], 0.2]}
result
{"proved":[{}],"in plain code":0.1}

Check what a function does for every input

A lambda you defined runs on the values the solver stands for, by its body, so a rule about what it returns is checked for every input at once. A schema of a record with typed fields stands for every such record. Here a careful withdrawal never leaves an open account below zero, for any balance and any amount, while a careless one can:

["begin",
  ["define", "careful", ["lambda", ["account", "amount"],
    ["cond", [["number/lessThan", ["object/get", "account", "balance"], "amount"], "account"],
             ["else", {"balance": ["number/subtract", ["object/get", "account", "balance"], "amount"]}]]]],
  ["define", "careless", ["lambda", ["account", "amount"],
    {"balance": ["number/subtract", ["object/get", "account", "balance"], "amount"]}]],
  ["define", "overdraws", ["lambda", ["withdraw"],
    ["query", ["exists", ["?account", "?amount"],
      ["and",
        ["schema/fits?", "?account", {"balance": "value/integer?"}],
        ["schema/fits?", "?amount", "value/integer?"],
        ["number/greaterThanOrEqualTo", ["object/get", "?account", "balance"], 0],
        ["number/greaterThan", "?amount", 0],
        ["number/lessThan", ["object/get", ["withdraw", "?account", "?amount"], "balance"], 0]]]]]],
  {"careful": ["overdraws", "careful"],
   "careless": ["overdraws", "careless"]}]
result
{"careful":[],"careless":[{}]}

See an example

why explains a row a rule gave through the solver with values that meet its goals:

["begin",
  ["relation", "limit", ["n"]],
  ["relation", "room", ["n"]],
  ["fact", ["limit", 5], ["limit", 1]],
  ["rule", ["room", "?n"], ["limit", "?n"],
    ["exists", ["?x"],
      ["and", ["schema/fits?", "?x", "value/integer?"],
        ["number/greaterThan", "?x", 2], ["number/lessThan", "?x", "?n"]]]],
  {"rooms": ["find", "?n", ["room", "?n"]],
   "why": ["why", ["room", 5]]}]
result
{
  "rooms": [5],
  "why": {
    "fact": ["room",5],
    "rule": [
      "rule",
      ["room","?n"],
      ["limit","?n"],
      [
        "exists",
        ["?x"],
        [
          "and",
          ["schema/fits?","?x","value/integer?"],
          ["number/greaterThan","?x",2],
          ["number/lessThan","?x","?n"]
        ]
      ]
    ],
    "because": [
      {"fact":["limit",5],"given":true},
      {
        "check": [
          "and",
          ["schema/fits?","?x","value/integer?"],
          ["number/greaterThan","?x",2],
          ["number/lessThan","?x",5]
        ],
        "example": {"?x":3}
      }
    ]
  }
}

Know what it cannot decide

Lion decides sums of numbers times known numbers, comparisons of them, and equality of values, so every question it decides has one answer. Anything else, such as a product of two unknowns or a string function, waits for values: the solver lists the values of the variables it needs, from what it can decide, and runs it on each, as plain code would:

{"factors of 6": ["find", ["array/make", "?x", "?y"],
   ["and", ["schema/fits?", "?x", "value/integer?"], ["schema/fits?", "?y", "value/integer?"],
     ["number/greaterThanOrEqualTo", "?x", 1], ["number/lessThanOrEqualTo", "?x", 6],
     ["number/greaterThanOrEqualTo", "?y", 1], ["number/lessThanOrEqualTo", "?y", 6],
     ["=", ["number/multiply", "?x", "?y"], 6]]],
 "names": ["find", "?name",
   ["and", ["schema/fits?", "?x", "value/integer?"],
     ["number/greaterThan", "?x", 7], ["number/lessThan", "?x", 11],
     ["=", "?name", ["string/concat", "room ", ["number/toString", "?x"]]]]]}
result
{
  "factors of 6": [[1,6],[2,3],[3,2],[6,1]],
  "names": ["room 10","room 8","room 9"]
}

When the values a waiting goal needs are infinitely many, they cannot each be tried, and the question fails, naming what the solver cannot reason about. A variable whose filters allow infinitely many values cannot be an answer either:

["query", ["exists", ["?x", "?y"],
  ["and", ["schema/fits?", "?x", "value/integer?"], ["schema/fits?", "?y", "value/integer?"],
    ["=", ["number/multiply", "?x", "?y"], 6]]]]
error
LogicError: ?x stands for infinitely many values that meet ["and",["schema/fits?","?x","value/integer?"],["schema/fits?","?y","value/integer?"],["=",["number/multiply","?x","?y"],6]], and ["=",["number/multiply","?x","?y"],6] waits for its value. The solver cannot reason about number/multiply of two unknowns: it decides sums of numbers times known numbers, comparisons of them, and equality of values. Bound ?x on both sides, or bind it with a relation goal.
["find", "?x", ["and", ["schema/fits?", "?x", "value/integer?"], ["number/greaterThan", "?x", 2]]]
error
LogicError: ?x stands for infinitely many values that meet ["and",["schema/fits?","?x","value/integer?"],["number/greaterThan","?x",2]], so they cannot each be an answer. Bound it on both sides, or ask only whether one exists, with exists or not.

How-to guide · task-oriented

Check every run of commands

Ask about every run of commands up to a length, and the states each passes through: a rule that must always hold, something that must eventually happen, and the shortest run that breaks a rule, with amounts of any size the solver works out.

This guide shows how to check a model of commands: a step function that takes a state and a command to the next state. Lion asks about every run of commands up to a length, which a schema like ["schema/arrayOf", "Command", 3] stands for, and about every state a run passes through. When a command carries an amount that a schema types, such as any positive whole number, the solver works the amounts out, so the check covers every amount, not only the ones a test tried.

Follow the states a run passes through

array/reductions gives every value array/reduce passes through, starting with the first, so for a step function it gives the states a run goes through:

["array/reductions",
  ["quote", [{"deposit": 5}, {"withdraw": 3}, {"withdraw": 4}]], 0,
  ["lambda", ["balance", "c"],
    ["cond", [["object/has?", "c", "deposit"], ["number/add", "balance", ["object/get", "c", "deposit"]]],
             ["else", ["number/subtract", "balance", ["object/get", "c", "withdraw"]]]]]]
result
[0,5,2,-2]

Check that a rule always holds

A rule always holds when no state of any run breaks it. Type the run with a schema, take each state with in, and ask whether one breaks the rule. Here the amounts are any positive whole numbers. A careful withdrawal, which refuses to take more than the balance, never takes the account below 0, while a careless one can:

["begin",
  ["schema", "Amount", ["schema/allOf", "value/integer?", ["lambda", ["n"], ["number/greaterThan", "n", 0]]]],
  ["schema", "Command", ["schema/anyOf", {"deposit": "Amount"}, {"withdraw": "Amount"}]],
  ["define", "careful", ["lambda", ["balance", "c"],
    ["cond", [["object/has?", "c", "deposit"], ["number/add", "balance", ["object/get", "c", "deposit"]]],
             [["number/lessThan", "balance", ["object/get", "c", "withdraw"]], "balance"],
             ["else", ["number/subtract", "balance", ["object/get", "c", "withdraw"]]]]]],
  ["define", "careless", ["lambda", ["balance", "c"],
    ["cond", [["object/has?", "c", "deposit"], ["number/add", "balance", ["object/get", "c", "deposit"]]],
             ["else", ["number/subtract", "balance", ["object/get", "c", "withdraw"]]]]]],
  ["define", "overdraws", ["lambda", ["step"],
    ["query", ["exists", ["?run", "?balance"],
      ["and", ["schema/fits?", "?run", ["schema/arrayOf", "Command", 3]],
              ["in", "?balance", ["array/reductions", "?run", 0, "step"]],
              ["number/lessThan", "?balance", 0]]]]]],
  {"careful": ["overdraws", "careful"], "careless": ["overdraws", "careless"]}]
result
{"careful":[],"careless":[{}]}

[] means no run of up to three commands, with any amounts, breaks the rule; [{}] means some run does.

Find the shortest run that breaks a rule

A rule with the run's length in its head, and the run only in its body, gives each length of a run that breaks the rule, however many runs of that length do. why shows a run of that length with amounts that break it:

["begin",
  ["schema", "Amount", ["schema/allOf", "value/integer?", ["lambda", ["n"], ["number/greaterThan", "n", 0]]]],
  ["schema", "Command", ["schema/anyOf", {"deposit": "Amount"}, {"withdraw": "Amount"}]],
  ["define", "careless", ["lambda", ["balance", "c"],
    ["cond", [["object/has?", "c", "deposit"], ["number/add", "balance", ["object/get", "c", "deposit"]]],
             ["else", ["number/subtract", "balance", ["object/get", "c", "withdraw"]]]]]],
  ["relation", "breaks", ["length"]],
  ["rule", ["breaks", "?n"],
    ["schema/fits?", "?run", ["schema/arrayOf", "Command", 3]],
    ["=", "?n", ["array/length", "?run"]],
    ["number/lessThan", ["array/reduce", "?run", 0, "careless"], 0]],
  {"shortest": ["aggregate/min", ["find", "?n", ["breaks", "?n"]]],
   "example": ["object/get", ["array/head", ["object/get", ["why", ["breaks", 1]], "because"]], "example"]}]
result
{"shortest":1,"example":{"?run":[{"withdraw":1}],"?n":1}}

Check that something eventually happens

Something must eventually happen when some state of every run meets it: array/some? over the states. Which runs have run their course is a goal about the run, such as its length. Here a heater starts at 0 and each command heats it by an amount between two bounds. In three steps it always reaches 20 degrees when each step heats by 7 to 10, and not when a step may heat by only 5:

["begin",
  ["define", "heater", ["lambda", ["low", "high"],
    {"heat": ["schema/allOf", "value/integer?",
      ["lambda", ["n"], ["boolean/and", ["number/greaterThanOrEqualTo", "n", "low"], ["number/lessThanOrEqualTo", "n", "high"]]]]}]],
  ["define", "always warm", ["lambda", ["command"],
    ["query", ["not", ["exists", ["?run"],
      ["and", ["schema/fits?", "?run", ["schema/arrayOf", "command", 3]],
              ["number/equals?", ["array/length", "?run"], 3],
              ["not", ["array/some?",
                ["array/reductions", "?run", 0, ["lambda", ["t", "c"], ["number/add", "t", ["object/get", "c", "heat"]]]],
                ["lambda", ["t"], ["number/greaterThanOrEqualTo", "t", 20]]]]]]]]]],
  {"heating by 5 to 10": ["always warm", ["heater", 5, 10]],
   "heating by 7 to 10": ["always warm", ["heater", 7, 10]]}]
result
{"heating by 5 to 10":[],"heating by 7 to 10":[{}]}

The schema here is made by a function the check is given, and is solved for as one written under a name is.

Know what it decides

A run's length is known in each shape the schema gives it, so the solver runs the step function on each command in turn, on amounts it works out, and decides what it decides everywhere: sums of numbers times known numbers, comparisons, and equality. A step it cannot decide, such as one that multiplies two amounts, waits for listed values, and so needs the amounts bounded.

How-to guide · task-oriented

Prove that every command keeps a rule

Prove for every state and every command that a step keeps a rule, see a state that breaks the proof, find the rules a proof needs, check a proof's certificate yourself, and ask whether one schema includes another.

This guide shows how to prove that a model keeps a rule: not for the runs a search tried, but for every state the rule allows and every command, which is the step of a proof by induction. A schema types the state and the command, and the solver works out every value they can take.

Prove that a command keeps a rule

An account has a balance and an overdraft limit, and a withdrawal that would go past the limit is refused. A rule is kept when no state the rule allows, and no command, leads to a state that breaks it. Ask whether such a state exists, under not: [{}] is the proof, for every account and every command, and [] says some state and command break the rule:

["begin",
  ["schema", "Account", {"balance": "value/integer?", "limit": "value/integer?"}],
  ["schema", "Amount", ["schema/allOf", "value/integer?", ["lambda", ["n"], ["number/greaterThan", "n", 0]]]],
  ["schema", "Command", ["schema/anyOf", {"deposit": "Amount"}, {"withdraw": "Amount"}]],
  ["define", "step", ["lambda", ["a", "c"], ["cond", [["object/has?", "c", "deposit"], {"balance": ["number/add", ["object/get", "a", "balance"], ["object/get", "c", "deposit"]], "limit": ["object/get", "a", "limit"]}], [["number/lessThan", ["number/add", ["object/get", "a", "balance"], ["object/get", "a", "limit"]], ["object/get", "c", "withdraw"]], "a"], ["else", {"balance": ["number/subtract", ["object/get", "a", "balance"], ["object/get", "c", "withdraw"]], "limit": ["object/get", "a", "limit"]}]]]],
  ["define", "within limit", ["lambda", ["a"], ["number/greaterThanOrEqualTo", ["number/add", ["object/get", "a", "balance"], ["object/get", "a", "limit"]], 0]]],
  ["define", "limit not negative", ["lambda", ["a"], ["number/greaterThanOrEqualTo", ["object/get", "a", "limit"], 0]]],
  ["define", "not overdrawn", ["lambda", ["a"], ["number/greaterThanOrEqualTo", ["object/get", "a", "balance"], 0]]],
  ["define", "keeps", ["lambda", ["rule"], ["query", ["not", ["exists", ["?a", "?c"], ["and", ["schema/fits?", "?a", "Account"], ["rule", "?a"], ["schema/fits?", "?c", "Command"], ["not", ["rule", ["step", "?a", "?c"]]]]]]]]],
  {"within limit": ["keeps", "within limit"], "not overdrawn": ["keeps", "not overdrawn"]}]
result
{"within limit":[{}],"not overdrawn":[]}

Staying within the limit is kept; never being overdrawn is not, since an account with a limit may go below 0.

See a state that breaks the proof

A rule that holds when the state that breaks the proof exists, and why, give that state and command. The state may never be reached from where the model starts: then the rule needs another one beside it that rules the state out.

["begin",
  ["schema", "Account", {"balance": "value/integer?", "limit": "value/integer?"}],
  ["schema", "Amount", ["schema/allOf", "value/integer?", ["lambda", ["n"], ["number/greaterThan", "n", 0]]]],
  ["schema", "Command", ["schema/anyOf", {"deposit": "Amount"}, {"withdraw": "Amount"}]],
  ["define", "step", ["lambda", ["a", "c"], ["cond", [["object/has?", "c", "deposit"], {"balance": ["number/add", ["object/get", "a", "balance"], ["object/get", "c", "deposit"]], "limit": ["object/get", "a", "limit"]}], [["number/lessThan", ["number/add", ["object/get", "a", "balance"], ["object/get", "a", "limit"]], ["object/get", "c", "withdraw"]], "a"], ["else", {"balance": ["number/subtract", ["object/get", "a", "balance"], ["object/get", "c", "withdraw"]], "limit": ["object/get", "a", "limit"]}]]]],
  ["define", "within limit", ["lambda", ["a"], ["number/greaterThanOrEqualTo", ["number/add", ["object/get", "a", "balance"], ["object/get", "a", "limit"]], 0]]],
  ["define", "limit not negative", ["lambda", ["a"], ["number/greaterThanOrEqualTo", ["object/get", "a", "limit"], 0]]],
  ["define", "not overdrawn", ["lambda", ["a"], ["number/greaterThanOrEqualTo", ["object/get", "a", "balance"], 0]]],
  ["define", "keeps", ["lambda", ["rule"], ["query", ["not", ["exists", ["?a", "?c"], ["and", ["schema/fits?", "?a", "Account"], ["rule", "?a"], ["schema/fits?", "?c", "Command"], ["not", ["rule", ["step", "?a", "?c"]]]]]]]]],
  ["relation", "breaks", ["rule"]],
  ["rule", ["breaks", ["quote", "not overdrawn"]], ["schema/fits?", "?a", "Account"], ["not overdrawn", "?a"], ["schema/fits?", "?c", "Command"], ["not", ["not overdrawn", ["step", "?a", "?c"]]]],
  ["object/get", ["array/head", ["object/get", ["why", ["breaks", ["quote", "not overdrawn"]]], "because"]], "example"]]
result
{"?a":{"balance":0,"limit":1},"?c":{"withdraw":1}}

Notice a proof that holds of no state

A proof that a rule is kept asks whether any state the rule allows, and any command, break it. When the rule allows no state at all, no state breaks it, and the proof holds of nothing. Write the proof as a rule, and why says which goals contradict each other, and "vacuous": true when they leave out the goal the proof denies:

["begin",
  ["schema", "Account", {"balance": "value/integer?", "limit": "value/integer?"}],
  ["schema", "Amount", ["schema/allOf", "value/integer?", ["lambda", ["n"], ["number/greaterThan", "n", 0]]]],
  ["schema", "Command", ["schema/anyOf", {"deposit": "Amount"}, {"withdraw": "Amount"}]],
  ["define", "step", ["lambda", ["a", "c"], ["cond", [["object/has?", "c", "deposit"], {"balance": ["number/add", ["object/get", "a", "balance"], ["object/get", "c", "deposit"]], "limit": ["object/get", "a", "limit"]}], ["else", {"balance": ["number/subtract", ["object/get", "a", "balance"], ["object/get", "c", "withdraw"]], "limit": ["object/get", "a", "limit"]}]]]],
  ["define", "never and always overdrawn", ["lambda", ["a"], ["boolean/and", ["number/greaterThanOrEqualTo", ["object/get", "a", "balance"], 0], ["number/lessThan", ["object/get", "a", "balance"], 0]]]],
  ["relation", "kept", ["rule"]],
  ["rule", ["kept", ["quote", "never and always overdrawn"]],
    ["not", ["exists", ["?a", "?c"], ["and", ["schema/fits?", "?a", "Account"], ["never and always overdrawn", "?a"], ["schema/fits?", "?c", "Command"], ["not", ["never and always overdrawn", ["step", "?a", "?c"]]]]]]],
  ["define", "told", ["array/head", ["object/get", ["why", ["kept", ["quote", "never and always overdrawn"]]], "because"]]],
  {"vacuous": ["object/get", "told", "vacuous"], "contradicting": ["object/get", "told", "contradicting"]}]
result
{
  "vacuous": true,
  "contradicting": [
    [
      "boolean/and",
      [
        "number/greaterThanOrEqualTo",
        ["object/get","?a","balance"],
        0
      ],
      ["number/lessThan",["object/get","?a","balance"],0]
    ]
  ]
}

The withdrawals have no limit here, so the proof that the account is never overdrawn and always overdrawn holds; why shows it holds only because no account meets the rule.

Find the rules a proof needs

A rule may be kept only together with others. Houdini's way finds the largest set of candidate rules that keeps itself: drop each candidate that some state the others allow, and some command, break, and ask again, until none is dropped. In Lion it is a few lines over the same question:

["begin",
  ["schema", "Account", {"balance": "value/integer?", "limit": "value/integer?"}],
  ["schema", "Amount", ["schema/allOf", "value/integer?", ["lambda", ["n"], ["number/greaterThan", "n", 0]]]],
  ["schema", "Command", ["schema/anyOf", {"deposit": "Amount"}, {"withdraw": "Amount"}]],
  ["define", "step", ["lambda", ["a", "c"], ["cond", [["object/has?", "c", "deposit"], {"balance": ["number/add", ["object/get", "a", "balance"], ["object/get", "c", "deposit"]], "limit": ["object/get", "a", "limit"]}], [["number/lessThan", ["number/add", ["object/get", "a", "balance"], ["object/get", "a", "limit"]], ["object/get", "c", "withdraw"]], "a"], ["else", {"balance": ["number/subtract", ["object/get", "a", "balance"], ["object/get", "c", "withdraw"]], "limit": ["object/get", "a", "limit"]}]]]],
  ["define", "within limit", ["lambda", ["a"], ["number/greaterThanOrEqualTo", ["number/add", ["object/get", "a", "balance"], ["object/get", "a", "limit"]], 0]]],
  ["define", "limit not negative", ["lambda", ["a"], ["number/greaterThanOrEqualTo", ["object/get", "a", "limit"], 0]]],
  ["define", "not overdrawn", ["lambda", ["a"], ["number/greaterThanOrEqualTo", ["object/get", "a", "balance"], 0]]],
  ["define", "keeps", ["lambda", ["rule"], ["query", ["not", ["exists", ["?a", "?c"], ["and", ["schema/fits?", "?a", "Account"], ["rule", "?a"], ["schema/fits?", "?c", "Command"], ["not", ["rule", ["step", "?a", "?c"]]]]]]]]],
  ["define", "candidates", {"within limit": "within limit", "limit not negative": "limit not negative", "not overdrawn": "not overdrawn"}],
  ["define", "holds all", ["lambda", ["names", "a"], ["array/every?", "names", ["lambda", ["n"], [["object/get", "candidates", "n"], "a"]]]]],
  ["define", "kept", ["lambda", ["names", "name"], ["not", ["exists", ["?a", "?c"], ["and", ["schema/fits?", "?a", "Account"], ["holds all", "names", "?a"], ["schema/fits?", "?c", "Command"], ["not", [["object/get", "candidates", "name"], ["step", "?a", "?c"]]]]]]]],
  ["define", "houdini", ["lambda", ["names"], ["begin", ["define", "survivors", ["find", "?n", ["and", ["in", "?n", "names"], ["kept", "names", "?n"]]]], ["cond", [["number/equals?", ["array/length", "survivors"], ["array/length", "names"]], "names"], ["else", ["houdini", "survivors"]]]]]],
  ["houdini", ["quote", ["within limit", "limit not negative", "not overdrawn"]]]]
result
["limit not negative","within limit"]

Check a proof yourself

Where a step of the solver stopped a rule, why shows a certificate for each case the solver split the goals into: the constraints, as whole-number sums compared with 0, and steps that each add earlier lines, each multiplied by a whole number, and over whole numbers may tighten the sum, dividing it by the greatest common divisor of its coefficients and rounding its constant down. The last line has no variables and is false, so the constraints have no solution. Checking it takes only arithmetic, so a small program can, without trusting the solver. Here one in Lion checks the certificate why gives:

["begin",
  ["relation", "limit", ["n"]],
  ["relation", "room", ["n"]],
  ["fact", ["limit", 3]],
  ["rule", ["room", "?n"], ["limit", "?n"], ["schema/fits?", "?x", "value/integer?"], ["number/greaterThan", "?x", 2], ["number/lessThan", "?x", "?n"]],
  ["define", "gcd", ["lambda", ["a", "b"], ["cond", [["number/equals?", "b", 0], ["number/absolute", "a"]], ["else", ["gcd", "b", ["number/remainder", "a", "b"]]]]]],
  ["define", "add line", ["lambda", ["total", "line", "times"], {"sum": ["array/reduce", ["object/keys", ["object/get", "line", "sum"]], ["object/get", "total", "sum"], ["lambda", ["acc", "name"], ["object/set", "acc", "name", ["number/add", ["cond", [["array/includes?", ["object/keys", "acc"], "name"], ["object/get", "acc", "name"]], ["else", 0]], ["number/multiply", "times", ["object/get", ["object/get", "line", "sum"], "name"]]]]]], "constant": ["number/add", ["object/get", "total", "constant"], ["number/multiply", "times", ["object/get", "line", "constant"]]], "relation": ["cond", [["string/equals?", ["object/get", "line", ["quote", "relation"]], ["quote", "="]], ["object/get", "total", ["quote", "relation"]]], [["boolean/or", ["string/equals?", ["object/get", "line", ["quote", "relation"]], ">"], ["string/equals?", ["object/get", "total", ["quote", "relation"]], ">"]], ">"], ["else", ">="]]}]],
  ["define", "tighten", ["lambda", ["line"], ["begin", ["define", "strict?", ["string/equals?", ["object/get", "line", ["quote", "relation"]], ">"]], ["define", "lowered", ["number/subtract", ["object/get", "line", "constant"], ["cond", ["strict?", 1], ["else", 0]]]], ["define", "divisor", ["array/reduce", ["object/values", ["object/get", "line", "sum"]], 0, "gcd"]], ["cond", [["number/lessThanOrEqualTo", "divisor", 1], {"sum": ["object/get", "line", "sum"], "constant": "lowered", "relation": ["cond", ["strict?", ">="], ["else", ["object/get", "line", ["quote", "relation"]]]]}], ["else", {"sum": ["array/reduce", ["object/keys", ["object/get", "line", "sum"]], {}, ["lambda", ["acc", "name"], ["object/set", "acc", "name", ["number/divide", ["object/get", ["object/get", "line", "sum"], "name"], "divisor"]]]], "constant": ["cond", [["string/equals?", ["object/get", "line", ["quote", "relation"]], ["quote", "="]], ["number/divide", "lowered", "divisor"]], ["else", ["number/floor", ["number/divide", "lowered", "divisor"]]]], "relation": ["cond", ["strict?", ">="], ["else", ["object/get", "line", ["quote", "relation"]]]]}]]]]],
  ["define", "false?", ["lambda", ["line"], ["boolean/and", ["array/every?", ["object/values", ["object/get", "line", "sum"]], ["lambda", ["k"], ["number/equals?", "k", 0]]], ["cond", [["string/equals?", ["object/get", "line", ["quote", "relation"]], ">="], ["number/lessThan", ["object/get", "line", "constant"], 0]], [["string/equals?", ["object/get", "line", ["quote", "relation"]], ">"], ["number/lessThanOrEqualTo", ["object/get", "line", "constant"], 0]], ["else", ["boolean/not", ["number/equals?", ["object/get", "line", "constant"], 0]]]]]]],
  ["define", "checks", ["lambda", ["given"], ["false?", ["array/head", ["array/slice", ["array/reduce", ["object/get", "given", "steps"], ["object/get", "given", "constraints"], ["lambda", ["lines", "step"], ["begin", ["define", "made", ["array/reduce", ["object/get", "step", "from"], {"sum": {}, "constant": 0, "relation": ["quote", "="]}, ["lambda", ["total", "use"], ["add line", "total", ["array/head", ["array/slice", "lines", ["array/head", "use"]]], ["array/head", ["array/tail", "use"]]]]]], ["array/concat", "lines", ["array/make", ["cond", [["object/get", "step", "tightened"], ["tighten", "made"]], ["else", "made"]]]]]]], -1]]]]],
  ["define", "proof", ["object/get", ["object/get", ["array/head", ["object/get", ["why", ["room", 3]], "because"]], "but"], "certificate"]],
  {"certificate": "proof", "every case checks": ["array/every?", "proof", "checks"]}]
result
{
  "certificate": [
    {
      "constraints": [
        {"constant":-2,"relation":">","sum":{"x":1}},
        {"constant":3,"relation":">","sum":{"x":-1}}
      ],
      "steps": [
        {"from":[[0,1]],"tightened":true},
        {"from":[[1,1]],"tightened":true},
        {"from":[[2,1],[3,1]],"tightened":true}
      ]
    }
  ],
  "every case checks": true
}

A case that needs the Omega test's dark and grey shadows over whole numbers receives a binary integer split tree (kind: "split") whose leaves are linear certificates. Lion also provides proof/valid?, a small trusted kernel that checks linear certificates, split trees, induction proofs, lemmas, and why derivations with plain arithmetic and without invoking the solver.

Prove properties by induction

For universal questions (["not", ["exists", ...]]) over recursive named schemas, unbounded lists (schema/arrayOf), or lower-bounded integers, the solver proves by structural or numeric induction whenever the recursive functions involved are pure, strictly decrease on a structural sub-part or lower-bounded integer measure, and return a uniform sort (number, truth, or list). For folds written with array/reduce over unbounded lists, the prover applies snoc-fold induction and proves the fold-step lemma by nested two-lookahead structural induction on the accumulator. Products of unknowns are tracked as exact polynomials so matching nonlinear terms cancel in induction steps:

["begin",
  ["schema", "PosInt", ["schema/allOf", "value/integer?", ["lambda", ["n"], ["number/greaterThanOrEqualTo", "n", 1]]]],
  ["schema", "Tree", ["schema/anyOf", {"leaf": "PosInt"}, {"node": {"left": "Tree", "right": "Tree", "val": "PosInt"}}]],
  ["define", "tree-sum", ["lambda", ["t"],
    ["cond",
      [["object/has?", "t", "leaf"], ["object/get", "t", "leaf"]],
      ["else", ["number/add",
        ["object/get", ["object/get", "t", "node"], "val"],
        ["tree-sum", ["object/get", ["object/get", "t", "node"], "left"]],
        ["tree-sum", ["object/get", ["object/get", "t", "node"], "right"]]]]]]],
  ["define", "sum-odd", ["lambda", ["n"],
    ["cond",
      [["number/lessThanOrEqualTo", "n", 0], 0],
      ["else", ["number/add", ["sum-odd", ["number/subtract", "n", 1]], ["number/subtract", ["number/multiply", 2, "n"], 1]]]]]],
  {"every tree sum is positive": ["query", ["not", ["exists", ["?t"],
     ["and", ["schema/fits?", "?t", "Tree"], ["number/lessThan", ["tree-sum", "?t"], 1]]]]],
   "sum of first n odd numbers is n^2": ["query", ["not", ["exists", ["?n"],
     ["and", ["schema/fits?", "?n", "value/integer?"],
             ["number/greaterThanOrEqualTo", "?n", 0],
             ["not", ["number/equals?", ["sum-odd", "?n"], ["number/multiply", "?n", "?n"]]]]]]]}]
result
{
  "every tree sum is positive": [{}],
  "sum of first n odd numbers is n^2": [{}]
}
["begin",
  ["define", "insert", ["lambda", ["x", "sorted"],
    ["cond",
      [["=", "sorted", ["quote", []]], ["array/make", "x"]],
      [["number/lessThanOrEqualTo", "x", ["array/head", "sorted"]], ["array/concat", ["array/make", "x"], "sorted"]],
      ["else", ["array/concat", ["array/make", ["array/head", "sorted"]], ["insert", "x", ["array/tail", "sorted"]]]]]]],
  ["define", "insertion-sort", ["lambda", ["xs"],
    ["array/reduce", "xs", ["quote", []], ["lambda", ["done", "x"], ["insert", "x", "done"]]]]],
  ["define", "ascending?", ["lambda", ["xs"],
    ["cond",
      [["number/lessThan", ["array/length", "xs"], 2], true],
      ["else", ["and", ["number/lessThanOrEqualTo", ["array/head", "xs"], ["array/head", ["array/tail", "xs"]]], ["ascending?", ["array/tail", "xs"]]]]]]],
  ["value/identity",
    ["not", ["exists", ["?xs"],
      ["and",
        ["schema/fits?", "?xs", ["schema/arrayOf", "value/integer?"]],
        ["not", [["lambda", ["out"], ["and", ["=", ["array/length", "out"], ["array/length", "?xs"]], ["ascending?", "out"]]], ["insertion-sort", "?xs"]]]]]]]]
result
true

Prove properties of rules by rule induction

proof/rules proves universally over all databases whose base relations fit their declared schemas that every row derived by a relation (or a record of mutually recursive relations) fits a target schema, returning a proof value checkable by proof/valid?:

["begin",
  ["schema", "PosCost", ["schema/allOf", "value/integer?", ["lambda", ["n"], ["number/greaterThanOrEqualTo", "n", 1]]]],
  ["schema", "PosEdge", {"from": "value/string?", "to": "value/string?", "cost": "PosCost"}],
  ["relation", "edge", ["from", "to", "cost"], {"schema": "PosEdge"}],
  ["relation", "path", ["from", "to", "cost"]],
  ["rule", ["path", "?a", "?b", ["aggregate/min", "?c"]], ["edge", "?a", "?b", "?c"]],
  ["rule", ["path", "?a", "?c", ["aggregate/min", ["number/add", "?c1", "?c2"]]], ["edge", "?a", "?b", "?c1"], ["path", "?b", "?c", "?c2"]],
  ["define", "p", ["proof/rules", "path", "PosEdge"]],
  {"proved": ["object/get", "p", "proved"], "kernel valid": ["proof/valid?", "p"]}]
result
{"proved":true,"kernel valid":true}

Prove goals, synthesize counterexamples, and compute exact bounds

proof/prove decides a universal or empirical goal in one call, returning a kernel-checked certificate or a concrete counterexample witness when a universal claim fails. proof/bounds computes exact tight min and max bounds across continuous linear, integer and mixed-integer linear, linear-fractional ratio (continuous Charnes-Cooper and integer Dinkelbach), bilinear/quadratic, and symbolic time/ constraints, with endpoint witnesses and kernel-valid minProof / maxProof certificates — checkable directly and bound to a threshold claim with 2-argument proof/valid?:

["begin",
  ["define", "rel", ["proof/bounds",
    ["number/divide", "?s", ["number/add", "?s", "?f"]],
    ["and",
      ["schema/fits?", "?s", "value/integer?"], ["schema/fits?", "?f", "value/integer?"],
      ["number/greaterThanOrEqualTo", "?s", ["number/add", ["number/multiply", 2, "?f"], 21]],
      ["number/lessThanOrEqualTo", ["number/add", "?s", "?f"], 43],
      ["number/greaterThanOrEqualTo", "?f", 6], ["number/lessThanOrEqualTo", "?f", 10],
      ["number/lessThanOrEqualTo", "?s", 37]]]],
  ["define", "rev", ["proof/bounds",
    ["number/multiply", "?n", "?p"],
    ["and",
      ["schema/fits?", "?n", "value/integer?"], ["schema/fits?", "?p", "value/number?"],
      ["number/greaterThanOrEqualTo", "?n", 4], ["number/lessThanOrEqualTo", "?n", 14],
      ["number/greaterThanOrEqualTo", "?p", 12], ["number/lessThanOrEqualTo", "?p", 22],
      ["number/lessThanOrEqualTo", ["number/add", "?p", ["number/multiply", 2, "?n"]], 36]]]],
  {"minReliabilityPct": ["number/round", ["number/multiply", 100, ["object/get", "rel", "min"]], 2],
   "maxReliabilityPct": ["number/round", ["number/multiply", 100, ["object/get", "rel", "max"]], 2],
   "clears83Pct": ["proof/valid?", "rel", {"atLeast": 0.83}],
   "minRevenue": ["object/get", "rev", "min"],
   "maxRevenue": ["object/get", "rev", "max"],
   "maxRevWitness": ["object/get", "rev", "witnessMax"]}]
result
{
  "minReliabilityPct": 83.33,
  "maxReliabilityPct": 86.05,
  "clears83Pct": true,
  "minRevenue": 48,
  "maxRevenue": 162,
  "maxRevWitness": {"?n":9,"?p":18}
}

Check TLA+ temporal liveness and refinement with proof/liveness and proof/refines

proof/liveness verifies TLA+-style leads-to properties (p ~> q) over finite state-transition systems under Weak Fairness (wf) and Strong Fairness (sf), excluding stuttering cycles and returning a kernel-verifiable liveness certificate or a lasso counterexample. proof/refines checks stuttering-invariant refinement (concrete => abstract) under a refinement mapping map:

["begin",
  ["define", "worker_step",
    ["lambda", ["state", "act"],
      ["cond",
        [["=", "act", "stutter"], "state"],
        [["=", "state", "idle"], "done"],
        ["else", "done"]]]],
  ["define", "live",
    ["proof/liveness", {
      "init": ["array/make", "idle"],
      "actions": ["array/make", "stutter", "work"],
      "step": "worker_step",
      "p": "idle",
      "q": "done",
      "wf": ["array/make", "work"]}]],
  ["define", "buf_step",
    ["lambda", ["s", "act"],
      ["cond",
        [["and", ["=", "act", "enqueue"],
          ["number/lessThan", ["number/add", ["object/get", "s", "c"], ["object/get", "s", "pending"]], 2]],
         {"c": ["object/get", "s", "c"], "pending": ["number/add", ["object/get", "s", "pending"], 1]}],
        [["and", ["=", "act", "flush"], ["number/greaterThan", ["object/get", "s", "pending"], 0]],
         {"c": ["number/add", ["object/get", "s", "c"], 1], "pending": ["number/subtract", ["object/get", "s", "pending"], 1]}],
        ["else", null]]]],
  ["define", "ref",
    ["proof/refines", {
      "concrete": {"init": ["array/make", {"c": 0, "pending": 0}], "actions": ["array/make", "enqueue", "flush"], "step": "buf_step"},
      "abstract": {"init": ["array/make", 0], "step": ["lambda", ["a1", "a2"], ["=", "a2", ["number/add", "a1", 1]]]},
      "map": ["lambda", ["s"], ["object/get", "s", "c"]]}]],
  {"livenessHolds": ["object/get", "live", "holds"],
   "livenessValid": ["proof/valid?", "live"],
   "refines": ["object/get", "ref", "refines"],
   "refinesValid": ["proof/valid?", "ref"],
   "stutteringSteps": ["object/get", "ref", "stutteringSteps"],
   "abstractSteps": ["object/get", "ref", "abstractSteps"]}]
result
{
  "livenessHolds": true,
  "livenessValid": true,
  "refines": true,
  "refinesValid": true,
  "stutteringSteps": 3,
  "abstractSteps": 3
}

Prove unbounded inductive invariants and bounded safety with proof/invariant and proof/bmc

proof/invariant discharges TLAPS-style inductive invariants (init => inv, inv && next => inv', and optional inv => property) symbolically via Lion's SMT solver over unbounded integers. proof/bmc performs Apalache-style symbolic bounded model checking up to depth, returning either a concrete counterexample trace or a kernel-verifiable bmc certificate:

["begin",
  ["define", "inv",
    ["proof/invariant", {
      "vars": {"a": "value/integer?", "b": "value/integer?"},
      "init": ["lambda", ["s"], ["and", ["=", ["object/get", "s", "a"], 10], ["=", ["object/get", "s", "b"], 0]]],
      "next": ["lambda", ["s", "s2"],
        ["and",
          ["number/greaterThanOrEqualTo", ["object/get", "s", "a"], 1],
          ["=", ["object/get", "s2", "a"], ["number/subtract", ["object/get", "s", "a"], 1]],
          ["=", ["object/get", "s2", "b"], ["number/add", ["object/get", "s", "b"], 1]]]],
      "invariant": ["lambda", ["s"],
        ["and",
          ["number/greaterThanOrEqualTo", ["object/get", "s", "a"], 0],
          ["number/greaterThanOrEqualTo", ["object/get", "s", "b"], 0],
          ["=", ["number/add", ["object/get", "s", "a"], ["object/get", "s", "b"]], 10]]],
      "property": ["lambda", ["s"], ["number/lessThanOrEqualTo", ["object/get", "s", "b"], 10]]}]],
  ["define", "bmc",
    ["proof/bmc", {
      "vars": "value/integer?",
      "depth": 3,
      "init": ["lambda", ["x"], ["=", "x", 0]],
      "next": ["lambda", ["x", "x2"], ["=", "x2", ["number/add", "x", 1]]],
      "property": ["lambda", ["x"], ["number/lessThanOrEqualTo", "x", 3]]}]],
  {"invariantProved": ["object/get", "inv", "proved"],
   "invariantValid": ["proof/valid?", ["object/get", "inv", "proof"]],
   "bmcProved": ["object/get", "bmc", "proved"],
   "bmcValid": ["proof/valid?", ["object/get", "bmc", "proof"]]}]
result
{
  "invariantProved": true,
  "invariantValid": true,
  "bmcProved": true,
  "bmcValid": true
}

Rewrite terms and decide SAT with kernel certificates using proof/simp and proof/sat

proof/simp normalizes terms under directed rewrite rules and certifies equality with replayable rewrite / rewrite-eq certificates. proof/sat runs CDCL with 1-UIP clause learning and emits a satisfying model or an independently checkable RUP UNSAT certificate:

["begin",
  ["define", "rew",
    ["proof/simp", {
      "rules": ["quote", [[["+", "?x", 0], "?x"], [["*", "?x", 1], "?x"], [["*", "?x", 0], 0]]],
      "term": ["quote", ["+", ["*", "n", 1], ["*", 7, 0]]],
      "target": ["quote", ["*", "n", 1]]}]],
  ["define", "unsat",
    ["proof/sat", ["quote", ["and", ["implies", "a", "b"], ["implies", "b", "c"], "a", ["not", "c"]]]]],
  {"simpEqual": ["object/get", "rew", "equal"],
   "simpNormalForm": ["object/get", "rew", "normalForm"],
   "simpValid": ["proof/valid?", ["object/get", "rew", "proof"]],
   "satSatisfiable": ["object/get", "unsat", "satisfiable"],
   "rupValid": ["proof/valid?", ["object/get", "unsat", "proof"]]}]
result
{
  "simpEqual": true,
  "simpNormalForm": "n",
  "simpValid": true,
  "satSatisfiable": false,
  "rupValid": true
}

Measure epistemic fragility with proof/sensitivity

proof/sensitivity checks every derivation of a ground conclusion in the database and reports whether it is resilient to any single-fact retraction, which base facts are critical (single points of failure), and the smallest joint retractions (minimalCuts) that break it:

["begin",
  ["relation", "edge", ["from", "to"]],
  ["relation", "reach", ["from", "to"]],
  ["fact", ["edge", "a", "b"], ["edge", "b", "d"], ["edge", "a", "c"], ["edge", "c", "d"]],
  ["rule", ["reach", "?x", "?y"], ["edge", "?x", "?y"]],
  ["rule", ["reach", "?x", "?z"], ["reach", "?x", "?y"], ["edge", "?y", "?z"]],
  ["proof/sensitivity", ["reach", "a", "d"]]]
result
{
  "critical": [],
  "holds": true,
  "minCutSize": 2,
  "minimalCuts": [
    [["edge","a","b"],["edge","a","c"]],
    [["edge","a","b"],["edge","c","d"]],
    [["edge","a","c"],["edge","b","d"]],
    [["edge","b","d"],["edge","c","d"]]
  ],
  "redundant": [["edge","a","b"],["edge","b","d"]],
  "resilient": true
}

Ask whether one schema includes another

schema/includes? says whether every value one schema allows fits another, exactly: by listing the first schema's values when it can list them, and by the solver otherwise — across value kinds, open records and lists, unbounded collections, and recursive or mutually recursive named schemas (including uninhabited recursive schemas). It refuses, and says why, only when neither can decide an arbitrary predicate:

["begin",
  ["schema", "PosInt", ["schema/allOf", "value/integer?", ["lambda", ["n"], ["number/greaterThan", "n", 0]]],
    "NonNeg", ["schema/allOf", "value/integer?", ["lambda", ["n"], ["number/greaterThanOrEqualTo", "n", 0]]],
    "PosTree", ["schema/anyOf", {"leaf": "PosInt"}, {"node": {"left": "PosTree", "right": "PosTree"}}],
    "NonNegTree", ["schema/anyOf", {"leaf": "NonNeg"}, {"node": {"left": "NonNegTree", "right": "NonNegTree"}}]],
  {"whole numbers are numbers": ["schema/includes?", "value/integer?", "value/number?"],
   "not every number is whole": ["schema/includes?", "value/number?", "value/integer?"],
   "strings are not numbers": ["schema/includes?", "value/string?", "value/number?"],
   "open record in exact record": ["schema/includes?", ["schema/open", {"x": "value/integer?"}], {"x": "value/integer?"}],
   "positive amounts are not negative": ["schema/includes?", "PosInt", "NonNeg"],
   "and not the other way": ["schema/includes?", "NonNeg", "PosInt"],
   "positive trees are non-negative trees": ["schema/includes?", "PosTree", "NonNegTree"],
   "lists are empty or non-empty": ["schema/includes?", ["schema/arrayOf", "value/integer?"], ["schema/anyOf", ["quote", []], ["schema/open", ["array/make", "value/integer?"], ["schema/arrayOf", "value/integer?"]]]],
   "a listed schema": ["schema/includes?", ["schema/anyOf", 1, 2], ["schema/anyOf", 1, 2, 3]]}]
result
{
  "whole numbers are numbers": true,
  "not every number is whole": false,
  "strings are not numbers": false,
  "open record in exact record": false,
  "positive amounts are not negative": true,
  "and not the other way": false,
  "positive trees are non-negative trees": true,
  "lists are empty or non-empty": true,
  "a listed schema": true
}

How-to guide · task-oriented

Verify protocols with symbolic invariants, BMC, liveness, rewriting, and SAT

Prove unbounded protocol invariants with proof/invariant, catch state-machine bugs with proof/bmc, prove progress under fairness with proof/liveness and refinement with proof/refines, and verify term rewrites and SAT UNSAT proofs with proof/simp, proof/sat, and proof/valid?.

Lion's verification library combines TLA+-style temporal checking, TLAPS-style inductive invariants, Apalache-style bounded model checking, directed term rewriting, and 1-UIP CDCL SAT solving — all zero-I/O and backed by certificates that proof/valid? checks independently without trusting the prover.

Prove an unbounded conservation invariant (proof/invariant)

To prove that an LsmSpine memtable and SSTable always conserve total Z-set weight across arbitrary inserts, retractions, and flushes, state init, invariant, next, and property over unbounded integers and verify the resulting certificate with proof/valid?:

["begin",
  ["define", "res",
    ["proof/invariant", {
      "vars": {"mem": "value/integer?", "sst": "value/integer?", "total": "value/integer?"},
      "init": ["lambda", ["s"],
        ["and", ["=", ["object/get", "s", "mem"], 0], ["=", ["object/get", "s", "sst"], 0], ["=", ["object/get", "s", "total"], 0]]],
      "invariant": ["lambda", ["s"],
        ["=", ["number/add", ["object/get", "s", "mem"], ["object/get", "s", "sst"]], ["object/get", "s", "total"]]],
      "next": ["lambda", ["s", "s2"],
        ["or",
          ["and",
            ["=", ["object/get", "s2", "mem"], ["number/add", ["object/get", "s", "mem"], 1]],
            ["=", ["object/get", "s2", "sst"], ["object/get", "s", "sst"]],
            ["=", ["object/get", "s2", "total"], ["number/add", ["object/get", "s", "total"], 1]]],
          ["and",
            ["=", ["object/get", "s2", "mem"], 0],
            ["=", ["object/get", "s2", "sst"], ["number/add", ["object/get", "s", "sst"], ["object/get", "s", "mem"]]],
            ["=", ["object/get", "s2", "total"], ["object/get", "s", "total"]]]]],
      "property": ["lambda", ["s"],
        ["=", ["number/add", ["object/get", "s", "mem"], ["object/get", "s", "sst"]], ["object/get", "s", "total"]]]
    }]],
  {"proved": ["object/get", "res", "proved"], "valid": ["proof/valid?", ["object/get", "res", "proof"]]}]
result
{"proved":true,"valid":true}

Catch a protocol bug with bounded model checking (proof/bmc)

When a transition breaks a safety property — here, a lost OCC update where committed advances without bumping rev — proof/bmc returns the minimal symbolic counterexample trace and depth:

["begin",
  ["define", "res",
    ["proof/bmc", {
      "bound": 3,
      "vars": {"rev": "value/integer?", "committed": "value/integer?"},
      "init": ["lambda", ["s"], ["and", ["=", ["object/get", "s", "rev"], 0], ["=", ["object/get", "s", "committed"], 0]]],
      "next": ["lambda", ["s", "s2"],
        ["and",
          ["=", ["object/get", "s2", "rev"], ["object/get", "s", "rev"]],
          ["=", ["object/get", "s2", "committed"], ["number/add", ["object/get", "s", "committed"], 1]]]],
      "property": ["lambda", ["s"], ["=", ["object/get", "s", "committed"], ["object/get", "s", "rev"]]]
    }]],
  {"proved": ["object/get", "res", "proved"], "depth": ["object/get", "res", "depth"], "trace": ["object/get", "res", "trace"]}]
result
{
  "proved": false,
  "depth": 1,
  "trace": [{"rev":0,"committed":0},{"rev":0,"committed":1}]
}

Prove progress under fairness (proof/liveness) and log refinement (proof/refines)

Weak fairness (wf) rules out infinite stuttering so a follower reaches a quorum of votes, and proof/refines checks that buffered local appends followed by quorum acknowledgements refine an abstract single-log commit counter:

["begin",
  ["define", "elect", ["lambda", ["v", "act"],
    ["cond",
      [["=", "act", "heartbeat"], "v"],
      [["number/lessThan", "v", 2], ["number/add", "v", 1]],
      ["else", null]]]],
  ["define", "live",
    ["proof/liveness", {
      "actions": ["array/make", "heartbeat", "grant_vote"],
      "init": ["array/make", 0],
      "p": 0,
      "q": 2,
      "step": "elect",
      "wf": ["array/make", "grant_vote"]
    }]],
  ["define", "wal", ["lambda", ["s", "act"],
    ["cond",
      [["boolean/and", ["=", "act", "buffer"], ["number/lessThan", ["object/get", "s", "pending"], 1]],
        {"committed": ["object/get", "s", "committed"], "pending": ["number/add", ["object/get", "s", "pending"], 1]}],
      [["boolean/and", ["=", "act", "commit"], ["boolean/and", ["number/greaterThan", ["object/get", "s", "pending"], 0], ["number/lessThan", ["object/get", "s", "committed"], 2]]],
        {"committed": ["number/add", ["object/get", "s", "committed"], 1], "pending": ["number/subtract", ["object/get", "s", "pending"], 1]}],
      ["else", null]]]],
  ["define", "ref_cert",
    ["proof/refines", {
      "abstract": {"init": ["array/make", 0], "step": ["lambda", ["a1", "a2"], ["=", "a2", ["number/add", "a1", 1]]]},
      "concrete": {"actions": ["array/make", "buffer", "commit"], "init": ["array/make", {"committed": 0, "pending": 0}], "step": "wal"},
      "map": ["lambda", ["s"], ["object/get", "s", "committed"]]
    }]],
  {"live": ["object/get", "live", "holds"], "liveValid": ["proof/valid?", "live"], "refines": ["object/get", "ref_cert", "refines"], "refinesValid": ["proof/valid?", "ref_cert"]}]
result
{
  "live": true,
  "liveValid": true,
  "refines": true,
  "refinesValid": true
}

Verify algebraic rewrites (proof/simp) and quorum exclusion (proof/sat)

proof/simp normalizes terms with a replayable rewrite certificate, and proof/sat proves that two candidates cannot both obtain a 2-of-3 quorum when every node casts at most one vote, producing a kernel-verified RUP UNSAT proof:

["begin",
  ["define", "simp",
    ["proof/simp", {
      "rules": ["quote", [[["zadd", "?x", 0], "?x"], [["zadd", "?x", ["zneg", "?x"]], 0]]],
      "term": ["quote", ["zadd", 5, ["zadd", 3, ["zneg", 3]]]],
      "target": ["quote", 5]
    }]],
  ["define", "quorum",
    ["proof/sat", ["quote",
      ["and",
        ["not", ["and", "a1", "b1"]],
        ["not", ["and", "a2", "b2"]],
        ["not", ["and", "a3", "b3"]],
        ["or", ["and", "a1", "a2"], ["and", "a1", "a3"], ["and", "a2", "a3"]],
        ["or", ["and", "b1", "b2"], ["and", "b1", "b3"], ["and", "b2", "b3"]]]]]],
  {"simpEqual": ["object/get", "simp", "equal"], "simpValid": ["proof/valid?", ["object/get", "simp", "proof"]], "quorumSat": ["object/get", "quorum", "satisfiable"], "quorumValid": ["proof/valid?", ["object/get", "quorum", "proof"]]}]
result
{
  "simpEqual": true,
  "simpValid": true,
  "quorumSat": false,
  "quorumValid": true
}

Combine SAT, arithmetic, polynomials, and EUF with DPLL(T) (proof/smt)

proof/smt runs a lazy DPLL(T) loop over CDCL SAT, exact linear integer/rational arithmetic, polynomial sum-of-squares, and EUF congruence closure with Nelson-Oppen equality sharing — returning a dpll-t certificate independently checked by proof/valid?:

["begin",
  ["define", "nelson_oppen",
    ["proof/smt", ["quote",
      ["and",
        ["<=", "x", "y"],
        ["<=", "y", "x"],
        ["!=", ["f", "x"], ["f", "y"]]]]]],
  ["define", "sos",
    ["proof/smt", ["quote",
      ["<", ["+", ["*", "a", "a"], ["*", "b", "b"], 1], 0]]]],
  {"noSat": ["object/get", "nelson_oppen", "satisfiable"],
   "noValid": ["proof/valid?", ["object/get", "nelson_oppen", "proof"]],
   "sosSat": ["object/get", "sos", "satisfiable"],
   "sosValid": ["proof/valid?", ["object/get", "sos", "proof"]]}]
result
{"noSat":false,"noValid":true,"sosSat":false,"sosValid":true}

Verify arrays, records, and automated k-induction

proof/smt also decides McCarthy's Theory of Arrays (select/store) and record updates (object/get/object/set) with kernel-checked array-axiom certificates and bidirectional Nelson-Oppen equality sharing, while proof/invariant accepts {"k": n} for automated k-induction on pipelines that are not 1-inductive:

["begin",
  ["define", "arr",
    ["proof/smt", ["quote",
      ["and",
        ["=", "b", ["store", "a", "i", 10]],
        ["<=", "i", "j"],
        ["<=", "j", "i"],
        ["<", ["select", "b", "j"], 10]]]]],
  ["define", "pipe",
    ["proof/invariant", {
      "vars": {"a": "value/integer?", "b": "value/integer?"},
      "init": ["lambda", ["s"], ["and", ["=", ["object/get", "s", "a"], 0], ["=", ["object/get", "s", "b"], 0]]],
      "next": ["lambda", ["s", "s2"], ["and", ["=", ["object/get", "s2", "a"], 1], ["=", ["object/get", "s2", "b"], ["object/get", "s", "a"]]]],
      "invariant": ["lambda", ["s"], ["number/greaterThanOrEqualTo", ["object/get", "s", "b"], 0]],
      "k": 3
    }]],
  {"arrValid": ["proof/valid?", ["object/get", "arr", "proof"]],
   "pipeK": ["object/get", "pipe", "k"],
   "pipeValid": ["proof/valid?", ["object/get", "pipe", "proof"]]}]
result
{"arrValid":true,"pipeK":2,"pipeValid":true}

Quantified axioms (forall E-matching) and automatic invariant strengthening

proof/smt supports universally quantified axioms via trigger-guided E-matching with kernel-checked forall-inst certificates, and proof/invariant accepts {"strengthen": true} to synthesize missing auxiliary linear lemmas from counterexamples to induction (PDR-lite) — emitting standard kernel-verified inductive-invariant proofs:

["begin",
  ["define", "q",
    ["proof/smt", ["quote",
      ["and",
        ["forall", ["x"], ["=", ["inv", ["inv", "x"]], "x"]],
        ["=", ["inv", "a"], "b"],
        ["!=", ["inv", "b"], "a"]]]]],
  ["define", "pdr",
    ["proof/invariant", {
      "vars": {"x": "value/integer?", "y": "value/integer?"},
      "init": ["lambda", ["s"], ["and", ["=", ["object/get", "s", "x"], 0], ["=", ["object/get", "s", "y"], 0]]],
      "next": ["lambda", ["s", "s2"],
        ["and",
          ["=", ["object/get", "s2", "x"], ["number/add", ["object/get", "s", "x"], 1]],
          ["=", ["object/get", "s2", "y"], ["number/add", ["object/get", "s", "y"], ["object/get", "s", "x"]]]]],
      "invariant": ["lambda", ["s"], ["number/greaterThanOrEqualTo", ["object/get", "s", "y"], 0]],
      "strengthen": true
    }]],
  {"forallSat": ["object/get", "q", "satisfiable"],
   "forallValid": ["proof/valid?", ["object/get", "q", "proof"]],
   "pdrProved": ["object/get", "pdr", "proved"],
   "pdrLemmas": ["object/get", "pdr", "strengthened"],
   "pdrValid": ["proof/valid?", ["object/get", "pdr", "proof"]]}]
result
{
  "forallSat": false,
  "forallValid": true,
  "pdrProved": true,
  "pdrLemmas": ["x >= 0"],
  "pdrValid": true
}

Duality-certified linear & mixed-integer optimization (proof/optimize)

["proof/optimize", "min" | "max", objective, goal] computes the exact global optimum and achieving witness over continuous or integer constraints, paired with a Farkas / Chvátal-Gomory / Omega split duality proof bound to optimal so proof/valid? rejects any tampered value:

["begin",
  ["define", "fleet",
    ["proof/optimize", "min",
      ["number/add", ["number/multiply", 420, "?s"], ["number/multiply", 980, "?m"]],
      ["and",
        ["schema/fits?", "?s", "value/integer?"],
        ["schema/fits?", "?m", "value/integer?"],
        ["number/greaterThanOrEqualTo", "?s", 0],
        ["number/greaterThanOrEqualTo", "?m", 0],
        ["number/greaterThanOrEqualTo", ["number/add", "?s", "?m"], 3],
        ["number/greaterThanOrEqualTo",
          ["number/add", ["number/multiply", 120, "?s"], ["number/multiply", 320, "?m"]],
          700]]]],
  {"optimalCost": ["object/get", "fleet", "optimal"],
   "witness": ["object/get", "fleet", "witness"],
   "kernelValid": ["proof/valid?", "fleet"],
   "atLeast2240": ["proof/valid?", "fleet", {"atLeast": 2240}]}]
result
{
  "optimalCost": 2380,
  "witness": {"?s":1,"?m":2},
  "kernelValid": true,
  "atLeast2240": true
}

Structured chains (proof/calc), SMT bit-vectors & ADTs, general LTL, and WAL trace validation (proof/trace)

proof/calc verifies transitive equational and inequality chains step by step; proof/smt extends DPLL(T) to fixed-width bit-vectors, algebraic datatypes, array extensionality, and E-graph-modulo forall E-matching; proof/liveness checks general LTL formulas (<>[], []<>, U) and unbounded variant ranking functions; and proof/trace validates live concrete or WAL state logs against abstract specs:

["begin",
  ["define", "chain",
    ["proof/calc", {
      "assumptions": ["quote", [[">=", "x", 0]]],
      "start": "x",
      "steps": ["array/make",
        {"op": "<=", "to": ["quote", ["+", "x", 2]]},
        {"op": "<", "to": ["quote", ["+", ["+", "x", 2], 1]]}]
    }]],
  ["define", "bv",
    ["proof/smt", {
      "vars": {"x": "bv8"},
      "formula": ["quote", ["not", ["bv/eq", ["bv/xor", ["bv/xor", "x", ["bv/const", 42, 8]], ["bv/const", 42, 8]], "x"]]]
    }]],
  ["define", "adt",
    ["proof/smt", ["quote", ["=", ["nil"], ["cons", 1, "xs"]]]]],
  ["define", "ltl",
    ["proof/liveness", {
      "actions": ["array/make", "dec", "stutter"],
      "init": ["array/make", 2],
      "step": ["lambda", ["s", "act"],
        ["cond",
          [["=", "act", "stutter"], "s"],
          [["number/greaterThan", "s", 0], ["number/subtract", "s", 1]],
          ["else", 0]]],
      "wf": ["array/make", "dec"],
      "formula": ["quote", ["eventually", ["always", 0]]]
    }]],
  ["define", "tr",
    ["proof/trace", {
      "init": ["lambda", ["s"], ["=", ["object/get", "s", "epoch"], 0]],
      "actions": {
        "advance": ["lambda", ["s1", "s2"], ["=", ["object/get", "s2", "epoch"], ["number/add", ["object/get", "s1", "epoch"], 1]]]
      },
      "actionProperty": ["lambda", ["s1", "s2"], ["number/greaterThanOrEqualTo", ["object/get", "s2", "epoch"], ["object/get", "s1", "epoch"]]],
      "trace": ["quote", [{"epoch": 0}, {"epoch": 1}, {"epoch": 1}, {"epoch": 2}]]
    }]],
  {"calcOp": ["object/get", "chain", "op"],
   "calcValid": ["proof/valid?", "chain"],
   "bvValid": ["proof/valid?", "bv"],
   "adtValid": ["proof/valid?", "adt"],
   "ltlHolds": ["object/get", "ltl", "holds"],
   "ltlValid": ["proof/valid?", "ltl"],
   "traceActions": ["object/get", "tr", "matchedActions"],
   "traceValid": ["proof/valid?", "tr"]}]
result
{
  "calcOp": "<",
  "calcValid": true,
  "bvValid": true,
  "adtValid": true,
  "ltlHolds": true,
  "ltlValid": true,
  "traceActions": ["advance","stutter","advance"],
  "traceValid": true
}

Unbounded symbolic refinement and ranking-function liveness

Pass concrete.vars to proof/refines to verify stuttering refinement over infinite state spaces via SMT rather than finite-state exploration, and pass variant (plus deadlockFree) to proof/liveness to prove unbounded termination:

["begin",
  ["define", "symRef",
    ["proof/refines", {
      "concrete": {
        "vars": {"c": "value/integer?", "buf": "value/integer?"},
        "init": ["lambda", ["s"], ["and", ["=", ["object/get", "s", "c"], 0], ["=", ["object/get", "s", "buf"], 0]]],
        "invariant": ["lambda", ["s"], ["and", ["number/greaterThanOrEqualTo", ["object/get", "s", "c"], 0], ["number/greaterThanOrEqualTo", ["object/get", "s", "buf"], 0]]],
        "next": ["lambda", ["s", "s2"],
          ["or",
            ["and", ["=", ["object/get", "s2", "c"], ["object/get", "s", "c"]], ["=", ["object/get", "s2", "buf"], ["number/add", ["object/get", "s", "buf"], 1]]],
            ["and", ["number/greaterThan", ["object/get", "s", "buf"], 0], ["=", ["object/get", "s2", "c"], ["number/add", ["object/get", "s", "c"], 1]], ["=", ["object/get", "s2", "buf"], ["number/subtract", ["object/get", "s", "buf"], 1]]]]]
      },
      "abstract": {
        "init": ["lambda", ["a"], ["=", ["object/get", "a", "c"], 0]],
        "next": ["lambda", ["a", "a2"], ["=", ["object/get", "a2", "c"], ["number/add", ["object/get", "a", "c"], 1]]]
      },
      "map": ["lambda", ["s"], {"c": ["object/get", "s", "c"]}]
    }]],
  ["define", "symLive",
    ["proof/liveness", {
      "vars": {"n": "value/integer?"},
      "init": ["lambda", ["s"], ["number/greaterThanOrEqualTo", ["object/get", "s", "n"], 0]],
      "invariant": ["lambda", ["s"], ["number/greaterThanOrEqualTo", ["object/get", "s", "n"], 0]],
      "next": ["lambda", ["s", "s2"], ["and", ["number/greaterThan", ["object/get", "s", "n"], 0], ["=", ["object/get", "s2", "n"], ["number/subtract", ["object/get", "s", "n"], 1]]]],
      "q": ["lambda", ["s"], ["=", ["object/get", "s", "n"], 0]],
      "variant": ["lambda", ["s"], ["object/get", "s", "n"]],
      "deadlockFree": true
    }]],
  {"refines": ["object/get", "symRef", "refines"],
   "refinesValid": ["proof/valid?", "symRef"],
   "liveHolds": ["object/get", "symLive", "holds"],
   "liveValid": ["proof/valid?", "symLive"]}]
result
{
  "refines": true,
  "refinesValid": true,
  "liveHolds": true,
  "liveValid": true
}

Named actions, action properties, and conditional rewriting

proof/invariant accepts named actions, named invariant conjuncts, and TLA+-style actionProperty constraints; proof/simp supports guarded conditional rules [lhs, rhs, when] under assumptions; and proof/smt handles McCarthy array extensionality and E-graph-modulo forall E-matching:

["begin",
  ["define", "inv",
    ["proof/invariant", {
      "vars": {"epoch": "value/integer?"},
      "init": ["lambda", ["s"], ["=", ["object/get", "s", "epoch"], 0]],
      "invariant": {"nonNegative": ["lambda", ["s"], ["number/greaterThanOrEqualTo", ["object/get", "s", "epoch"], 0]]},
      "actions": {"bump": ["lambda", ["s", "s2"], ["=", ["object/get", "s2", "epoch"], ["number/add", ["object/get", "s", "epoch"], 1]]]},
      "actionProperty": ["lambda", ["s", "s2"], ["number/greaterThanOrEqualTo", ["object/get", "s2", "epoch"], ["object/get", "s", "epoch"]]]
    }]],
  ["define", "condSimp",
    ["proof/simp", {
      "assumptions": ["quote", [[">=", "x", 0]]],
      "rules": ["quote", [[["abs", "?a"], "?a", [">=", "?a", 0]]]],
      "term": ["quote", ["abs", "x"]],
      "target": "x"
    }]],
  ["define", "ext",
    ["proof/smt",
      ["quote", ["and", ["!=", "a", "b"], ["=", ["select", "a", 0], 7], ["forall", ["i"], ["=", ["select", "a", "i"], ["select", "b", "i"]]]]]]],
  ["define", "ematch",
    ["proof/smt",
      ["quote", ["and", ["=", "a", "b"], ["=", ["f", "a"], "c"], ["forall", ["x"], ["=", ["g", ["f", "x"]], "x"]], ["not", ["=", ["g", "c"], "b"]]]]]],
  {"invProved": ["object/get", "inv", "proved"],
   "invValid": ["proof/valid?", ["object/get", "inv", "proof"]],
   "simpProved": ["object/get", "condSimp", "proved"],
   "simpValid": ["proof/valid?", "condSimp"],
   "extUnsat": ["boolean/not", ["object/get", "ext", "satisfiable"]],
   "extValid": ["proof/valid?", "ext"],
   "ematchUnsat": ["boolean/not", ["object/get", "ematch", "satisfiable"]],
   "ematchValid": ["proof/valid?", "ematch"]}]
result
{
  "invProved": true,
  "invValid": true,
  "simpProved": true,
  "simpValid": true,
  "extUnsat": true,
  "extValid": true,
  "ematchUnsat": true,
  "ematchValid": true
}

Live rendered proof certificates (@lionlang/ui)

Because Lion documentation itself is a Lion program, pages can run solvers at build time and render interactive-grade ui/proof cards directly into the document:

proof/calc — Transitive Chain
Verified by proof/valid?
x < (x + 2) + 1 verified
Inspect JSON proof certificate
{
  "end": [
    "+",
    [
      "+",
      "x",
      2
    ],
    1
  ],
  "op": "<",
  "proof": {
    "end": [
      "+",
      [
        "+",
        "x",
        2
      ],
      1
    ],
    "kind": "calc",
    "op": "<",
    "start": "x",
    "steps": [
      {
        "from": "x",
        "op": "<=",
        "proof": {
          "atoms": {
            "1": [
              ">=",
              "x",
              0
            ],
            "2": [
              ">",
              "x",
              [
                "+",
                "x",
                2
              ]
            ]
          },
          "formula": [
            "and",
            [
              ">=",
              "x",
              0
            ],
            [
              ">",
              "x",
              [
                "+",
                "x",
                2
              ]
            ]
          ],
          "kind": "dpll-t",
          "lemmas": [
            {
              "certificate": {
                "constraints": [
                  {
                    "constant": -2,
                    "relation": ">",
                    "sum": {}
                  }
                ],
                "steps": [
                  {
                    "from": [
                      [
                        0,
                        1
                      ]
                    ],
                    "tightened": false
                  }
                ]
              },
              "clause": [
                -2
              ]
            }
          ],
          "rup": {
            "clauses": [
              [
                -3,
                1
              ],
              [
                -3,
                2
              ],
              [
                3,
                -1,
                -2
              ],
              [
                3
              ],
              [
                -2
              ]
            ],
            "hints": [
              [
                5,
                4,
                2
              ]
            ],
            "kind": "rup",
            "proof": [
              []
            ]
          }
        },
        "to": [
          "+",
          "x",
          2
        ]
      },
      {
        "from": [
          "+",
          "x",
          2
        ],
        "op": "<",
        "proof": {
          "atoms": {
            "1": [
              ">=",
              "x",
              0
            ],
            "2": [
              ">=",
              [
                "+",
                "x",
                2
              ],
              [
                "+",
                [
                  "+",
                  "x",
                  2
                ],
                1
              ]
            ]
          },
          "formula": [
            "and",
            [
              ">=",
              "x",
              0
            ],
            [
              ">=",
              [
                "+",
                "x",
                2
              ],
              [
                "+",
                [
                  "+",
                  "x",
                  2
                ],
                1
              ]
            ]
          ],
          "kind": "dpll-t",
          "lemmas": [
            {
              "certificate": {
                "constraints": [
                  {
                    "constant": -1,
                    "relation": ">=",
                    "sum": {}
                  }
                ],
                "steps": [
                  {
                    "from": [
                      [
                        0,
                        1
                      ]
                    ],
                    "tightened": false
                  }
                ]
              },
              "clause": [
                -2
              ]
            }
          ],
          "rup": {
            "clauses": [
              [
                -3,
                1
              ],
              [
                -3,
                2
              ],
              [
                3,
                -1,
                -2
              ],
              [
                3
              ],
              [
                -2
              ]
            ],
            "hints": [
              [
                5,
                4,
                2
              ]
            ],
            "kind": "rup",
            "proof": [
              []
            ]
          }
        },
        "to": [
          "+",
          [
            "+",
            "x",
            2
          ],
          1
        ]
      }
    ]
  },
  "proved": true,
  "start": "x"
}
proof/smt — 8-bit Bit-Vector XOR
Verified via bit-blasted RUP/LRAT
(x ^ 42) ^ 42 = x (bv8) verified
Inspect JSON proof certificate
{
  "proof": {
    "atoms": {},
    "formula": [
      "not",
      [
        "bv/eq",
        [
          "bv/xor",
          [
            "bv/xor",
            "x",
            [
              "bv/const",
              42,
              8
            ]
          ],
          [
            "bv/const",
            42,
            8
          ]
        ],
        "x"
      ]
    ],
    "kind": "dpll-t",
    "lemmas": [],
    "rup": {
      "clauses": [
        [
          -9
        ],
        [
          10
        ],
        [
          -11
        ],
        [
          12
        ],
        [
          -13
        ],
        [
          14
        ],
        [
          -15
        ],
        [
          -16
        ],
        [
          -17,
          1,
          9
        ],
        [
          -17,
          -1,
          -9
        ],
        [
          17,
          -1,
          9
        ],
        [
          17,
          1,
          -9
        ],
        [
          -18,
          2,
          10
        ],
        [
          -18,
          -2,
          -10
        ],
        [
          18,
          -2,
          10
        ],
        [
          18,
          2,
          -10
        ],
        [
          -19,
          3,
          11
        ],
        [
          -19,
          -3,
          -11
        ],
        [
          19,
          -3,
          11
        ],
        [
          19,
          3,
          -11
        ],
        [
          -20,
          4,
          12
        ],
        [
          -20,
          -4,
          -12
        ],
        [
          20,
          -4,
          12
        ],
        [
          20,
          4,
          -12
        ],
        [
          -21,
          5,
          13
        ],
        [
          -21,
          -5,
          -13
        ],
        [
          21,
          -5,
          13
        ],
        [
          21,
          5,
          -13
        ],
        [
          -22,
          6,
          14
        ],
        [
          -22,
          -6,
          -14
        ],
        [
          22,
          -6,
          14
        ],
        [
          22,
          6,
          -14
        ],
        [
          -23,
          7,
          15
        ],
        [
          -23,
          -7,
          -15
        ],
        [
          23,
          -7,
          15
        ],
        [
          23,
          7,
          -15
        ],
        [
          -24,
          8,
          16
        ],
        [
          -24,
          -8,
          -16
        ],
        [
          24,
          -8,
          16
        ],
        [
          24,
          8,
          -16
        ],
        [
          -25
        ],
        [
          26
        ],
        [
          -27
        ],
        [
          28
        ],
        [
          -29
        ],
        [
          30
        ],
        [
          -31
        ],
        [
          -32
        ],
        [
          -33,
          17,
          25
        ],
        [
          -33,
          -17,
          -25
        ],
        [
          33,
          -17,
          25
        ],
        [
          33,
          17,
          -25
        ],
        [
          -34,
          18,
          26
        ],
        [
          -34,
          -18,
          -26
        ],
        [
          34,
          -18,
          26
        ],
        [
          34,
          18,
          -26
        ],
        [
          -35,
          19,
          27
        ],
        [
          -35,
          -19,
          -27
        ],
        [
          35,
          -19,
          27
        ],
        [
          35,
          19,
          -27
        ],
        [
          -36,
          20,
          28
        ],
        [
          -36,
          -20,
          -28
        ],
        [
          36,
          -20,
          28
        ],
        [
          36,
          20,
          -28
        ],
        [
          -37,
          21,
          29
        ],
        [
          -37,
          -21,
          -29
        ],
        [
          37,
          -21,
          29
        ],
        [
          37,
          21,
          -29
        ],
        [
          -38,
          22,
          30
        ],
        [
          -38,
          -22,
          -30
        ],
        [
          38,
          -22,
          30
        ],
        [
          38,
          22,
          -30
        ],
        [
          -39,
          23,
          31
        ],
        [
          -39,
          -23,
          -31
        ],
        [
          39,
          -23,
          31
        ],
        [
          39,
          23,
          -31
        ],
        [
          -40,
          24,
          32
        ],
        [
          -40,
          -24,
          -32
        ],
        [
          40,
          -24,
          32
        ],
        [
          40,
          24,
          -32
        ],
        [
          -41,
          33,
          1
        ],
        [
          -41,
          -33,
          -1
        ],
        [
          41,
          -33,
          1
        ],
        [
          41,
          33,
          -1
        ],
        [
          -42,
          34,
          2
        ],
        [
          -42,
          -34,
          -2
        ],
        [
          42,
          -34,
          2
        ],
        [
          42,
          34,
          -2
        ],
        [
          -43,
          35,
          3
        ],
        [
          -43,
          -35,
          -3
        ],
        [
          43,
          -35,
          3
        ],
        [
          43,
          35,
          -3
        ],
        [
          -44,
          36,
          4
        ],
        [
          -44,
          -36,
          -4
        ],
        [
          44,
          -36,
          4
        ],
        [
          44,
          36,
          -4
        ],
        [
          -45,
          37,
          5
        ],
        [
          -45,
          -37,
          -5
        ],
        [
          45,
          -37,
          5
        ],
        [
          45,
          37,
          -5
        ],
        [
          -46,
          38,
          6
        ],
        [
          -46,
          -38,
          -6
        ],
        [
          46,
          -38,
          6
        ],
        [
          46,
          38,
          -6
        ],
        [
          -47,
          39,
          7
        ],
        [
          -47,
          -39,
          -7
        ],
        [
          47,
          -39,
          7
        ],
        [
          47,
          39,
          -7
        ],
        [
          -48,
          40,
          8
        ],
        [
          -48,
          -40,
          -8
        ],
        [
          48,
          -40,
          8
        ],
        [
          48,
          40,
          -8
        ],
        [
          -49,
          -41
        ],
        [
          -49,
          -42
        ],
        [
          -49,
          -43
        ],
        [
          -49,
          -44
        ],
        [
          -49,
          -45
        ],
        [
          -49,
          -46
        ],
        [
          -49,
          -47
        ],
        [
          -49,
          -48
        ],
        [
          49,
          41,
          42,
          43,
          44,
          45,
          46,
          47,
          48
        ],
        [
          -49
        ]
      ],
      "hints": [
        [
          48,
          8,
          39,
          110,
          79
        ],
        [
          48,
          8,
          123,
          37,
          109,
          77
        ],
        [
          47,
          7,
          35,
          106,
          75
        ],
        [
          47,
          7,
          125,
          33,
          105,
          73
        ],
        [
          46,
          6,
          30,
          102,
          72
        ],
        [
          46,
          6,
          127,
          32,
          101,
          70
        ],
        [
          45,
          5,
          27,
          98,
          67
        ],
        [
          45,
          5,
          129,
          25,
          97,
          65
        ],
        [
          44,
          4,
          22,
          94,
          64
        ],
        [
          44,
          4,
          131,
          24,
          93,
          62
        ],
        [
          43,
          3,
          19,
          90,
          59
        ],
        [
          43,
          3,
          133,
          17,
          89,
          57
        ],
        [
          42,
          2,
          14,
          86,
          56
        ],
        [
          42,
          2,
          135,
          16,
          85,
          54
        ],
        [
          41,
          136,
          122,
          124,
          126,
          128,
          130,
          132,
          134,
          121,
          1,
          11,
          82,
          51
        ],
        [
          137,
          136,
          122,
          124,
          126,
          128,
          130,
          132,
          134,
          121,
          81,
          1,
          9,
          41,
          49
        ]
      ],
      "kind": "rup",
      "proof": [
        [
          -8,
          -48
        ],
        [
          -48
        ],
        [
          -7,
          -47
        ],
        [
          -47
        ],
        [
          -6,
          -46
        ],
        [
          -46
        ],
        [
          -5,
          -45
        ],
        [
          -45
        ],
        [
          -4,
          -44
        ],
        [
          -44
        ],
        [
          -3,
          -43
        ],
        [
          -43
        ],
        [
          -2,
          -42
        ],
        [
          -42
        ],
        [
          -1
        ],
        []
      ]
    }
  },
  "proved": true,
  "satisfiable": false
}

How-to guide · task-oriented

Govern ontologies, prevent join fanout, and enforce workflow policies

Attach description, synonyms, certified, and foreign-key references to relations, avoid aggregate join fanout, and enforce completion invariants and counterfactual assuming diffs.

Relations in Lion carry first-class ontology metadata directly in their declaration: description, synonyms, certified, and foreign-key references. That metadata round-trips through snapshots, Prolly trees, HTTP /v1/ontology/*, MCP lion_search / lion_answerable, and Apache Ossie 3-file YAML bundles.

Declare governed relations with foreign keys and synonyms

Attach description, synonyms, certified, and references to each base relation, then enforce workflow completion invariants (such as requiring verification before a task can be marked "done") and resolve decision contradictions declaratively:

["begin",
  ["relation", "work_item", ["id", "title", "status"], {
    "key": ["id"],
    "certified": true,
    "description": "Tracked engineering work item",
    "synonyms": ["task", "todo"]
  }],
  ["relation", "verification", ["item_id", "proof"], {
    "certified": true,
    "description": "Test or benchmark evidence backing a work item",
    "references": {"item_id": ["work_item", "id"]},
    "synonyms": ["evidence"]
  }],
  ["invariant", ["and", ["work_item", "?id", "?_", "done"], ["not", ["verification", "?id", "?_"]]], {"assert": "none"}],
  ["fact",
    ["work_item", "t1", "Ship ontology guide", "done"],
    ["verification", "t1", "build-docs passed"]],
  ["query", ["and", ["work_item", "?id", "?title", "done"], ["verification", "?id", "?proof"]]]]
result
[
  {
    "id": "t1",
    "title": "Ship ontology guide",
    "proof": "build-docs passed"
  }
]

Avoid aggregate join fanout by pre-aggregating detail tables

Joining a measured parent relation (supplier) with a repeating child relation (shipment) inside aggregate/sum inflates the parent budget once per matching child row. Lion's declarative lint flags this statically; pre-aggregating the child relation in its own rule keeps every total exact:

["begin",
  ["relation", "supplier", ["id", "budget"], {"key": ["id"], "certified": true, "description": "Approved suppliers"}],
  ["relation", "shipment", ["id", "supplier_id", "qty"], {"key": ["id"], "references": {"supplier_id": ["supplier", "id"]}, "description": "Individual deliveries"}],
  ["relation", "shipped_by_supplier", ["supplier_id", "total_qty"]],
  ["relation", "supplier_summary", ["total_budget", "total_qty"]],
  ["fact",
    ["supplier", "s1", 100],
    ["shipment", "sh1", "s1", 4],
    ["shipment", "sh2", "s1", 6]],
  ["rule", ["shipped_by_supplier", "?s", ["aggregate/sum", "?q"]], ["shipment", "?_", "?s", "?q"]],
  ["rule", ["supplier_summary", ["aggregate/sum", "?b"], ["aggregate/sum", "?q"]],
    ["supplier", "?s", "?b"],
    ["shipped_by_supplier", "?s", "?q"]],
  ["query", ["supplier_summary", "?budget", "?qty"]]]
result
[{"budget":100,"qty":10}]

Preview policy impact with assuming before committing

Use assuming to test how a proposed change alters derived violations or active decisions without mutating the underlying database:

["begin",
  ["relation", "decision", ["id", "topic", "choice"], {"key": ["id"], "certified": true, "description": "Recorded design choices"}],
  ["relation", "supersedes", ["newer", "older"], {"references": {"newer": ["decision", "id"], "older": ["decision", "id"]}}],
  ["relation", "active_decision", ["id", "topic", "choice"]],
  ["rule", ["active_decision", "?id", "?t", "?c"], ["decision", "?id", "?t", "?c"], ["not", ["supersedes", "?_", "?id"]]],
  ["fact", ["decision", "d1", "lint", "typescript"]],
  {"before": ["find", "?c", ["active_decision", "?_", "lint", "?c"]],
   "after": ["assuming",
     ["fact", ["decision", "d2", "lint", "lion-datalog"], ["supersedes", "d2", "d1"]],
     ["find", "?c", ["active_decision", "?_", "lint", "?c"]]]}]
result
{"before":["typescript"],"after":["lion-datalog"]}

How-to guide · task-oriented

Build Graph-as-Code apps and shareable public HTML UI artifacts

Declare schema, logic rules, counterfactual assuming branches, formal proofs, and 35 interactive ui/* elements in one Lion JSON program, test them live in the Playground, and export standalone HTML artifacts with lion artifact.

With @lionlang/ui, a single Lion JSON program can declare its governed data schema, recursive Datalog rules, counterfactual assuming branches, kernel-verified SMT/PDR proofs, and its entire interactive user interface — then compile into a standalone public HTML page with zero backend required.

Explore all 14 live public artifacts and the Studio

Open the Lion Artifact Gallery & Live Studio to explore 6 signature Lion-only business-value proof apps alongside 8 Graph-as-Code & verification blueprints — toggle the Lion JSON editor on demand, share programs via URL hash, or export 100% single-file offline HTML pages:

UI primitives (36 elements)

@lionlang/ui provides 36 pure JSON UI constructors rendered by a zero-dependency, XSS-safe DOM renderer:

  • Layout & Visual Hierarchy: ui/section (numbered visual chapters), ui/stack, ui/row, ui/grid, ui/split, ui/card, ui/hero, ui/tabs, ui/accordion, ui/divider
  • Relational Data & Graphs: ui/graph (clickable non-overlapping SVG with ego-network focus & skip-layer arcs), ui/table (clickable linked rows), ui/chart, ui/metric, ui/kv, ui/list, ui/diff, ui/badge, ui/alert, ui/progress, ui/code, ui/text, ui/heading, ui/link, ui/timeline, ui/source
  • Interactive Controls: ui/button, ui/input, ui/textarea, ui/select, ui/toggle, ui/checkbox, ui/slider
  • Logic & Verification: ui/why (derivation provenance tree), ui/proof (live SMT counterexample models, proof/optimize witnesses, liveness lassos, and expandable DPLL(T)/PDR theory lemma cards), ui/frame

Build a pure Graph-as-Code logic + UI specification

Every Lion UI artifact uses plain relations for state and a view function returning nested UI nodes. Because UI nodes are plain JSON objects, you can inspect and test them in pure Lion without a browser:

["begin",
  ["relation", "entity", ["id", "kind"], {"key": ["id"]}],
  ["relation", "link", ["from", "to", "rel"], {"references": {"from": ["entity", "id"], "to": ["entity", "id"]}}],
  ["relation", "reaches", ["src", "dst"]],
  ["fact",
    ["entity", "planner", "agent"],
    ["entity", "verifier", "agent"],
    ["entity", "ledger", "service"],
    ["link", "planner", "verifier", "submits_to"],
    ["link", "verifier", "ledger", "commits"]],
  ["rule", ["reaches", "?a", "?b"], ["link", "?a", "?b", "?_"]],
  ["rule", ["reaches", "?a", "?c"], ["link", "?a", "?b", "?_"], ["reaches", "?b", "?c"]],
  {"mainReaches": ["find", "?d", ["reaches", "planner", "?d"]],
   "branchEdges": ["assuming", ["fact", ["link", "planner", "ledger", "direct_bypass"]],
     ["find", "?r", ["link", "planner", "ledger", "?r"]]]}]
result
{
  "mainReaches": ["ledger","verifier"],
  "branchEdges": ["direct_bypass"]
}

Export a standalone public HTML artifact from the CLI

lion artifact packages/examples/graph-as-code-agent-memory.json \
  --title "Agent Knowledge Graph" \
  --out agent-knowledge-graph.html

Open agent-knowledge-graph.html directly from disk or host it on any static file server (GitHub Pages, S3, Cloudflare Pages, Vercel) — all queries, counterfactual branches, and formal proofs execute locally in the visitor's browser.

How-to guide · task-oriented

Check the shape of data

Say what a value must be with a schema, find where data does not fit, and have a relation refuse rows that do not.

This guide shows how to check data against a schema. A schema says what a value must be, and Lion has one rule for what fits one: a function is a predicate, a record or list fits part by part, and any other value fits a value equal to it.

Describe a record

Write the record you expect, with a schema in place of each value. schema/fits? asks whether a value fits, and schema/problems lists every place where it does not:

["begin",
  ["define", "Order",
    {"id": "value/integer?",
     "status": ["schema/anyOf", "open", "shipped"],
     "note": ["schema/optional", "value/string?"]}],
  ["define", "incoming", ["quote", {"id": "7", "status": "opne"}]],
  {"fits": ["schema/fits?", "incoming", "Order"],
   "problems": ["schema/problems", "incoming", "Order"]}]
result
{
  "fits": false,
  "problems": [
    {"path":["id"],"expected":"value/integer?","found":"7"},
    {
      "path": ["status"],
      "expected": ["schema/anyOf","open","shipped"],
      "found": "opne"
    }
  ]
}

Each problem has the path to the part that does not fit, the schema that was expected there, and the value that was found. A record schema fits a record with the same keys, so a key it does not name is a problem too, with only what was found. Wrap the record in schema/open to allow other keys.

Allow keys you do not name

A record schema says every key the record has. To check some keys and let the rest be, wrap the record in schema/open. To let one key be left out, give it schema/optional:

["begin",
  ["define", "incoming", ["quote", {"id": 7, "status": "open", "rush": true}]],
  {"exact": ["schema/problems", "incoming",
     {"id": "value/integer?", "status": "value/string?"}],
   "open": ["schema/fits?", "incoming",
     ["schema/open", {"id": "value/integer?", "status": "value/string?"}]],
   "optional": ["schema/fits?", "incoming",
     {"id": "value/integer?", "status": "value/string?",
      "rush": ["schema/optional", "value/boolean?"],
      "note": ["schema/optional", "value/string?"]}]}]
result
{
  "exact": [{"path":["rush"],"found":true}],
  "open": true,
  "optional": true
}

Build one schema from two

A record schema is exact, so schema/allOf of two record schemas with different keys fits nothing: each refuses the other's keys. Give schema/open the second as the schema of the rest instead. The keys the first names are checked against it, and the record of the other keys against the second, so the two make one exact schema. Any schema can check the rest, such as schema/recordOf for keys you cannot name in advance:

["begin",
  ["schema", "Entity", {"id": "value/integer?", "created": "value/string?"}],
  ["schema", "Line", {"sku": "value/string?", "qty": "value/integer?"}],
  ["schema", "Stock", ["schema/open", "Entity", "Line"]],
  ["define", "incoming", ["quote", {"id": 4, "created": "2026-11-18", "sku": "a1", "qty": 2, "rush": true}]],
  {"allOf": ["schema/fits?", "incoming", ["schema/allOf", "Entity", "Line"]],
   "composed": ["schema/problems", "incoming", "Stock"],
   "string extras": ["schema/fits?", "incoming",
     ["schema/open", "Entity", ["schema/recordOf", "value/string?"]]]}]
result
{
  "allOf": false,
  "composed": [{"path":["rush"],"found":true}],
  "string extras": false
}

Check lists and plain values

A list of schemas fits a list of the same length, item by item, which suits a pair or a triple. schema/arrayOf fits a list of any length whose items all fit, and schema/recordOf a record whose values all fit. Any value that is not a function, a record, or a list fits a value equal to it, so data is a schema for itself:

{"a pair": ["schema/fits?",
   ["array/make", 2, "kg"],
   ["array/make", "value/number?", ["schema/anyOf", "kg", "lb"]]],
 "a longer list": ["schema/fits?",
   ["array/make", 2, "kg", "net"],
   ["array/make", "value/number?", "value/string?"]],
 "every item": ["schema/fits?", ["array/make", 1, 2, 3], ["schema/arrayOf", "value/integer?"]],
 "every value": ["schema/problems", {"tea": 2, "cup": "one"}, ["schema/recordOf", "value/integer?"]],
 "the same data": ["schema/fits?", ["quote", {"a": [1, 2]}], ["quote", {"a": [1, 2]}]]}
result
{
  "a pair": true,
  "a longer list": false,
  "every item": true,
  "every value": [{"path":["cup"],"expected":"value/integer?","found":"one"}],
  "the same data": true
}

Give a schema a name

schema declares a schema under a name, the way relation declares a relation. The name is then a predicate, and other schemas can use it. A shape can name its own schema, which describes nested data, and one form can declare several schemas that name each other:

["begin",
  ["schema", "Line",
    {"sku": "value/string?",
     "qty": ["schema/allOf", "value/integer?",
       ["lambda", ["n"], ["number/greaterThan", "n", 0]]]}],
  ["schema", "Order", {"id": "value/integer?", "lines": ["schema/arrayOf", "Line"]}],
  ["schema", "Folder", {"name": "value/string?", "folders": ["schema/arrayOf", "Folder"]}],
  ["schema",
    "Expr", ["schema/anyOf", "value/number?", "Sum"],
    "Sum", {"add": ["schema/arrayOf", "Expr"]}],
  {"order": ["Order", ["quote", {"id": 1, "lines": [{"sku": "a1", "qty": 2}]}]],
   "expr": ["Expr", ["quote", {"add": [1, {"add": [2, 3]}]}]],
   "bad line": ["schema/problems",
     ["quote", {"id": 1, "lines": [{"sku": "a1", "qty": 0}]}], "Order"],
   "folder": ["Folder",
     ["quote", {"name": "root", "folders": [{"name": "src", "folders": []}]}]]}]
result
{
  "order": true,
  "expr": true,
  "bad line": [
    {
      "path": ["lines",0,"qty"],
      "expected": ["lambda",["n"],["number/greaterThan","n",0]],
      "found": 0
    }
  ],
  "folder": true
}

A lambda is a schema for whatever it returns true for. One that fails, as number/greaterThan does on a string, simply does not fit. A misspelled name is different: "value/intger?" in a shape is an error that suggests value/integer?, and not a schema that nothing fits.

Stop on data that does not fit

schema/assert returns the value when it fits, so it can wrap the place where data comes in. When the value does not fit, it fails and says where:

["begin",
  ["schema", "Order", {"id": "value/integer?", "status": ["schema/anyOf", "open", "shipped"]}],
  ["object/get",
    ["schema/assert", ["quote", {"id": 7, "status": "opne"}], "Order"],
    "id"]]
error
LogicError: {"id":7,"status":"opne"} does not fit "Order": "status" must fit ["schema/anyOf","open","shipped"] but is "opne".

Sort incoming data with rules

A schema check is a call like any other, so it works as a goal in a rule, under not, and in a find. Here raw documents go in as facts. One rule keeps the ones that fit, and takes them apart with a pattern, and another turns each problem of the others into a row:

["begin",
  ["relation", "inbox", ["doc"]],
  ["relation", "order", ["id", "status"], {"key": "id"}],
  ["relation", "rejected", ["doc", "where"]],
  ["schema", "Order", {"id": "value/integer?", "status": ["schema/anyOf", "open", "shipped"]}],
  ["fact",
    ["inbox", {"id": 1, "status": "open"}],
    ["inbox", {"id": 2, "status": "opne"}],
    ["inbox", {"id": "3", "status": "shipped"}]],
  ["rule", ["order", "?id", "?status"],
    ["inbox", ["schema/allOf", "Order", {"id": "?id", "status": "?status"}]]],
  ["rule", ["rejected", "?doc", ["object/get", "?problem", "path"]],
    ["inbox", "?doc"], ["in", "?problem", ["schema/problems", "?doc", "Order"]]],
  {"orders": ["query", ["order", "?id", "?status"]],
   "rejected": ["query", ["rejected", "?doc", "?where"], {"order": "where"}],
   "how many": ["aggregate/count",
     ["find", "?doc", ["and", ["inbox", "?doc"], ["not", ["Order", "?doc"]]]]]}]
result
{
  "orders": [{"id":1,"status":"open"}],
  "rejected": [
    {"doc":{"id":"3","status":"shipped"},"where":["id"]},
    {"doc":{"id":2,"status":"opne"},"where":["status"]}
  ],
  "how many": 2
}

Have a relation refuse rows that do not fit

The relation option "schema" names a declared schema that every row must fit. A row is checked as a record of its columns, so the schema names every column, or is a schema/open record that names some. A fact form that would add a row that does not fit fails, and changes nothing:

["begin",
  ["schema", "Order", {"id": "value/integer?", "status": ["schema/anyOf", "open", "shipped"]}],
  ["relation", "order", ["id", "status"], {"key": "id", "schema": "Order"}],
  ["fact", ["order", 1, "open"]],
  ["fact", ["order", 2, "opne"]]]
error
LogicError: Adding this fact breaks an invariant, so nothing changed. The invariant expected no answers but found 1, such as {"id":2,"status":"opne"}: ["and",["order","?id","?status"],["not",["Order",{"id":"?id","status":"?status"}]]]. {"id":2,"status":"opne"} does not fit "Order": "status" must fit ["schema/anyOf","open","shipped"] but is "opne".

The option stands for the invariant that the message shows, so it is kept like every invariant, and the message ends with where the row does not fit.

Require that a value exists elsewhere

A relation with one column is a predicate, so it is a schema: a value fits person when it is one of its rows. As the schema of a column, that is a foreign key. Retracting a person who is still someone's parent is refused:

["begin",
  ["relation", "person", ["name"]],
  ["schema", "Kin", {"parent": "person", "child": "person"}],
  ["relation", "parent", ["parent", "child"], {"schema": "Kin"}],
  ["fact", ["person", "ada"], ["person", "ben"], ["parent", "ada", "ben"]],
  ["retract", ["person", "ben"]]]
error
LogicError: Retracting this fact breaks an invariant, so nothing changed. The invariant expected no answers but found 1, such as {"parent":"ada","child":"ben"}: ["and",["parent","?parent","?child"],["not",["Kin",{"parent":"?parent","child":"?child"}]]]. {"parent":"ada","child":"ben"} does not fit "Kin": "child" must fit "person" but is "ben".

One fact form can add a person and their parent together, since a form is checked once it has made all of its changes.

Check data from TypeScript

Bind the data to a name in the environment, and check it against a schema the database holds:

import { run } from "@lionlang/core/evaluation/evaluate";
import { LogicDatabase } from "@lionlang/core/logic/database";
import { stdlib } from "@lionlang/core/modules";
import { Effect } from "effect";

const database = new LogicDatabase();
await Effect.runPromise(
  run(["schema", "Order", { id: "value/integer?" }], stdlib, { database })
);

const problems = await Effect.runPromise(
  run(["schema/problems", "incoming", "Order"], { ...stdlib, incoming }, { database })
);

An empty list means incoming fits. Schemas are data like the rest of a Lion program, so a program can add them while it runs, and a snapshot saves the ones a database holds.

How-to guide · task-oriented

Take data apart

Bind logic variables to the parts of records and lists with patterns, in relation calls, queries, and rules.

This guide shows how to get at the parts of nested data in a rule or query. A schema with a logic variable in it is a pattern: the variable takes the value it meets, so one goal checks a value and takes it apart.

Bind the fields of a record

Write the record you are looking for as an argument of a relation call, with a variable where a value should go. The call asks for the rows that fit, and binds the variables:

["begin",
  ["relation", "inbox", ["doc"]],
  ["fact",
    ["inbox", {"type": "refund", "id": 3}],
    ["inbox", {"type": "refund", "id": 4}],
    ["inbox", {"type": "order", "id": 1}]],
  ["query", ["inbox", {"type": "refund", "id": "?id"}], {"order": "id"}]]
result
[{"id":3},{"id":4}]

A record in a pattern fits a record with the same keys. The value "refund" fits only itself, so it picks the rows, and ?id takes the id of each.

Take some keys of a larger record

schema/open fits a record whatever other keys it has, so a pattern can name only the keys it needs. ?_ fits any value and binds nothing, which asks only that a key is there:

["begin",
  ["relation", "inbox", ["doc"]],
  ["fact",
    ["inbox", {"type": "order", "id": 1, "note": "gift"}],
    ["inbox", {"type": "order", "id": 2, "rush": true}],
    ["inbox", {"type": "refund", "id": 3}]],
  {"orders": ["find", "?id", ["inbox", ["schema/open", {"type": "order", "id": "?id"}]]],
   "with a note": ["find", "?id", ["inbox", ["schema/open", {"id": "?id", "note": "?_"}]]]}]
result
{"orders":[1,2],"with a note":[1]}

Keep the rest of a record or list

Give schema/open a second schema, and what the record leaves over must fit it: the record of the keys it does not name. A variable there takes the rest, so a rule can strip the keys it knows and pass on the others. Around a list, the rest is the list of the items after the ones it names:

["begin",
  ["relation", "inbox", ["doc"]],
  ["relation", "extras", ["id", "rest"]],
  ["fact",
    ["inbox", {"type": "order", "id": 1, "note": "gift"}],
    ["inbox", {"type": "order", "id": 2, "rush": true, "via": "phone"}],
    ["inbox", {"type": "refund", "id": 3}]],
  ["rule", ["extras", "?id", "?rest"],
    ["inbox", ["schema/open", {"type": "order", "id": "?id"}, "?rest"]]],
  {"extras": ["query", ["extras", "?id", "?rest"], {"order": "id"}],
   "first and others": ["query",
     ["schema/fits?", ["array/make", "a", "b", "c"], ["schema/open", ["array/make", "?first"], "?others"]]]}]
result
{
  "extras": [
    {"id":1,"rest":{"note":"gift"}},
    {"id":2,"rest":{"rush":true,"via":"phone"}}
  ],
  "first and others": [{"first":"a","others":["b","c"]}]
}

The parts a pattern names and its rest, put back together, are the value: a key the record names is never in the rest.

Go through a list inside a record

The element of in can be a pattern too. Here one goal takes the lines out of each order, and in takes each line apart, so a rule turns nested documents into rows that other rules can count:

["begin",
  ["relation", "inbox", ["doc"]],
  ["relation", "line", ["order", "sku", "qty"]],
  ["relation", "units", ["order", "total"]],
  ["fact",
    ["inbox", ["quote", {"id": 1, "lines": [{"sku": "a1", "qty": 2}, {"sku": "b2", "qty": 1}]}]],
    ["inbox", ["quote", {"id": 2, "lines": [{"sku": "a1", "qty": 5}]}]]],
  ["rule", ["line", "?order", "?sku", "?qty"],
    ["inbox", {"id": "?order", "lines": "?lines"}],
    ["in", {"sku": "?sku", "qty": "?qty"}, "?lines"]],
  ["rule", ["units", "?order", ["aggregate/sum", "?qty"]],
    ["line", "?order", "?sku", "?qty"]],
  {"lines": ["find", ["array/make", "?order", "?sku", "?qty"], ["line", "?order", "?sku", "?qty"]],
   "units": ["query", ["units", "?order", "?total"], {"order": "order"}]}]
result
{
  "lines": [[1,"a1",2],[1,"b2",1],[2,"a1",5]],
  "units": [{"order":1,"total":3},{"order":2,"total":5}]
}

Try every value a schema allows

When nothing else binds the value schema/fits? checks, a schema that can list the values it allows binds the value to each one that fits. So a few lines check every case up to a bound: here every run of at most two moves, to find those that leave an account below zero. ["schema/arrayOf", "Move", 2] allows lists of at most two moves:

["begin",
  ["schema", "Move", ["schema/anyOf", 2, -1, -3]],
  {"moves": ["find", "?m", ["schema/fits?", "?m", "Move"]],
   "runs": ["aggregate/count", ["find", "?run", ["schema/fits?", "?run", ["schema/arrayOf", "Move", 2]]]],
   "below zero": ["find", "?run",
     ["and",
       ["schema/fits?", "?run", ["schema/arrayOf", "Move", 2]],
       ["number/lessThan", ["aggregate/sum", "?run"], 0]]]}]
result
{
  "moves": [-3,-1,2],
  "runs": 13,
  "below zero": [[-3],[-3,-3],[-3,-1],[-3,2],[-1],[-1,-3],[-1,-1],[2,-3]]
}

Data, records and lists of such schemas, schema/anyOf, value/boolean?, and schema/arrayOf with a most length can list what they allow. A schema that allows infinitely many values, or a predicate that does not say which it accepts, cannot, so the goal needs another to bind the value first:

["find", "?n", ["schema/fits?", "?n", "value/integer?"]]
error
LogicError: ?n stands for infinitely many values that meet ["and",["schema/fits?","?n","value/integer?"]], so they cannot each be an answer. Bound it on both sides, or ask only whether one exists, with exists or not.

Take a list apart by position

A list of variables fits a list of the same length. = matches one side against the other, so it binds the variables on either side:

["begin",
  ["relation", "route", ["stops"]],
  ["fact",
    ["route", ["array/make", "oslo", "bergen", "voss"]],
    ["route", ["array/make", "rome", "pisa", "turin"]],
    ["route", ["array/make", "kyoto", "nara"]]],
  ["query",
    ["and", ["route", "?stops"], ["=", ["array/make", "?from", "?_", "?to"], "?stops"]],
    {"order": "from"}]]
result
[
  {"stops":["oslo","bergen","voss"],"from":"oslo","to":"voss"},
  {"stops":["rome","pisa","turin"],"from":"rome","to":"turin"}
]

The route with two stops has no answer, since the pattern has three places.

Check a part while you take it

Every schema works in a pattern. A predicate says what a part must be, schema/allOf checks a part and binds it, and schema/anyOf offers a choice. A predicate can be made from a variable that another goal binds:

["begin",
  ["relation", "reading", ["sensor", "celsius"]],
  ["relation", "limit", ["celsius"]],
  ["fact",
    ["reading", "attic", 30], ["reading", "cellar", 10], ["reading", "roof", "n/a"],
    ["limit", 25]],
  {"numbers": ["find", "?sensor", ["reading", "?sensor", "value/number?"]],
   "hot": ["find", "?sensor",
     ["and", ["limit", "?max"],
       ["reading", "?sensor", ["func/partial", "number/lessThan", "?max"]]]],
   "attic or roof": ["query",
     ["reading", ["schema/anyOf", "attic", "roof"], "?celsius"]],
   "checked": ["query",
     ["reading", "?sensor", ["schema/allOf", "value/number?", "?celsius"]],
     {"order": "sensor"}]}]
result
{
  "numbers": ["attic","cellar"],
  "hot": ["attic"],
  "attic or roof": [{"celsius":30},{"celsius":"n/a"}],
  "checked": [
    {"sensor":"attic","celsius":30},
    {"sensor":"cellar","celsius":10}
  ]
}

Take apart a value you already have

schema/fits? is the same goal for a value that another goal bound, or one from outside. With a named schema and a pattern in one schema/allOf, a rule keeps the documents that fit and takes them apart at once:

["begin",
  ["relation", "inbox", ["doc"]],
  ["relation", "order", ["id", "status"], {"key": "id"}],
  ["schema", "Order", {"id": "value/integer?", "status": ["schema/anyOf", "open", "shipped"]}],
  ["fact",
    ["inbox", {"id": 1, "status": "open"}],
    ["inbox", {"id": 2, "status": "opne"}],
    ["inbox", {"id": "3", "status": "shipped"}]],
  ["rule", ["order", "?id", "?status"],
    ["inbox", ["schema/allOf", "Order", {"id": "?id", "status": "?status"}]]],
  {"orders": ["query", ["order", "?id", "?status"]],
   "one value": ["query",
     ["schema/fits?", ["quote", {"id": 7, "status": "open"}], {"id": "?id", "status": "?status"}]]}]
result
{
  "orders": [{"id":1,"status":"open"}],
  "one value": [{"id":7,"status":"open"}]
}

The order of the goals in a rule does not matter: a goal that binds through a pattern gives what it gives when another goal has bound its variables first.

How-to guide · task-oriented

Explain a result

Find out why a fact holds: which rule derived it, from which facts, all the way down. Or why it does not: which rules could have given it, and what stopped each one.

This guide shows how to use why to trace a derived fact back to its sources, and to find what a fact that does not hold is missing.

Ask why a fact holds

Give why the fact, with no variables:

["begin",
  ["relation", "edge", ["from", "to"]],
  ["relation", "path", ["from", "to"]],
  ["fact", ["edge", "a", "b"], ["edge", "b", "c"]],
  ["rule", ["path", "?x", "?y"], ["edge", "?x", "?y"]],
  ["rule", ["path", "?x", "?z"], ["path", "?x", "?y"], ["edge", "?y", "?z"]],
  ["why", ["path", "a", "c"]]]
result
{
  "fact": ["path","a","c"],
  "rule": [
    "rule",
    ["path","?x","?z"],
    ["path","?x","?y"],
    ["edge","?y","?z"]
  ],
  "because": [
    {
      "fact": ["path","a","b"],
      "rule": ["rule",["path","?x","?y"],["edge","?x","?y"]],
      "because": [{"fact":["edge","a","b"],"given":true}]
    },
    {"fact":["edge","b","c"],"given":true}
  ]
}

Each level names the fact, the rule that derived it, and the facts because of which it holds. A fact you added says "given": true.

See which way is told

A row can come about in several ways. why tells the one a new database finds first: rules run in the order they were added, round after round from the facts, and of the answers of the first rule that gives the row, the least. So a path is explained by its shortest chain of edges, here the edge from a to c that came after the path was derived through b:

["begin",
  ["relation", "edge", ["from", "to"]],
  ["relation", "path", ["from", "to"]],
  ["fact", ["edge", "a", "b"], ["edge", "b", "c"]],
  ["rule", ["path", "?x", "?y"], ["edge", "?x", "?y"]],
  ["rule", ["path", "?x", "?z"], ["path", "?x", "?y"], ["edge", "?y", "?z"]],
  ["query", ["path", "?x", "?y"]],
  ["fact", ["edge", "a", "c"]],
  ["why", ["path", "a", "c"]]]
result
{
  "fact": ["path","a","c"],
  "rule": ["rule",["path","?x","?y"],["edge","?x","?y"]],
  "because": [{"fact":["edge","a","c"],"given":true}]
}

The tree does not depend on the order the facts were added in, or on what the database derived before they changed: a database given the three edges at once tells the same.

Read filters and negations

Filters appear as check, with the values they were called on, and negations as absent, with the goal that had no match and why it had none:

["begin",
  ["relation", "user", ["name", "age"]],
  ["relation", "banned", ["name"]],
  ["relation", "eligible", ["name"]],
  ["fact", ["user", "ana", 34]],
  ["rule", ["eligible", "?n"],
    ["user", "?n", "?age"],
    ["number/greaterThan", "?age", 18],
    ["not", ["banned", "?n"]]],
  ["why", ["eligible", "ana"]]]
result
{
  "fact": ["eligible","ana"],
  "rule": [
    "rule",
    ["eligible","?n"],
    ["user","?n","?age"],
    ["number/greaterThan","?age",18],
    ["not",["banned","?n"]]
  ],
  "because": [
    {"fact":["user","ana",34],"given":true},
    {"check":["number/greaterThan",34,18]},
    {"absent":["banned","ana"],"because":[]}
  ]
}

See how a figure was worked out

A rule that computes a value with = shows the computation as a check too, with the values it was given in place of its variables, so a ratio or a total traces to the rows it came from. Every check, evaluated as it stands, is true, so anyone can work the arithmetic again:

["begin",
  ["relation", "line", ["item", "usd_m"]],
  ["relation", "gross_margin", ["percent"]],
  ["fact", ["line", "revenue", 409.8], ["line", "cost of services", 301.5]],
  ["rule", ["gross_margin", "?percent"],
    ["line", "revenue", "?revenue"],
    ["line", "cost of services", "?cost"],
    ["=", "?percent",
      ["number/divide",
        ["number/round", ["number/multiply", 1000, ["number/divide", ["number/subtract", "?revenue", "?cost"], "?revenue"]]],
        10]]],
  ["why", ["gross_margin", ["array/head", ["find", "?p", ["gross_margin", "?p"]]]]]]
result
{
  "fact": ["gross_margin",26.4],
  "rule": [
    "rule",
    ["gross_margin","?percent"],
    ["line","revenue","?revenue"],
    ["line","cost of services","?cost"],
    [
      "=",
      "?percent",
      [
        "number/divide",
        [
          "number/round",
          [
            "number/multiply",
            1000,
            [
              "number/divide",
              ["number/subtract","?revenue","?cost"],
              "?revenue"
            ]
          ]
        ],
        10
      ]
    ]
  ],
  "because": [
    {"fact":["line","revenue",409.8],"given":true},
    {"fact":["line","cost of services",301.5],"given":true},
    {
      "check": [
        "=",
        26.4,
        [
          "number/divide",
          [
            "number/round",
            [
              "number/multiply",
              1000,
              [
                "number/divide",
                ["number/subtract",409.8,301.5],
                409.8
              ]
            ]
          ],
          10
        ]
      ]
    }
  ]
}

The figure in the last line is itself worked out, with find, so the program never states the 26.4 it explains.

See what a pattern matched

A goal can say which rows it wants with a pattern or a schema, and then the goal itself does not say which row it found. why does: the premise is the row the goal matched. A schema check that held is a check:

["begin",
  ["relation", "inbox", ["doc"]],
  ["relation", "big", ["id"]],
  ["schema", "Order", ["schema/open", {"id": "value/integer?"}]],
  ["fact",
    ["inbox", {"id": 1, "total": 80, "note": "gift"}],
    ["inbox", {"id": 2, "total": 20}]],
  ["rule", ["big", "?id"],
    ["inbox", ["schema/open", {"id": "?id", "total": "?total"}]],
    ["schema/fits?", {"id": "?id"}, "Order"],
    ["number/greaterThan", "?total", 50]],
  ["why", ["big", 1]]]
result
{
  "fact": ["big",1],
  "rule": [
    "rule",
    ["big","?id"],
    ["inbox",["schema/open",{"id":"?id","total":"?total"}]],
    ["schema/fits?",{"id":"?id"},"Order"],
    ["number/greaterThan","?total",50]
  ],
  "because": [
    {
      "fact": ["inbox",{"id":1,"total":80,"note":"gift"}],
      "given": true
    },
    {"check":["schema/fits?",{"id":1},"Order"]},
    {"check":["number/greaterThan",80,50]}
  ]
}

See what an aggregate combined

For an aggregated fact, why lists every match it combined under matches, in the order of their answers. For min, max, and shortest, it explains the one match that produced the value, the least where several did.

["begin",
  ["relation", "order", ["id", "customer", "amount"]],
  ["relation", "spend", ["customer", "total"]],
  ["fact", ["order", 1, "ana", 30], ["order", 2, "ana", 20]],
  ["rule", ["spend", "?c", ["aggregate/sum", "?a"]], ["order", "?_", "?c", "?a"]],
  ["why", ["spend", "ana", 50]]]
result
{
  "fact": ["spend","ana",50],
  "rule": [
    "rule",
    ["spend","?c",["aggregate/sum","?a"]],
    ["order","?_","?c","?a"]
  ],
  "matches": [
    [{"fact":["order",1,"ana",30],"given":true}],
    [{"fact":["order",2,"ana",20],"given":true}]
  ]
}

Ask why a fact does not hold

For a fact that does not hold, why returns it as absent, and under because every way it could have held and what stood in the way. Each rule that could give the fact is a way. It names the rule, the goals of its body that held under because, and under but the goal that stopped it:

["begin",
  ["relation", "user", ["name", "age"]],
  ["relation", "banned", ["name"]],
  ["relation", "eligible", ["name"]],
  ["fact", ["user", "ana", 34], ["user", "bo", 16], ["user", "cy", 40], ["banned", "cy"]],
  ["rule", ["eligible", "?n"],
    ["user", "?n", "?age"],
    ["number/greaterThan", "?age", 18],
    ["not", ["banned", "?n"]]],
  {"bo": ["why", ["eligible", "bo"]],
   "cy": ["why", ["eligible", "cy"]],
   "dee": ["why", ["eligible", "dee"]]}]
result
{
  "bo": {
    "absent": ["eligible","bo"],
    "because": [
      {
        "rule": [
          "rule",
          ["eligible","?n"],
          ["user","?n","?age"],
          ["number/greaterThan","?age",18],
          ["not",["banned","?n"]]
        ],
        "because": [
          {"absent":["banned","bo"],"because":[]},
          {"fact":["user","bo",16],"given":true}
        ],
        "but": {"absent":["number/greaterThan",16,18]}
      }
    ]
  },
  "cy": {
    "absent": ["eligible","cy"],
    "because": [
      {
        "rule": [
          "rule",
          ["eligible","?n"],
          ["user","?n","?age"],
          ["number/greaterThan","?age",18],
          ["not",["banned","?n"]]
        ],
        "because": [],
        "but": {"fact":["banned","cy"],"given":true}
      }
    ]
  },
  "dee": {
    "absent": ["eligible","dee"],
    "because": [
      {
        "rule": [
          "rule",
          ["eligible","?n"],
          ["user","?n","?age"],
          ["number/greaterThan","?age",18],
          ["not",["banned","?n"]]
        ],
        "because": [{"absent":["banned","dee"],"because":[]}],
        "but": {"absent":["user","dee","?age"],"because":[]}
      }
    ]
  }
}

What stands under but is the other side of the goal that stopped the rule. A filter that was false and a relation call with no match are absent. A not stops a rule because what it denies holds, so cy's but is the fact that he is banned. Every absent, asked as it stands, is false, as every check is true. A variable the rule had not bound when it stopped keeps its name, as ?age does for dee.

Lion runs a rule's body from the values the fact gives its head, so the goals those values reach come first and a rule stops as early as it can. A rule is told once for every answer of its first goals that the next goal stops. A fact that no rule could give has an empty because.

Follow an absent fact through its rules

An absent goal that rules could give is explained in turn, so the tree goes down to the facts that are missing. A goal the tree has explained once is written without because wherever it comes up again, which is also where recursion ends: ["path", "a", "d"] would need itself.

["begin",
  ["relation", "edge", ["from", "to"]],
  ["relation", "path", ["from", "to"]],
  ["fact", ["edge", "a", "b"], ["edge", "b", "a"], ["edge", "c", "d"]],
  ["rule", ["path", "?x", "?y"], ["edge", "?x", "?y"]],
  ["rule", ["path", "?x", "?z"], ["edge", "?x", "?y"], ["path", "?y", "?z"]],
  ["why", ["path", "a", "d"]]]
result
{
  "absent": ["path","a","d"],
  "because": [
    {
      "rule": ["rule",["path","?x","?y"],["edge","?x","?y"]],
      "because": [],
      "but": {"absent":["edge","a","d"],"because":[]}
    },
    {
      "rule": [
        "rule",
        ["path","?x","?z"],
        ["edge","?x","?y"],
        ["path","?y","?z"]
      ],
      "because": [{"fact":["edge","a","b"],"given":true}],
      "but": {
        "absent": ["path","b","d"],
        "because": [
          {
            "rule": ["rule",["path","?x","?y"],["edge","?x","?y"]],
            "because": [],
            "but": {"absent":["edge","b","d"],"because":[]}
          },
          {
            "rule": [
              "rule",
              ["path","?x","?z"],
              ["edge","?x","?y"],
              ["path","?y","?z"]
            ],
            "because": [{"fact":["edge","b","a"],"given":true}],
            "but": {"absent":["path","a","d"]}
          }
        ]
      }
    }
  ]
}

See what a rule gave instead

When a rule's whole body holds and the fact is still absent, the rule gave another row: its head computes or combines a value, and it is not the one asked about. Such a way has no because of its own. Its but is the row the rule gave, explained as any row that holds:

["begin",
  ["relation", "order", ["id", "customer", "amount"]],
  ["relation", "spend", ["customer", "total"]],
  ["fact", ["order", 1, "ana", 30], ["order", 2, "ana", 20]],
  ["rule", ["spend", "?c", ["aggregate/sum", "?a"]], ["order", "?_", "?c", "?a"]],
  ["why", ["spend", "ana", 60]]]
result
{
  "absent": ["spend","ana",60],
  "because": [
    {
      "rule": [
        "rule",
        ["spend","?c",["aggregate/sum","?a"]],
        ["order","?_","?c","?a"]
      ],
      "but": {
        "fact": ["spend","ana",50],
        "rule": [
          "rule",
          ["spend","?c",["aggregate/sum","?a"]],
          ["order","?_","?c","?a"]
        ],
        "matches": [
          [{"fact":["order",1,"ana",30],"given":true}],
          [{"fact":["order",2,"ana",20],"given":true}]
        ]
      }
    }
  ]
}

See why a goal under not has no match

A goal under not can be made of several goals, with variables of its own. When it is absent, each of its alternatives is a way, told like a rule's body but without a rule:

["begin",
  ["relation", "person", ["name"]],
  ["relation", "mother", ["child", "mother"]],
  ["relation", "tall", ["name"]],
  ["relation", "plain", ["name"]],
  ["fact", ["person", "ada"], ["mother", "ada", "eve"]],
  ["rule", ["plain", "?p"],
    ["person", "?p"],
    ["not", ["and", ["mother", "?p", "?m"], ["tall", "?m"]]]],
  ["why", ["plain", "ada"]]]
result
{
  "fact": ["plain","ada"],
  "rule": [
    "rule",
    ["plain","?p"],
    ["person","?p"],
    ["not",["and",["mother","?p","?m"],["tall","?m"]]]
  ],
  "because": [
    {"fact":["person","ada"],"given":true},
    {
      "absent": ["and",["mother","ada","?m"],["tall","?m"]],
      "because": [
        {
          "because": [{"fact":["mother","ada","eve"],"given":true}],
          "but": {"absent":["tall","eve"],"because":[]}
        }
      ]
    }
  ]
}

See what is only assumed

Lion is closed-world: what is not known does not hold. Most of what is absent stays absent whatever is learned later about an unknown, but not all of it. Ben's unknown mother is not known to be eve, and she may be. why marks such a goal with "assumed": true: it could come to hold once an unknown is known.

["begin",
  ["relation", "person", ["name"]],
  ["relation", "mother", ["child", "mother"]],
  ["relation", "stranger", ["name"]],
  ["fact", ["person", "ada"], ["person", "ben"], ["mother", "ada", "eve"]],
  ["rule", ["exists", ["?m"], ["mother", "?c", "?m"]], ["person", "?c"]],
  ["rule", ["stranger", "?c"], ["mother", "?c", "?m"], ["not", ["=", "?m", "eve"]]],
  {"ben is a stranger": ["why", ["stranger", "ben"]],
   "ada is not": ["why", ["stranger", "ada"]],
   "ben's mother is not eve": ["why", ["mother", "ben", "eve"]],
   "ada's mother is not fay": ["why", ["mother", "ada", "fay"]]}]
result
{
  "ben is a stranger": {
    "fact": ["stranger","ben"],
    "rule": [
      "rule",
      ["stranger","?c"],
      ["mother","?c","?m"],
      ["not",["=","?m","eve"]]
    ],
    "because": [
      {
        "fact": ["mother","ben",["some","?m",["mother","ben","?m"]]],
        "rule": [
          "rule",
          ["exists",["?m"],["mother","?c","?m"]],
          ["person","?c"]
        ],
        "because": [{"fact":["person","ben"],"given":true}]
      },
      {
        "absent": ["=",["some","?m",["mother","ben","?m"]],"eve"],
        "assumed": true
      }
    ]
  },
  "ada is not": {
    "absent": ["stranger","ada"],
    "because": [
      {
        "rule": [
          "rule",
          ["stranger","?c"],
          ["mother","?c","?m"],
          ["not",["=","?m","eve"]]
        ],
        "because": [{"fact":["mother","ada","eve"],"given":true}],
        "but": {"check":["=","eve","eve"]}
      }
    ]
  },
  "ben's mother is not eve": {
    "absent": ["mother","ben","eve"],
    "assumed": true,
    "because": [
      {
        "rule": [
          "rule",
          ["exists",["?m"],["mother","?c","?m"]],
          ["person","?c"]
        ],
        "but": {
          "fact": ["mother","ben",["some","?m",["mother","ben","?m"]]],
          "rule": [
            "rule",
            ["exists",["?m"],["mother","?c","?m"]],
            ["person","?c"]
          ],
          "because": [{"fact":["person","ben"],"given":true}]
        }
      }
    ]
  },
  "ada's mother is not fay": {
    "absent": ["mother","ada","fay"],
    "because": [
      {
        "rule": [
          "rule",
          ["exists",["?m"],["mother","?c","?m"]],
          ["person","?c"]
        ],
        "but": {"fact":["mother","ada","eve"],"given":true}
      }
    ]
  }
}

Ben is a stranger only as far as is known: the absent his row rests on is assumed. Ada is not a stranger whatever ben's mother turns out to be, so nothing there is marked. Read the mark on the goal it stands on:

  • An absent goal that is not marked stays absent whatever the unknowns are. What stands under its because says what stood in the way, and a mark there is about that goal, not about this one.
  • A fact holds whatever the unknowns are when nothing it rests on is marked: no premise under its because or matches, however deep, other than under the because of an absent goal.
  • A check is marked when it computes with an unknown, as ["value/unknown?", "?m"] does. An = or in between values holds whatever an unknown is. A row that combines matches, such as a count, is marked when a match holds an unknown or its rule's body could gain one.

The mark is safe rather than exact. Lion follows each rule that could give the goal, and marks the goal when a row that holds an unknown could match one of the goals on the way. A goal that is not marked cannot change. One that is marked may still not change, for a reason Lion does not look for. "Saying what an unknown is" means adding the fact its some form describes with a value in place of its variable, such as ["fact", ["mother", "ben", "eve"]].

  • why in the reference.

How-to guide · task-oriented

Save and load a logic database

Write a database out as a Lion program, store it anywhere, and rebuild it later from the command line or TypeScript.

This guide shows how to persist a logic database. A saved database is a snapshot: an ordinary Lion program of relation, schema, fact, rule, and invariant forms that rebuilds it when run.

Take a snapshot in Lion

["begin",
  ["relation", "edge", ["from", "to"]],
  ["relation", "path", ["from", "to"]],
  ["fact", ["edge", "a", "b"], ["edge", "b", "c"]],
  ["rule", ["path", "?x", "?y"], ["edge", "?x", "?y"]],
  ["invariant", ["edge", "?x", "?x"], {"assert": "none"}],
  ["snapshot"]]
result
[
  "begin",
  ["relation","edge",["from","to"]],
  ["relation","path",["from","to"]],
  ["rule",["path","?x","?y"],["edge","?x","?y"]],
  ["fact",["edge","a","b"],["edge","b","c"]],
  ["invariant",["edge","?x","?x"],{"assert":"none"}]
]

The rules come before the facts, which are written in one fact form, and the invariants come last, so loading a snapshot checks the facts and the invariants once, against the whole program, as the database was checked. Strings that would load as something else, such as relation names, logic variable names, and namespaced names, are written inside quote, and so are lists and records. Rules are written with values as they were evaluated, and a rule that invents with its exists head. An unknown in a fact is written as its some form. A named schema is written with its shape, schemas that one form declared in one form, and the schema of a relation's rows as the invariant it stands for.

Save schemas with the data

A database holds its schemas too, so a snapshot writes them. Schemas that one form declared are written in one form, a rule keeps the pattern it was written with, and the schema of a relation's rows is written as the invariant it stands for, so a loaded database refuses the same rows:

["begin",
  ["schema",
    "Expr", ["schema/anyOf", "value/number?", "Sum"],
    "Sum", {"add": ["schema/arrayOf", "Expr"]}],
  ["schema", "Order", ["schema/open", {"id": "value/integer?", "total": "Expr"}]],
  ["relation", "order", ["id", "total", "note"], {"key": "id", "schema": "Order"}],
  ["relation", "summed", ["id"]],
  ["fact", ["order", 1, ["quote", {"add": [2, 3]}], "gift"]],
  ["rule", ["summed", "?id"], ["order", "?id", {"add": "?parts"}, "?_"]],
  ["snapshot"]]
result
[
  "begin",
  ["relation","order",["id","total","note"],{"key":["id"]}],
  ["relation","summed",["id"]],
  [
    "schema",
    "Expr",
    ["schema/anyOf","value/number?","Sum"],
    "Sum",
    {"add":["schema/arrayOf","Expr"]}
  ],
  [
    "schema",
    "Order",
    ["schema/open",{"id":"value/integer?","total":"Expr"}]
  ],
  [
    "rule",
    ["summed","?id"],
    ["order","?id",{"add":"?parts"},"?_"]
  ],
  ["fact",["order",1,["quote",{"add":[2,3]}],"gift"]],
  [
    "invariant",
    [
      "and",
      ["order","?id","?total","?note"],
      [
        "not",
        ["Order",{"id":"?id","total":"?total","note":"?note"}]
      ]
    ],
    {"assert":"none"}
  ]
]

Restore facts from a snapshot

A snapshot is a program, so evaluating it puts back what it holds. Here a fact is removed after the snapshot, and running the snapshot with eval restores it:

["begin",
  ["relation", "edge", ["from", "to"]],
  ["fact", ["edge", "a", "b"], ["edge", "b", "c"]],
  ["define", "saved", ["snapshot"]],
  ["retract", ["edge", "a", "b"]],
  {"before": ["query", ["edge", "?from", "?to"]],
   "restored": ["begin", ["eval", "saved"], ["query", ["edge", "?from", "?to"]]]}]
result
{
  "before": [{"from":"b","to":"c"}],
  "restored": [{"from":"b","to":"c"},{"from":"a","to":"b"}]
}

Evaluating a snapshot adds to the database; it does not remove facts the snapshot lacks. To start over, load it into an empty database.

Persist helper definitions in a snapshot

Top-level define bindings marked with {"persist": true} are written into the snapshot alongside relations, rules, and invariants so restored databases keep their helper constants and functions:

["begin",
  ["define", "tax_rate", 0.08, {"persist": true}],
  ["define", "with_tax", ["lambda", ["price"], ["number/multiply", "price", ["number/add", 1, "tax_rate"]]], {"persist": true}],
  {"total": ["with_tax", 100], "saved": ["snapshot"]}]
result
{
  "total": 108,
  "saved": [
    "begin",
    ["define","tax_rate",0.08,{"persist":true}],
    [
      "define",
      "with_tax",
      [
        [
          "lambda",
          ["tax_rate"],
          [
            "lambda",
            ["price"],
            [
              "number/multiply",
              "price",
              ["number/add",1,"tax_rate"]
            ]
          ]
        ],
        0.08
      ],
      {"persist":true}
    ]
  ]
}

Save and load from TypeScript

saveDatabase and loadDatabase do the same with a LogicDatabase:

import { readFileSync, writeFileSync } from "node:fs";
import { Effect } from "effect";
import { run } from "@lionlang/core/evaluation/evaluate";
import { loadDatabase, saveDatabase } from "@lionlang/core/logic/snapshot";
import { stdlib } from "@lionlang/core/modules";

const program = Effect.gen(function* () {
  const database = yield* loadDatabase(JSON.parse(readFileSync("store.json", "utf8")), stdlib);
  yield* run(["fact", ["edge", "c", "d"]], stdlib, { database });
  writeFileSync("store.json", JSON.stringify(yield* saveDatabase(database)));
});

A rule is saved with everything it holds: a function under the name the environment gives it, and a cond, record, or lambda that waits for a logic variable as its own form. Two things have no written form, a lambda that calls itself and a function made while the program ran, and saveDatabase fails with an error that names them.

Save from the command line

bun run lion program.json --database store.json

The command loads store.json, runs the program against it, and saves it back one form and one fact per line, unless the program fails.

How-to guide · task-oriented

Add your own functions and algorithms

Give Lion programs your own values and functions, use them inside logic rules, and add graph-style algorithms.

This guide shows how to extend the environment from TypeScript. It assumes you can already run Lion from TypeScript.

Add a function

Bind a function under a namespaced name. It receives evaluated arguments and returns a plain value or an Effect:

import { Effect } from "effect";
import { run } from "@lionlang/core/evaluation/evaluate";
import { stdlib } from "@lionlang/core/modules";

const env = {
  ...stdlib,
  "text/upper": (text: string) => text.toUpperCase(),
  "shop/stock": (sku: string) => Effect.promise(() => fetchStock(sku)),
};

await Effect.runPromise(run(["text/upper", "lion"], env)); // => "LION"

Return an Effect for anything asynchronous or anything that can fail, so Lion can wait for it and report failures as typed errors.

A function may return any value, also one JSON cannot hold, such as a Date, a Map, a bigint, an instance of a class, or undefined. Plain code carries it as it is, through names, lists, records, and lambdas, and = is true of it only for the same value. The logic database and a question's answers hold data only, so a fact, a derived row, or an answer that holds such a value fails, and the message shows the value as its kind, as it shows a function as <function>:

const env = { ...stdlib, "host/now": () => new Date(0) };

await Effect.runPromise(run(["array/make", ["host/now"]], env)); // => [the Date itself]
await Effect.runPromise(
  run(["begin", ["relation", "seen", ["at"]], ["fact", ["seen", ["host/now"]]]], env)
);
// fails: Facts may only contain data, but the "at" of ["seen","<Date>"] is "<Date>", which is not data.

Add a module of functions

namespaceEntries prefixes every key of a record, the way the standard library is built:

import { namespaceEntries, stdlib } from "@lionlang/core/modules";

const text = {
  upper: (s: string) => s.toUpperCase(),
  lower: (s: string) => s.toLowerCase(),
};

const env = { ...stdlib, ...namespaceEntries("text", text) };
// "text/upper" and "text/lower"

Use functions inside rules

A host function needs nothing more to work in a rule or query. Like every function, it waits when it is called with a logic variable, and runs once the variable is bound, so it works as a filter or a computed value:

const text = {
  upper: (s: string) => s.toUpperCase(),
  "long?": (s: string) => s.length > 8,
};

const env = { ...stdlib, ...namespaceEntries("text", text) };
// ["rule", ["shout", "?n", ["text/upper", "?n"]], ["name", "?n"], ["text/long?", "?n"]]

Use functions that return the same result for the same arguments and have no side effects; the engine may call them any number of times, in any order. A function used as a filter must return true or false.

A goal given to your function is asked first, so the function receives true or false.

A string of the form module/name that nothing is bound to is an error when its module has other names, so a program that misspells one of your functions is told which name it probably meant.

Use a function as a schema

A function is a predicate, so a function you add is a schema for the values it returns true for. It works wherever a schema does: in schema/fits?, in match, as a part of a record, and as an argument of a relation call. To check a value against a schema from your own code, use fits:

import { Effect } from "effect";
import { fits } from "@lionlang/core/logic/fit";

const env = {
  ...stdlib,
  "text/email?": (value: unknown) => typeof value === "string" && value.includes("@"),
  "list/count": (items: unknown[], schema: unknown) =>
    Effect.map(
      Effect.filter(items, (item) =>
        Effect.map(fits(schema, item), (fit) => fit === true)
      ),
      (kept) => kept.length
    ),
};
// ["schema/fits?", {"to": "ada@example.com"}, {"to": "text/email?"}]
// ["query", ["contact", "?name", "text/email?"]]
// ["list/count", "rows", {"to": "text/email?"}]

Tell Lion what a function reads

An invariant is asked again only when a change can have broken it, which takes knowing what its goal reads. Lion cannot see inside your function: it might read the database on its own. So an invariant whose goal calls a host function, in the goal itself, inside a schema, or through a rule, is asked in full after every change to facts. That is always correct, and costs more on a large database. A function that reads nothing but its arguments can say so:

import { readsOnlyArguments } from "@lionlang/core/logic/terms";

const isEmail = (value: unknown) => typeof value === "string" && value.includes("@");
readsOnlyArguments({ isEmail });

const env = { ...stdlib, "text/email?": isEmail };
// ["invariant", ["and", ["contact", "?name", "?to"], ["not", ["text/email?", "?to"]]], {"assert": "none"}]

The invariant is then treated like one over the standard library: a change to contact checks the new rows, and a change to any other relation does not ask it at all.

Call back into Lion

A function that takes a Lion function, such as a lambda or a relation, calls it with call. It gives the callback's value, with a goal asked, and lets the whole call wait when that value is not known yet:

import { Effect } from "effect";
import { call } from "@lionlang/core/evaluation/special-forms/function";

const env = {
  ...stdlib,
  "list/keep": (items: unknown[], keep: unknown) =>
    Effect.filter(items, (item) =>
      Effect.map(call(keep, item), (kept) => kept === true)
    ),
};
// ["list/keep", ["array/make", "ana", "bo"], "member"]
// ["rule", ["shortlist", ["list/keep", "?names", "member"]], ["team", "?names"]]

Build goals from host code

A function that should receive logic variables as they are, to build a goal from them, is marked with logicFunction:

import { LogicForm, logicFunction } from "@lionlang/core/logic/terms";

const same = logicFunction((left: unknown, right: unknown) =>
  Effect.succeed(new LogicForm("=", [left, right]))
);

const env = { ...stdlib, "my/same": same };
// ["query", ["and", ["name", "?n"], ["my/same", "?shout", ["text/upper", "?n"]]]]

Add an algorithm

For work that rules do badly, defineAlgorithm turns a function over whole relations into a goal, like those in the graph module. It receives each relation input as its tuples and each value input as itself, and returns rows, or a string that explains why it cannot. A value input can be a variable that another goal binds; the function then runs once for each value. An input must be JSON data. The columns the function returns are matched like a relation's, so a goal can give a schema for one:

import { defineAlgorithm } from "@lionlang/core/logic/algorithms";

const outDegree = defineAlgorithm({
  name: "my/outDegree",
  inputs: [{ kind: "relation", name: "edges" }],
  columns: ["node", "degree"],
  run: ([edges]) => {
    const counts = new Map<unknown, number>();
    for (const [from] of edges as unknown[][]) {
      counts.set(from, (counts.get(from) ?? 0) + 1);
    }
    return [...counts];
  },
});

const env = { ...stdlib, "my/outDegree": outDegree };
// ["query", ["my/outDegree", "edge", "?node", "?degree"]]

The engine runs the algorithm once its input relations are complete, and its rows can feed rules, not, find, and aggregates. why marks them as computed.

How-to guide · task-oriented

Call JavaScript objects and methods

Read properties, call methods, construct classes, and pass Lion functions to JavaScript callbacks.

This guide shows how to work with JavaScript values that your host puts in the environment, using the object and func modules.

Read values

object/get reads one key; object/get-path follows a dot path, with numbers for list positions:

["begin",
  ["define", "config", ["quote", {"users": [{"name": "ana"}, {"name": "bo"}], "port": 8080}]],
  {"port": ["object/get", "config", "port"],
   "second": ["object/get-path", "config", "users.1.name"],
   "keys": ["object/keys", "config"]}]
result
{"port":8080,"second":"bo","keys":["users","port"]}

A record in a program evaluates its values, and a list inside it would be a call, so the data here is quoted.

Call a method

object/call-method calls a method by name with this set to the value. Every method function works on any value except null, including strings and lists:

{"upper": ["object/call-method", "lion", "toUpperCase"],
 "padded": ["object/call-method", "7", "padStart", 3, "0"],
 "joined": ["object/call-method", ["array/make", "a", "b"], "join", "-"]}
result
{"upper":"LION","padded":"007","joined":"a-b"}

object/call-method-path follows a dot path through objects and calls the method at its end, such as "console.log" on a host value or "user.name.trim" on a record.

Construct an instance

When the host binds a class, object/new constructs it:

const env = { ...stdlib, URL };
await Effect.runPromise(run(
  ["object/get", ["object/new", "URL", "https://lionlang.dev/docs"], "pathname"], env));
// => "/docs"

Pass a Lion function to JavaScript

Lion functions return Effects, which JavaScript callbacks cannot use. func/callback wraps a Lion function so JavaScript can call it: the result comes back as a value, or as a Promise when the function's work is asynchronous. It keeps the relations and names of the program that created it.

["object/call-method", "button", "addEventListener", "click",
  ["func/callback", ["lambda", ["event"], ["console/log", "clicked"]]]]

Prepare functions in advance

["begin",
  ["define", "addTax", ["func/partial", "number/multiply", 1.25]],
  ["array/map", ["array/make", 10, 20], "addTax"]]
result
[12.5,25]

func/bind fixes this and leading arguments, and func/apply calls a function with a given this, the arguments given, and the items of its last argument, a list, as JavaScript's Function.prototype.apply does.

How-to guide · task-oriented

Ask AI models with TypeSafe

Turn natural language into typed judgments inside a Lion program with the TypeSafe AI and Jev bindings.

This guide shows how to call TypeSafe's System One models from Lion with @lionlang/typesafe-ai. You need a TypeSafe API key. These examples call a paid API, so they are not live on this page.

Add the bindings

bun add @lionlang/typesafe-ai
export TYPESAFE_API_KEY=...
import { Effect } from "effect";
import { run } from "@lionlang/core/evaluation/evaluate";
import { stdlib } from "@lionlang/core/modules";
import { makeTypeSafeBindings } from "@lionlang/typesafe-ai";

const env = { ...stdlib, ...makeTypeSafeBindings() };

makeTypeSafeBindings takes the TypeSafe client configuration and an optional namespace, "typesafe" by default.

Ask several questions about one input

typesafe/system-one takes the state to judge and a record of questions. Build each question with typesafe/noul (yes or no), typesafe/choice (one of several labels), or typesafe/score (a point on a scale):

["typesafe/system-one", {
  "state": "Help! My payouts have been failing for 3 days.",
  "questions": {
    "urgent": ["typesafe/noul", "Does this convey urgency?",
      {"true": "Explicitly time-sensitive", "false": "No urgency expressed"}],
    "team": ["typesafe/choice", "Which team should handle this?",
      {"billing": "Payments and refunds", "technical": "Bugs and outages"}],
    "frustration": ["typesafe/score", "How frustrated is the customer?",
      ["quote", ["Calm", "Frustrated", "Very angry"]]]}}]

Lists in the request are data, so they are quoted. Each answer comes back with its probabilities, so a program can branch on confidence with cond.

List the available models

["typesafe/models"]

Try it in the editor

In the graph editor (lion repl), the Jev button loads a starter System One program. The editor asks for a key on the first run and keeps it only in the tab's memory.

Reference · information-oriented

Evaluation rules

How Lion evaluates each kind of JSON value: numbers, booleans, null, strings, arrays, and records.

A Lion program is any JSON value. Evaluation depends only on the value's JSON type.

JSON typeEvaluates to
numberItself.
booleanItself.
nullItself.
stringThe value of the name, when a scope it is written in declares it; otherwise a logic variable, for a name like "?x"; otherwise itself. See Strings.
array[] for an empty array; otherwise a special form or a function call. See Arrays.
object (record)A record with the same keys, each value evaluated. See Records.

Strings

What a string means is settled by the scopes it is written in, before it runs, so a binding made later never turns data into a name. A scope declares its bindings from its start: a run's top scope declares what the environment and the database bind, every name the program's top level defines, and every relation and schema it declares; a lambda's scope declares its parameters and the names its body defines. A string is read in this order:

  1. If a scope declares the name, the string evaluates to the name's value. Read before its define has run, it fails with UndefinedYetError.
  2. If the name has the form ?name, where name starts with a letter or _ and continues with letters, digits, _, or -, it evaluates to a logic variable. "?_" and names starting with ?_ are anonymous variables.
  3. If the name has the form module/name and reads as a misspelled name, it is an UnboundNameError that suggests the name: other names of its module are bound, as for "number/ad", or a bound name is a letter or two away, as for "numbr/add".
  4. Otherwise the string evaluates to itself, as "n/a" and "text/plain" do.

The first element of an array is the one place a string is never data, since it names what the array does: one that no scope declares is looked up where the call runs. See Arrays.

["begin",
  ["define", "name", "lion"],
  {"bound": "name", "unbound": "unbound text", "quoted": ["quote", "name"],
   "with a slash": "n/a"}]
result
{
  "bound": "lion",
  "unbound": "unbound text",
  "quoted": "name",
  "with a slash": "n/a"
}
["number/ad", 1, 2]
error
UnboundNameError: Nothing is bound to "number/ad". Did you mean "number/add"? To mean the string itself, write ["quote", "number/ad"].

The misspelled name fails wherever it stands: as a function, as a value, as a schema, and inside a rule when the rule is written. ["quote", "number/ad"] is the string.

To use a string that might be bound as plain text, wrap it in quote.

Arrays

  • An empty array evaluates to [].
  • An array whose first element is the name of a special form or logic form, which no scope around it declares, is evaluated by the form's own rules.
  • An array that starts with such a name but does not fit the form's shape, such as ["define", "x"], fails with MalformedFormError, which says what the form takes.
  • Any other array is a function call. Every element is evaluated, from left to right. The first must evaluate to a function, which is called with the rest as arguments. If it does not, evaluation fails with InvalidFunctionCallError.
  • The first element names what the array does, so a string there is a name and never data. A name no scope declares is looked up where the call runs: a relation or function that code eval ran has bound by then is called, in plain code and in a rule, query, or find alike. Anywhere else, the same string is data.
["begin",
  ["eval", ["quote", ["begin",
    ["relation", "visited", ["city"]],
    ["fact", ["visited", "Lima"], ["visited", "Oslo"]]]]],
  {"found": ["find", "?c", ["visited", "?c"]],
   "asked": ["visited", "Oslo"],
   "the string": "visited"}]
result
{"found":["Lima","Oslo"],"asked":true,"the string":"visited"}
[["lambda", ["fact"], ["fact", 3]], "value/identity"]
result
3
[1, 2, 3]
error
InvalidFunctionCallError: [1,2,3] is not a valid call. The first element must be a special form or evaluate to a function.

Records

A record evaluates each value and keeps its keys as written, in order. A record with a logic variable among its values waits for it, as a call does. A record holds values, so a goal among them is asked: the record holds true or false. Keys are never evaluated. A key must not be empty or __proto__; a program with such a key fails with SchemaError before it runs.

{"sum": ["number/add", 1, 2], "nested": {"ok": ["boolean/not", false]}}
result
{"sum":3,"nested":{"ok":true}}

Function calls

  • Arguments are evaluated before the call, from left to right.
  • A function may return a value or an Effect. Lion runs an Effect and uses its result.
  • A call gives a function as many arguments as it takes: a lambda one for each parameter, and a library function, a relation, or a schema what it says. Any other number fails, and says how many the function takes.
  • A call with a logic variable among its arguments does not run. It waits: it becomes a value that a rule or query computes once the variable is bound. Every function waits this way, except relations, aggregates, graph algorithms, and lambdas, which take logic variables as they are.
  • A function that is given a goal with a relation in it gets the goal's answer, true or false: the goal is asked. Relations, aggregates, graph algorithms, and lambdas take the goal itself.
  • Calls nest as deep as memory allows. A call in tail position keeps nothing of the call it is in, as in Scheme. A lambda's body is in tail position, and so are the result of a cond case and the last expression of a begin that are. A lambda that calls itself there is a loop, and runs in constant memory.
["number/add", "?n", 1]
result
["number/add","?n",1]
["begin",
  ["define", "count", ["lambda", ["n", "total"],
    ["cond", [["number/equals?", "n", 0], "total"],
             ["else", ["count", ["number/subtract", "n", 1], ["number/add", "total", 1]]]]]],
  ["count", 100000, 0]]
result
100000

Conditions

A condition is true or false, wherever Lion tests one: a cond case, an argument of and, or, and not, and a filter of a rule or query. Any other value fails, with a message that shows it. A condition that is a goal with a relation in it is asked first, and gives true or false. match predicates fit a value when they return true.

["cond", [["array/length", ["array/make"]], "empty"], ["else", "some"]]
error
LogicError: A condition must be true or false, but ["array/length",["array/make"]] is 0.

Names of forms

A define, a set!, or a lambda parameter can bind any name but the empty string and __proto__. A form's name a binding takes is a call where the binding is in scope, as a binding shadows a keyword in Scheme, and the form everywhere else. A body declares what it defines from its start, so a body that defines a form's name cannot also use the form: ["define", "define", 1] calls the name it defines, which has no value yet, and fails with UndefinedYetError, as R7RS Scheme makes such a definition an error. A relation or schema is bound for every run of its database, so its name cannot be a form's: begin, cond, define, set!, eval, lambda, match, quote, relation, schema, rule, fact, retract, query, find, assuming, exists, some, why, not, and, or, =, in, snapshot, or invariant.

Each run

Each evaluation (run in TypeScript, one file on the command line, one live example on this page) starts with a fresh environment holding the bindings it was given, and an empty logic database unless one is passed in. Names defined in one run are gone in the next; a shared database keeps its relations, facts, rules, and invariants. See Names, scope, and environments.

Reference · information-oriented

Special forms

The forms that control evaluation: quote, eval, begin, define, set!, lambda, cond, and match.

A special form is an array whose first element is the form's name, where no scope declares that name. Unlike a function call, a special form decides which of its parts to evaluate, and when. The logic layer's forms are in Logic forms.

quote

["quote", expression]

Returns expression without evaluating it. Use it for literal lists, records that contain lists, and strings that might be bound names.

["quote", ["number/add", 1, 2]]
result
["number/add",1,2]

eval

["eval", expression]

Evaluates expression, then evaluates the result as a program in the current environment. The result is compiled when it runs, as a program is: its strings mean what the scope declares then, together with the names the code defines, which it binds in the body eval stands in, and the relations and schemas it declares. The result must be JSON data; a function or other host value fails with SchemaError.

["eval", ["quote", ["number/add", 1, 2]]]
result
3
["eval", ["quote",
  ["begin",
    ["define", "twice", ["lambda", ["n"], ["double", ["double", "n"]]]],
    ["define", "double", ["lambda", ["n"], ["number/multiply", "n", 2]]],
    ["twice", 5]]]]
result
20

begin

["begin", expression, ...]

Evaluates each expression in order and returns the last result. ["begin"] returns [].

["begin", ["define", "x", 1], ["define", "x", 2], "x"]
result
2
  • Every expression before the last runs, also one that waits for a logic variable. Such an expression, or a question in a rule, a query, or a find, makes the whole begin wait, as a condition makes cond wait, and the begin then runs every expression for each answer, as plain code would with the values in place. A question it does not need is not asked, but what the question holds runs.
  • A program's own begin, and a begin among its forms, runs its forms one at a time instead, as Scheme splices a top-level begin into the program. A definition there of a value that waits names it, and the forms after it run.
["begin",
  ["define", "pair", ["lambda", ["n"],
    ["begin", ["schema/assert", "n", "value/number?"], ["array/make", "n", "n"]]]],
  ["find", ["pair", "?item"], ["in", "?item", ["array/make", 3, "three"]]]]
error
LogicError: "three" does not fit "value/number?".
["begin",
  ["define", "half", ["number/divide", "?n", 2]],
  ["find", "half", ["in", "?n", ["array/make", 2, 4]]]]
result
[1,2]

define

["define", name, expression]
["define", name, expression, {"persist": true}]
  • Evaluates expression, binds name to the result in the body the form stands in, a lambda's or the program's, and returns the result.
  • The body declares the name from its start, so the name means this definition everywhere in the body, and functions can name each other in any order. Read before the define has run, it fails with UndefinedYetError.
  • A define inside a lambda binds in the lambda's call, and never changes a name outside it. To change one, use set!.
  • Binding a name again replaces its value. Functions that use the name see the new value when they next run.
  • name can be any non-empty string but __proto__, a form's name among them: see Names of forms.
  • At top level, an optional fourth argument {"persist": true} saves the binding in the logic database so later programs and snapshots inherit it.
["begin",
  ["define", "greet", ["lambda", [], ["string/concat", "hello, ", "who"]]],
  ["define", "who", "world"],
  ["greet"]]
result
"hello, world"

delay

["delay", expression]
  • Returns a promise of expression, in the scope the form is written in, as Racket's delay does. Nothing runs until value/force asks.
  • The first force runs the expression and keeps its value; every force after gives that value without running it again. A failure keeps nothing, so the next force runs the expression again. A promise forced while it is being forced fails, since forcing it would never end.
  • value/force of any other value gives the value, and value/promise? tells a promise apart. A promise is not data: a fact or a query's answer cannot hold one.
["begin",
  ["define", "runs", 0],
  ["define", "total", ["delay", ["begin", ["set!", "runs", ["number/add", "runs", 1]], ["aggregate/sum", ["array/range", 0, 1000]]]]],
  {"before a force, the expression has run": "runs",
   "forced": ["value/force", "total"],
   "forced again": ["value/force", "total"],
   "after two forces, it has run": "runs"}]
result
{
  "before a force, the expression has run": 0,
  "forced": 499500,
  "forced again": 499500,
  "after two forces, it has run": 1
}

set!

["set!", name, expression]
  • Evaluates expression, changes the value of the nearest binding of name to it, and returns it, as set! does in Scheme.
  • It is how a lambda changes a name around it, such as a counter or the state of an app that its callbacks update.
  • A name no scope around the form declares has no binding to change, so the form fails with UnboundNameError.
  • A rule, query, or find runs its parts when and as often as the engine chooses, so there set! fails for a binding made outside it, where a counter would give every row one number. A binding the call makes for itself it changes as anywhere.
["begin",
  ["define", "calls", 0],
  ["define", "counted", ["lambda", ["x"], ["begin", ["set!", "calls", ["number/add", "calls", 1]], "calls"]]],
  ["relation", "item", ["x"]],
  ["relation", "numbered", ["x", "n"]],
  ["rule", ["numbered", "?x", ["counted", "?x"]], ["item", "?x"]]]
error
LogicError: set! cannot change "calls" while a rule, query, or find runs: the engine chooses when and how often its parts run, so a change to a binding made outside it would not happen once for each answer. Change it outside, or derive the value with a rule or an aggregate. (in "counted")
["begin",
  ["define", "count", 0],
  ["define", "tick", ["lambda", [], ["set!", "count", ["number/add", "count", 1]]]],
  ["tick"], ["tick"],
  "count"]
result
2

lambda

["lambda", [parameter, ...], body]
["lambda", name, body]
  • Returns a function. Calling it binds each parameter to the matching argument, and declares the names its body defines, in a new environment whose parent is the one where the lambda was created, then evaluates body.
  • Written with one name in place of its list of parameters, it takes any number of arguments and binds the name to the list of them, as (lambda args body) does in Scheme. The list is what array/make gives with the arguments: a goal among them is asked, and where an argument waits for a logic variable, the list waits with it.
  • A call gives a lambda with a list of parameters one argument for each. Called with any other number, it fails as every function does: ["lambda",["a","b"],"a"] takes 2 arguments but got 1., or, when a define bound it, with the name it was bound to. Host code that passes more, as Array.prototype.map does, calls it through func/callback, which gives it as many as it takes.
  • The body is one expression; use begin for several. It is in tail position, so a lambda that calls itself last loops in constant memory.
  • Parameters can be any non-empty strings but __proto__; one that takes a form's name makes the form a call in the body: see Names of forms. Listing a parameter name more than once is warned of by lion check and the graph editor.
  • A parameter written [name, schema] is a contract: a call checks the argument as schema/assert does, before the body runs, so a misfit fails there and the functions the failure left start with the caller. The schema is made where the lambda is. Where the call waits for a logic variable, the check waits too. A match with no fallback on such a parameter is checked to cover every value the contract allows.
["begin",
  ["define", "makeAdder", ["lambda", ["n"], ["lambda", ["x"], ["number/add", "x", "n"]]]],
  ["define", "addTen", ["makeAdder", 10]],
  ["addTen", 5]]
result
15
["begin",
  ["define", "total", ["lambda", "amounts", ["array/reduce", "amounts", 0, "number/add"]]],
  {"three": ["total", 5, 10, 20],
   "none": ["total"],
   "applied": ["func/apply", "total", null, 1, ["array/make", 2, 3]],
   "in a find": ["find", ["total", "?x", 1], ["in", "?x", ["array/make", 10, 20]]]}]
result
{"three":35,"none":0,"applied":6,"in a find":[11,21]}
["begin",
  ["define", "next", ["lambda", [["n", "value/number?"]], ["number/add", "n", 1]]],
  ["define", "label", ["lambda", ["n"], ["string/concat", "item ", ["number/toString", ["next", "n"]]]]],
  ["label", "seven"]]
error
LogicError: "seven" does not fit "value/number?". (in "label")

cond

["cond", [condition, result], ..., ["else", result]]
  • Evaluates each condition in order and returns the evaluated result of the first one that is true. Later conditions are not evaluated. A condition must be true or false; any other value fails: see Conditions.
  • A condition that is a goal with a relation in it, such as a relation call, is asked: it holds when the goal has a match.
  • An else branch always matches, unless a scope declares else. Any branch after an unshadowed else is warned of by lion check and the graph editor.
  • With no match and no else, returns null.
["cond",
  [["number/greaterThan", 3, 5], "big"],
  [["number/greaterThan", 3, 1], "medium"],
  ["else", "small"]]
result
"medium"

match

["match", value, [schema, function], ..., fallback?]
  • Evaluates value, then tries each pair in order. The first whose schema the value fits is chosen, and its function is called with the value. If the value fits none, fallback is called with the value; a match with no fallback fails, as Racket's does, naming the value.
  • Anything is a schema. A function is a predicate: the value fits when it returns true, and a failure, or any other result, counts as not fitting. A relation with one column is a predicate too: the value fits when the goal the relation builds from it has a match.
  • A record fits a record with the same keys, where each value fits the schema under the same key; ["schema/open", record] fits a record that has other keys too. A list fits a list of the same length, item by item. Any other value fits a value equal to it. Schemas nest.
  • At least one pair is required, and the fallback may be left out. A last part that is a pair is a case, so write a fallback as a lambda or a name, not as a call of two parts.
  • A case after one whose schema takes every value it allows can never be reached. Reading the program finds it, as schema/includes? decides, where both schemas have one value wherever the match runs: the graph editor shows it, and lion check prints it.
["match", {"type": "user", "name": "Ada"},
  [{"type": ["func/partial", "string/equals?", "user"], "name": "value/string?"},
   ["lambda", ["u"], ["string/concat", "user ", ["object/get", "u", "name"]]]],
  ["lambda", ["other"], "unknown"]]
result
"user Ada"

Without a fallback, a value no case fits fails:

["match", "five",
  ["value/integer?", ["lambda", ["n"], "an integer"]],
  ["value/number?", ["lambda", ["n"], "a number"]]]
error
LogicError: No case of the match fits "five", and it has no fallback: ["match","five",["value/integer?",["lambda",["n"],"an integer"]],["value/number?",["lambda",["n"],"a number"]]].

A plain value, a list, and a schema built by the schema module are schemas too. The first pair here asks for a record with one key, so it does not fit; the third opens the record and takes it:

["match", ["quote", {"type": "refund", "amount": 5, "lines": [1, 2]}],
  [{"type": "refund"}, ["lambda", ["m"], "a refund and nothing else"]],
  [["schema/open", {"type": "sale"}], ["lambda", ["m"], "a sale"]],
  [["schema/open", {"type": ["schema/anyOf", "refund", "void"],
                    "lines": ["array/make", "value/number?", "value/number?"]}],
   ["lambda", ["m"], ["object/get", "m", "amount"]]],
  ["lambda", ["m"], "something else"]]
result
5

Reference · information-oriented

Logic forms

The forms of Lion's Datalog-style logic layer: relations, facts, rules, queries, goals, questions, unknowns, snapshots, and invariants.

The logic layer stores facts in relations, derives more with rules, and answers queries. Relations, goals, and logic variables are ordinary Lion values, and answers are plain Lion data. For the rules every program must follow, see Logic database guarantees.

Logic variables

  • An unbound string of the form "?name" evaluates to a logic variable. See Strings for the exact form.
  • The same name refers to the same variable throughout one goal or rule.
  • "?_", and any name starting with ?_, is anonymous: each occurrence is a separate variable, and it never appears in answers.
  • A call or record that mentions a logic variable waits for it.
  • A variable that only a question mentions belongs to the question. A variable that exists lists, or that some stands for, belongs to that form.

Goals

A goal is a value that a query, rule, or invariant can solve. Goals are built by calling a relation, by not, and, or, =, in, and exists, by calling a graph algorithm, and by calling any other function on logic variables, which makes a filter. The booleans true and false are goals that always and never hold. Any expression can also ask a goal.

Waiting for values

A rule or query is written before its variables have values. Anything that needs the value of a logic variable waits, and runs once for each answer that binds the variable.

  • A call waits when one of its arguments is a logic variable or a value that waits. Every function waits this way: standard functions, functions from the host, and functions made by func/partial.
  • cond waits when a condition is not known yet, match when its value is not, eval when its code is not, begin when an expression before its last is not, and a record when one of its values is not.
  • What a rule, query, or find holds runs when it does. A call on values that are already known may be computed when the rule is written. So a rule, query, or find refuses a set! of a binding made outside it, whose change would happen once, or as often as the engine chose, rather than once for each answer.
  • Relations, aggregates, and graph algorithms take logic variables as they are, and build goals and aggregates from them. A lambda's body runs right away, so a lambda can build goals; whatever in the body needs a value waits. Only an argument that asks a question makes a lambda's call wait, so the question is answered first, as it is in plain code.
  • What waits computes what it would compute with the value in place of the variable.
  • As a goal, a call that waits is a filter, and so is a variable. A filter must be true or false; any other value fails the query.
  • Names are replaced by their values when the rule or query is written, also inside a cond or lambda that waits—including recursive and mutually recursive lambdas, which are closed into self-contained blocks—so redefining a name later does not change the rule.
["begin",
  ["relation", "reading", ["sensor", "celsius"]],
  ["fact", ["reading", "attic", 30], ["reading", "cellar", 10]],
  ["query",
    ["and", ["reading", "?sensor", "?c"],
      ["=", "?summary",
        {"fahrenheit": ["number/add", ["number/multiply", "?c", 1.8], 32],
         "level": ["cond", [["number/greaterThan", "?c", 25], "hot"], ["else", "fine"]]}]],
    {"order": "sensor"}]]
result
[
  {
    "sensor": "attic",
    "c": 30,
    "summary": {"fahrenheit":86,"level":"hot"}
  },
  {
    "sensor": "cellar",
    "c": 10,
    "summary": {"fahrenheit":50,"level":"fine"}
  }
]
["query",
  ["and", ["in", "?word", ["array/make", "apple", "cherry"]],
    ["string/indexOf", "?word", "a"]]]
error
LogicError: A condition must be true or false, but ["string/indexOf","apple","a"] is 0.

Asking questions

A goal with a relation in it is a question, and so is exists, which has variables of its own. Any expression can ask a question. As a goal of a rule or query it matches rows and binds variables. Anywhere else it is asked:

  • Under not, it holds when it has no match.
  • As a value, it is true when it has a match and false when it has none. A goal is a value in a cond condition, as an argument of a function, as an operand of = or in, as a value of a record or an argument of a fact, and as the value match looks at. A relation is a predicate for match and for functions that are given it, such as array/map.
  • find gives what it matches, as a list.
  • assuming gives what an expression gives in the database as it would be after some changes.
  • When a question is asked, the variables that the rule or query around it has bound have their values. Every other variable in it is the question's own: the question binds it, and it never appears in an answer. Two questions that use the same name for a variable of their own do not share it.
  • In plain code a question is asked as soon as something needs its value, and every variable in it is its own. In a rule, query, invariant, or find, a question is part of what is written: it is asked for each answer, when that runs.
  • A question asked from a rule sees every row of the relations it asks about, so those are derived first. A rule cannot ask about a relation that depends on the rule's own head.
  • define, and, or, not, and a lambda keep a goal as it is, so goals can still be named, combined, and passed around. So does a program, or a begin, whose value is a goal: it gives the goal as written.
["begin",
  ["relation", "parent", ["parent", "child"]],
  ["relation", "retired", ["name"]],
  ["fact", ["parent", "ada", "ben"], ["parent", "ada", "cy"], ["parent", "ben", "dee"]],
  ["fact", ["retired", "ada"]],
  {"children of ada": ["find", "?child", ["parent", "ada", "?child"]],
   "ada has a grandchild":
     ["cond", [["and", ["parent", "ada", "?c"], ["parent", "?c", "?_"]], "yes"], ["else", "no"]],
   "ben is retired": ["retired", "ben"],
   "who is retired": ["array/map", ["array/make", "ada", "ben"], "retired"]}]
result
{
  "children of ada": ["ben","cy"],
  "ada has a grandchild": "yes",
  "ben is retired": false,
  "who is retired": [true,false]
}
["begin",
  ["relation", "parent", ["parent", "child"]],
  ["relation", "person", ["name"]],
  ["relation", "family", ["name", "children", "kind"]],
  ["fact", ["person", "ada"], ["person", "ben"], ["person", "cy"]],
  ["fact", ["parent", "ada", "ben"], ["parent", "ada", "cy"]],
  ["rule",
    ["family", "?p",
      ["find", "?c", ["parent", "?p", "?c"]],
      ["cond", [["parent", "?p", "?_"], "has children"], [["parent", "?_", "?p"], "has a parent"], ["else", "alone"]]],
    ["person", "?p"]],
  ["query", ["family", "?name", "?children", "?kind"], {"order": "name"}]]
result
[
  {"name":"ada","children":["ben","cy"],"kind":"has children"},
  {"name":"ben","children":[],"kind":"has a parent"},
  {"name":"cy","children":[],"kind":"has a parent"}
]

relation

["relation", name, [column, ...]]
["relation", name, [column, ...], {"key": column-or-columns, "schema": schema-name}]
["relation", name, [column, ...], {"key": column-or-columns, "merge": {column: aggregate, ...}}]
  • Declares a relation in the current database and binds name to it in the global environment. Returns the relation, a function: calling it with one term per column builds a goal. Each term is a schema for its column: a value, a variable, a pattern, or a predicate.
  • Column names must be distinct. Options are read as written, not evaluated. They are "key", "schema", "merge", and optional semantic ontology metadata: "description" (string), "synonyms" (list of non-empty strings), "certified" (boolean), and "references" (record mapping a column name to [targetRelation, targetColumn]).
  • With a key, the relation holds at most one row per key: adding a fact whose key is present replaces the old row. A key can name one column or several.
  • With a merge, which needs a key, the rows a key gets combine instead: each column the merge names, outside the key, combines the values of every candidate with its aggregate, such as "aggregate/min", "aggregate/sum", or "aggregate/count". Every fact of the relation and every row its rules give is a candidate, counted once, a fact never replaces another, and a column the merge does not name must agree. A rule's head gives a merged column plainly, or with the same aggregate. The relation is aggregated: it is derived in full before the rules that read it, and with a lattice aggregate, "aggregate/min", "aggregate/max", "aggregate/shortest", or "aggregate/union", it can go through recursion.
  • A relation whose rules aggregate merges the same way, with the aggregates of its rules' heads and the other columns of the head as its key: its facts, and the rows of its rules with plain heads, are candidates too, whatever order they come in.
  • With a schema, the name of a declared schema, every row must fit it, taken as a record of every column, so the schema names every column or is schema/open. The option adds the invariant ["invariant", ["and", [name, "?column", ...], ["not", [schema, {"column": "?column", ...}]]], {"assert": "none"}], and is nothing more: it must hold for the rows that are there, it is kept and reported like every invariant, and a snapshot writes it as one.
  • Declaring a relation that already exists with the same columns and key does nothing; declaring it with different ones fails. A relation cannot take the name of a schema.
["begin",
  ["relation", "order", ["id", "status"], {"key": "id"}],
  ["fact", ["order", 1, "open"], ["order", 1, "paid"]],
  ["query", ["order", "?id", "?status"]]]
result
[{"id":1,"status":"paid"}]

With a merge, the cheapest offer for each item is the row its key holds, whether a fact or a rule gives it:

["begin",
  ["relation", "offer", ["sku", "usd"]],
  ["relation", "best", ["sku", "usd"], {"key": "sku", "merge": {"usd": "aggregate/min"}}],
  ["fact", ["offer", "a1", 5], ["offer", "a1", 4], ["offer", "b2", 9]],
  ["rule", ["best", "?sku", "?usd"], ["offer", "?sku", "?usd"]],
  ["fact", ["best", "b2", 7]],
  ["query", ["best", "?sku", "?usd"], {"order": "sku"}]]
result
[{"sku":"a1","usd":4},{"sku":"b2","usd":7}]

A relation whose rules aggregate combines the same way: a fact, and a rule with a plain head, give it candidates too. Here refunds come in through a plain rule, and a fact gives the lab a total no sale gives:

["begin",
  ["relation", "sale", ["id", "team", "usd"]],
  ["relation", "refund", ["id", "team", "usd"]],
  ["relation", "spend", ["team", "usd"]],
  ["fact", ["sale", 1, "web", 500], ["sale", 2, "web", 20], ["sale", 3, "ops", 70]],
  ["fact", ["refund", 1, "web", -50]],
  ["rule", ["spend", "?t", ["aggregate/sum", "?usd"]], ["sale", "?id", "?t", "?usd"]],
  ["rule", ["spend", "?t", "?usd"], ["refund", "?id", "?t", "?usd"]],
  ["fact", ["spend", "lab", 0]],
  ["query", ["spend", "?team", "?usd"], {"order": "team"}]]
result
[
  {"team":"lab","usd":0},
  {"team":"ops","usd":70},
  {"team":"web","usd":470}
]

With a schema, a change that would leave a row that does not fit is refused. Here the schema is open, so it need not name the note column:

["begin",
  ["schema", "Order",
    ["schema/open", {"id": "value/integer?", "status": ["schema/anyOf", "open", "paid"]}]],
  ["relation", "order", ["id", "status", "note"], {"key": "id", "schema": "Order"}],
  ["fact", ["order", 1, "open", "gift"]],
  ["fact", ["order", 2, "lost", "none"]]]
error
LogicError: Adding this fact breaks an invariant, so nothing changed. The invariant expected no answers but found 1, such as {"id":2,"status":"lost","note":"none"}: ["and",["order","?id","?status","?note"],["not",["Order",{"id":"?id","status":"?status","note":"?note"}]]]. {"id":2,"status":"lost","note":"none"} does not fit "Order": "status" must fit ["schema/anyOf","open","paid"] but is "lost".

Relations can also declare governed ontology metadata — description, synonyms, certified, and foreign-key references — which persists across snapshots and Prolly trees and powers semantic search, join-path routing, and Apache Ossie export:

["begin",
  ["relation", "supplier", ["id", "name"],
    {"key": "id", "description": "Approved vendor accounts", "synonyms": ["vendor"], "certified": true}],
  ["relation", "shipment", ["id", "supplier_id", "qty"],
    {"key": "id", "references": {"supplier_id": ["supplier", "id"]}}],
  ["fact", ["supplier", "s1", "Acme"], ["shipment", "sh1", "s1", 12]],
  ["query", ["and", ["shipment", "?sh", "?s", "?qty"], ["supplier", "?s", "?name"]]]]
result
[{"sh":"sh1","s":"s1","qty":12,"name":"Acme"}]

schema

["schema", name, shape]
["schema", name, shape, name, shape, ...]
  • Declares a schema in the current database and binds name to it in the global environment. Returns the schema, a function: calling it with a value says whether the value fits the shape.
  • shape is evaluated once, with the values its names have then, as a rule holds the values of its names. It can name the schema being declared, so a schema can describe nested data.
  • One form can declare several schemas, and each shape can name any of them, so schemas can be defined in terms of each other. A value fits only when that follows from the shapes in finitely many steps. A shape can name the schemas of its form but cannot call them, since they have no shape yet.
  • What a name in a shape means is settled when the shape is declared. A name that nothing has yet is a plain string, and nothing can be declared under it afterwards: the later form fails, and says to declare that name first, to declare the two in one form, or to write the string inside quote.
  • A schema that comes back to itself without going into the value does not fit: only 1 fits ["schema", "Loop", ["schema/anyOf", "Loop", 1]].
  • A lambda in a shape can ask about its own schema again. About a smaller value, one that holds fewer values, counting each character of a string, the schema is checked as any schema is. About the same value, it gets the least answer that agrees with itself: first that the value does not fit, then that it fits; when neither agrees, the check fails, since whether the value fits has no answer. About any other value the check is refused, since it need not end. Such a failure inside another schema's lambda makes that schema not fit, as any lambda that fails does.
  • A shape cannot ask the database while it is declared, since a snapshot writes the shape and it must mean the same when loaded. A relation in a shape, or a lambda that asks, asks when a value is checked.
  • Declaring a schema that already exists with the same shape does nothing; declaring it with a different one fails. A schema cannot take the name of a relation.
["begin",
  ["schema", "Tree", {"value": "value/number?", "children": ["schema/arrayOf", "Tree"]}],
  {"fits": ["Tree", ["quote", {"value": 1, "children": [{"value": 2, "children": []}]}]],
   "problems": ["schema/problems",
     ["quote", {"value": 1, "children": [{"value": "two", "children": []}]}], "Tree"]}]
result
{
  "fits": true,
  "problems": [
    {
      "path": ["children",0,"value"],
      "expected": "value/number?",
      "found": "two"
    }
  ]
}

Schemas that one form declares can name each other. Here an expression is a number or a sum, and a sum holds expressions. Loop comes back to itself without going into the value, so only 1 fits it:

["begin",
  ["schema",
    "Expr", ["schema/anyOf", "value/number?", "Sum"],
    "Sum", {"add": ["schema/arrayOf", "Expr"]},
    "Loop", ["schema/anyOf", "Loop", 1]],
  {"a sum of sums": ["Expr", ["quote", {"add": [1, {"add": [2, 3]}]}]],
   "a word in it": ["Expr", ["quote", {"add": [1, {"add": [2, "x"]}]}]],
   "loop": ["array/map", ["array/make", 1, 2], "Loop"]}]
result
{"a sum of sums":true,"a word in it":false,"loop":[true,false]}

A lambda in a shape can ask about its own schema. EvenList asks about the list's tail, a smaller value, so it is plain recursion. Same asks the same question again, and its least answer that agrees with itself is that the value does not fit:

["begin",
  ["schema", "EvenList", ["schema/anyOf", ["quote", []],
    ["lambda", ["v"], ["and", ["value/array?", "v"], ["number/greaterThan", ["array/length", "v"], 0],
      ["not", ["schema/fits?", ["array/tail", "v"], "EvenList"]]]]]],
  ["schema", "Same", ["lambda", ["v"], ["schema/fits?", "v", "Same"]]],
  {"even lengths": ["array/map", ["quote", [[], [1], [1, 2]]], "EvenList"],
   "asks the same question": ["Same", 1]}]
result
{
  "even lengths": [true,false,true],
  "asks the same question": false
}

Odd would fit exactly the values that do not fit it, so no answer agrees with it, and the check fails:

["begin",
  ["schema", "Odd", ["lambda", ["v"], ["not", ["schema/fits?", "v", "Odd"]]]],
  ["Odd", 1]]
error
LogicError: Whether 1 fits "Odd" has no answer: checking it asks the same question again, and the value would fit exactly when it does not.

Asking about a value that is no smaller, such as a list that holds it, is refused:

["begin",
  ["schema", "Grows", ["lambda", ["v"], ["schema/fits?", ["array/make", "v"], "Grows"]]],
  ["Grows", 1]]
error
LogicError: Schema "Grows" asks whether [1] fits it while checking 1. A schema may ask about itself again only about a smaller value, so that its check ends.

Declared in two forms, the first shape would take "Line" for a plain string, so the second form is refused:

["begin",
  ["schema", "Order", {"lines": ["schema/arrayOf", "Line"]}],
  ["schema", "Line", {"sku": "value/string?"}]]
error
UndefinedYetError: "Line" is read before it is defined. A define binds its name from the start of the body it is in, and a relation or schema form from the start of the program, so the string means that definition, which has no value yet. Define it first, or write ["quote", "Line"] to mean the string.

What fits a schema

Anything is a schema, and one rule says what fits it. match, the functions of the schema module, a schema's own parts, and the schema of a relation's rows all ask through it.

  • A function is a predicate: a value fits when the function returns true. A failure, or any other result, counts as not fitting, except a misspelled name, which is an error. A relation with one column, a named schema, and a schema that a schema function built are functions. A relation with more columns is not the schema of one value, and using it as one is an error.
  • A record fits a record with the same keys, with values that fit. A key whose schema is schema/optional can be left out, and schema/open allows keys the record does not name: what a record or list of schemas leaves over is its rest, which is nothing on its own, anything in ["schema/open", record], and what fits rest in ["schema/open", record, rest].
  • A list fits a list of the same length, item by item.
  • Any other value fits a value equal to it.

So data is a schema for itself: it fits exactly the values equal to it.

{"a function": ["schema/fits?", 3, "value/number?"],
 "a record": ["schema/fits?",
   {"id": 1, "tag": "new"},
   {"id": "value/integer?", "tag": "value/string?"}],
 "a key too many": ["schema/fits?", {"id": 1, "tag": "new"}, {"id": "value/integer?"}],
 "a list": ["schema/fits?",
   ["array/make", 2, "kg"],
   ["array/make", "value/number?", ["schema/anyOf", "kg", "lb"]]],
 "a list too long": ["schema/fits?",
   ["array/make", 2, "kg", "net"],
   ["array/make", "value/number?", "value/string?"]],
 "a value": ["schema/fits?", "open", "open"],
 "data for itself": ["schema/fits?", ["quote", {"a": [1, 2]}], ["quote", {"a": [1, 2]}]]}
result
{
  "a function": true,
  "a record": true,
  "a key too many": false,
  "a list": true,
  "a list too long": false,
  "a value": true,
  "data for itself": true
}

A relation with one column is a predicate, so it is a schema: a value fits when it is one of the relation's rows.

["begin",
  ["relation", "person", ["name"]],
  ["fact", ["person", "ada"], ["person", "ben"]],
  {"a person": ["schema/fits?", "ada", "person"],
   "a stranger": ["schema/problems", {"owner": "cy"}, {"owner": "person"}]}]
result
{
  "a person": true,
  "a stranger": [{"path":["owner"],"expected":"person","found":"cy"}]
}
["begin",
  ["relation", "parent", ["parent", "child"]],
  ["fact", ["parent", "ada", "ben"]],
  ["schema/fits?", "ada", "parent"]]
error
LogicError: "parent" has 2 columns, so it cannot be the schema of one value: a relation is a schema when it has one column. To mean the string, write ["quote", "parent"].

A schema check is a call, so it waits for logic variables like any other: as a goal it is a filter, and it gives in a rule what it gives in plain code. A logic variable inside a schema is its value once it is bound, and until then it takes the value it meets; see Patterns. A schema that holds a relation asks the database when it checks a value, so a rule cannot use one that asks about the relation the rule derives.

["begin",
  ["relation", "reading", ["sensor", "value"]],
  ["schema", "Celsius", ["schema/allOf", "value/number?",
    ["lambda", ["c"], ["number/greaterThan", "c", -273.15]]]],
  ["fact", ["reading", "attic", 30], ["reading", "cellar", "cold"], ["reading", "void", -300]],
  {"good": ["find", "?s", ["and", ["reading", "?s", "?v"], ["Celsius", "?v"]]],
   "bad": ["find", "?s", ["and", ["reading", "?s", "?v"], ["not", ["Celsius", "?v"]]]]}]
result
{"good":["attic"],"bad":["cellar","void"]}

Patterns

A schema with a logic variable in it is a pattern. Once the variable is bound it is its value, and until then any value fits it, and binds it. A pattern tests a value and takes it apart at once. These goals bind the variables of a pattern:

  • ["schema/fits?", value, schema] binds the variables in the schema. When nothing else binds the value, it binds the value too, to each value the schema allows, if the schema can list them: data lists itself, a record or list of schemas every way of choosing its parts, with and without a key whose schema is optional, schema/anyOf what its schemas list, schema/allOf what its first schema that can list lists, value/boolean? false and true, value/null? null, and ["schema/arrayOf", schema, most] every list of at most most items. Each value is then checked, so the value takes exactly the values that fit. A schema that cannot list its values but says what kind they are makes the value symbolic instead, and the goals about it are solved for.
  • A relation call binds the variables in its arguments, each a schema for its column. An argument that is not data, such as a predicate or a variable that holds one, is a schema like any other.
  • = and in bind the variables of a record or list, on either side of = or as the element of in. They compare values, so a function in the record is a value there, and not a predicate.
  • A record in a pattern fits a record with the same keys, and schema/open takes the keys it names from a record that has more. A list fits a list of the same length, and schema/open around a list takes its first items. A variable as the rest, as in ["schema/open", {"id": "?id"}, "?rest"], binds the record of the other keys or the list of the other items.
  • ?_ fits any value and binds nothing. A variable that occurs twice must take the same value.
  • Every schema function works in a pattern. schema/anyOf gives the answers of every schema that fits, each once; in plain code, where nothing is left to bind, the first that fits decides.
  • A predicate made from a variable, as ["func/partial", "number/lessThan", "?max"] is, is the predicate made from the variable's value.
  • ["schema/open", "?shape"] does not bind ?shape: it waits for another goal to bind it to a record of schemas.
  • A goal gives the same answers whether it binds a variable through a pattern or finds it bound by another goal, so the order of a body's goals does not matter. A schema lists its values only where no relation goal, =, or in can bind the value first.
  • In plain code, a check with an unbound variable in it is a goal, like = with one. Give it to query.
["begin",
  ["relation", "inbox", ["doc"]],
  ["fact",
    ["inbox", ["quote", {"type": "order", "id": 1, "lines": [{"sku": "a1", "qty": 2}]}]],
    ["inbox", ["quote", {"type": "order", "id": 2, "lines": [], "rush": true}]],
    ["inbox", ["quote", {"type": "refund", "id": 3}]]],
  {"refunds": ["query", ["inbox", {"type": "refund", "id": "?id"}]],
   "orders": ["find", "?id", ["inbox", ["schema/open", {"type": "order", "id": "?id"}]]],
   "lines": ["find", ["array/make", "?order", "?sku"],
     ["and",
       ["inbox", ["schema/open", {"id": "?order", "lines": "?lines"}]],
       ["in", {"sku": "?sku", "qty": "?_"}, "?lines"]]],
   "one value": ["query", ["schema/fits?", ["quote", {"a": 1, "b": 2}],
     ["schema/anyOf", ["schema/open", {"a": "?x"}], ["schema/open", {"b": "?x"}]]]],
   "ends": ["query", ["=", ["array/make", "?first", "?_", "?last"], ["quote", ["a", "b", "c"]]]]}]
result
{
  "refunds": [{"id":3}],
  "orders": [1,2],
  "lines": [[1,"a1"]],
  "one value": [{"x":1},{"x":2}],
  "ends": [{"first":"a","last":"c"}]
}

A variable that occurs twice takes one value, a variable can hold a schema for a later goal, and in plain code a check with an unbound variable is a goal to give to query:

["begin",
  ["relation", "reading", ["sensor", "celsius"]],
  ["fact", ["reading", "attic", 30], ["reading", "cellar", 10], ["reading", "roof", "n/a"]],
  {"the same twice": ["query",
     ["schema/fits?", ["quote", {"low": 3, "high": 3}], {"low": "?n", "high": "?n"}]],
   "not the same": ["query",
     ["schema/fits?", ["quote", {"low": 3, "high": 4}], {"low": "?n", "high": "?n"}]],
   "a schema in a variable": ["find", "?sensor",
     ["and", ["=", "?wanted", ["schema/anyOf", 10, 30]], ["reading", "?sensor", "?wanted"]]],
   "a predicate from a variable": ["find", "?sensor",
     ["and", ["reading", "?sensor", ["func/partial", "number/lessThan", "?least"]],
             ["=", "?least", 20]]],
   "a goal for query": ["query", ["schema/fits?", 1, "?x"]]}]
result
{
  "the same twice": [{"n":3}],
  "not the same": [],
  "a schema in a variable": ["attic","cellar"],
  "a predicate from a variable": ["attic"],
  "a goal for query": [{"x":1}]
}

Solving for values

A schema stands for every value it allows. When nothing else binds the value schema/fits? checks, a schema that lists finitely many values binds it to each (see Patterns). A schema that cannot list them, but says what kind they are, makes the value symbolic instead: the goals about it are solved for.

  • value/integer? stands for a whole number, and value/number? for any number. A record or list of schemas stands for a record or list of what its parts stand for, schema/anyOf for any of its schemas' values, ["schema/arrayOf", schema, most] for a list of each length up to most, and schema/allOf for what its first part stands for that fits the others. Data, value/boolean?, and value/null? stand for their values. A predicate alone, such as a lambda, says no kind, so a variable it types is still unbound.
  • A goal that waits only for such variables joins one step that runs after every other goal its variables need. = with such a variable on one side gives it the value of the other.
  • The step works the goals out on the values: number/add, number/subtract, number/multiply, number/power (with non-negative integer exponents, exact polynomial cancellation, and univariate quadratics), number/divide by a known number, number/floor, number/ceiling, number/round, and number/remainder by a known non-zero divisor; products of unknowns are tracked as exact polynomials so matching nonlinear terms cancel in equalities and comparisons; number/lessThan, number/lessThanOrEqualTo, number/greaterThan, number/greaterThanOrEqualTo, number/equals?, value/integer?, and = make constraints; cond, match, number/min, number/max, number/absolute, boolean/and, boolean/or, boolean/not, boolean/xor, boolean/nand, boolean/nor, boolean/equals?, all value/* predicates and value/identity, and, or, not, schema/fits?, and guarded schema/assert / contracted lambdas make cases; object/get, object/has?, object/set, object/remove, object/merge, object/keys, object/values, object/entries, object/fromEntries, and object/get-path work on records; quantity/* handles dimensional arithmetic and unit checks; func/partial and lambdas run by their body, including begin with local define and recursion over bounded inputs; on a list of known length, such as one ["schema/arrayOf", schema, most] stands for, array/reduce, array/reductions, array/map, array/filter, array/flat-map, array/reverse, array/sort, array/slice, array/zip, array/some?, array/every?, array/length, array/head, array/tail, array/at (including symbolic indices), array/indexOf, array/find, array/range, array/concat, array/includes?, and aggregate/* run item by item, and in takes each item. For universal claims (["not", ["exists", ...]]) over recursive named schemas, unbounded schema/arrayOf, or lower-bounded integers, the solver also proves by structural or numeric induction when the recursive functions are pure, strictly decrease on a structural sub-part or lower-bounded integer measure, and return a uniform sort. Anything else on such a value, such as a product of two distinct unknowns that does not cancel, a string function, or a question, waits: the step lists the values of the variables it needs and runs it on each, as plain code does. When those are infinitely many, the step fails and names what the solver cannot reason about.
  • The solver decides with exact numbers, so every question gets yes or no on every machine: Fourier and Motzkin's method for numbers that may be any number, and Pugh's Omega test for whole ones. Plain code computes with the same exact numbers, so what the solver proves about numbers holds of what plain code computes.
  • The step binds the variables whose values make the answers, to each combination of values they take, when they are finitely many: a whole number bounded on both sides, or any number the goals fix to one value. In a query or a find, which give one answer or value for every match, and in a rule that aggregates, which combines one value from each, those are every variable of the body, as for values a schema lists; in any other rule, those its head shows. A variable a cond defines takes the value of each case that can hold. A variable with infinitely many values fails the step, and says so. The others, such as a plain rule's own, those exists lists, and a question's own under not, only need some values to exist, so exists asks whether one does and not proves that none does, for every value.
  • why explains a row the step gave with an example: values that meet its goals. Where the step stopped a rule, its absent has a certificate for each case the solver split the goals into, which proof/valid? checks with plain arithmetic: whole-number sums compared with 0, steps that add earlier lines multiplied by whole numbers and, over whole numbers, tighten them down to a false line, or a binary integer split tree (kind: "split") when integer refutation needs the Omega test's dark and grey shadows. When induction proved the goal, absent holds an induction proof record. It also has contradicting, the fewest of the step's goals that have no values together, and, where the step denies a goal and those goals leave out every goal it denies, "vacuous": true: the other goals allow no values at all. An exists under not that the solver decides as a whole is told the same way.
  • A step gives at most 100,000 answers, splits into at most 4,096 cases, and makes at most 20,000 constraints while it eliminates its variables. Past those it is refused, so every question ends soon.
["begin",
  ["define", "fee", ["lambda", ["amount"],
    ["cond", [["number/lessThan", "amount", 100], 2],
             ["else", ["number/divide", "amount", 50]]]]],
  {"amounts with a fee of 3": ["find", "?amount",
     ["and", ["schema/fits?", "?amount", "value/integer?"],
       ["number/lessThanOrEqualTo", "?amount", 200],
       ["=", ["fee", "?amount"], 3]]],
   "is the fee ever below 2": ["query",
     ["exists", ["?amount"],
       ["and", ["schema/fits?", "?amount", "value/number?"],
         ["number/greaterThanOrEqualTo", "?amount", 0],
         ["number/lessThan", ["fee", "?amount"], 2]]]]}]
result
{"amounts with a fee of 3":[150],"is the fee ever below 2":[]}

fact

["fact", goal, ...]
  • Adds each fact, a relation call with data and no logic variables, and returns the facts given. Data is JSON values and unknowns. A question among a fact's arguments is asked, and the fact holds its answer.
  • A fact can be exists over a relation call or an and of them. It adds the rows with an unknown for each listed variable, the rows a rule with that head would invent, whether or not the head holds already.
  • A relation's facts are a set; adding a fact that is present changes nothing.
  • For a keyed relation, a fact replaces the row with the same key; within one form, the last fact for a key wins, and the form writes no other fact for that key, so a form whose last facts hold already changes nothing. A relation that merges what a key gets keeps every fact as a candidate instead.
  • A relation that a graph algorithm computes cannot have facts.
  • The form is one change: it is checked in full, made in full, and checked against every invariant, or it fails and changes nothing. A rule or invariant form among its facts fails before any part is evaluated, so it adds no rule.

retract

["retract", goal, ...]
["retract", pattern, {"where": goal}]
  • Removes each fact, and returns the facts that were present and removed. A fact can be exists, as in fact.
  • A rule or invariant form among them, written as it was added, takes that rule or invariant back, and is returned too. The relations whose rules changed are derived again. A rule that says two values are the same takes its invariant back with it.
  • A row of a keyed relation is removed only when every column matches.
  • Facts derived by rules cannot be retracted. What rules derived from a removed fact changes with it.
  • Like fact, the form is one all-or-nothing change.
  • With a pattern and options record {"where": goal}, retracts every matching base fact whose variables satisfy goal.
["begin",
  ["relation", "edge", ["from", "to"]],
  ["fact", ["edge", "a", "b"], ["edge", "b", "c"]],
  ["retract", ["edge", "a", "b"], ["edge", "x", "y"]]]
result
[["edge","a","b"]]
["begin",
  ["relation", "edge", ["from", "to"]],
  ["relation", "linked", ["from", "to"]],
  ["fact", ["edge", "a", "b"]],
  ["rule", ["linked", "?x", "?y"], ["edge", "?x", "?y"]],
  ["rule", ["linked", "?y", "?x"], ["edge", "?x", "?y"]],
  {"taken": ["retract", ["rule", ["linked", "?y", "?x"], ["edge", "?x", "?y"]]],
   "linked": ["query", ["linked", "?from", "?to"]]}]
result
{
  "taken": [["rule",["linked","?y","?x"],["edge","?x","?y"]]],
  "linked": [{"from":"a","to":"b"}]
}

rule

["rule", head, goal, ...]
  • Adds a rule: head holds for every way of satisfying all the goals. Returns the rule as written, with values as evaluated.
  • The head is a relation call, an = between two values, an and of those, which adds a row for each call, or exists over relation calls, which invents a value for each variable it lists.
  • A head ["=", a, b] makes an equality rule: whenever the body holds, a and b are one value. It holds as the invariant ["and", goal, ..., ["not", ["=", a, b]]], so a rule that does not hold is not added and a change that would break it is refused, in an invariant's words. While the relations its body reads are derived, an unknown the rules there invented takes the value on the other side, as under a key. It runs with the relations of every rule that invents an unknown it can meet, which are derived together with every relation it reads, so nothing between them can ask a question about them. See Say that something exists.
  • Head arguments can be values, variables bound by the body, computed values, questions, and aggregates.
  • The rule is checked when added: every head variable must be bound by the body, unless the head lists it in exists, every goal must be safe, and the whole program must stay stratified and terminating. A rule that fails a check is not added.
  • An or in the body makes one rule with several alternatives.
  • Adding a rule the database already holds, one a snapshot would write the same way, changes nothing.
  • Adding a rule is one all-or-nothing change, checked against every invariant.

query

["query", goal]
["query", goal, options]
  • Returns one record per distinct answer, with one key per named variable, without its ?. A goal with no variables returns [{}] when it holds and [] when it does not. A variable that only a question in the goal mentions is not part of an answer.
  • Without the "order" option, answers come in the order they are found, which can change between versions of Lion.
  • Options sort, page, and assert on the answers; see Query options.
["begin",
  ["relation", "edge", ["from", "to"]],
  ["fact", ["edge", "a", "b"], ["edge", "a", "c"]],
  {"targets": ["query", ["edge", "a", "?to"], {"order": "to"}],
   "holds": ["query", ["edge", "a", "b"]],
   "fails": ["query", ["edge", "b", "a"]]}]
result
{"targets":[{"to":"b"},{"to":"c"}],"holds":[{}],"fails":[]}

find

["find", template, goal]
  • Returns the value of template for every match of goal, as a list. The template is any expression over the goal's variables: a variable, a record, a call, or another find.
  • The list is sorted, in the order that values sort in, so it never depends on how the matches were found. A template such as ["array/make", "?points", "?name"] sorts by points first.
  • Every match gives one value, so the list can repeat a value, as aggregate/collect does. A match that several alternatives of an or find gives one. Use aggregate/unique for distinct values.
  • The goal must bind every variable of the template that the rule or query around the find does not.
  • A find is a question: in plain code it is asked right away, and in a rule, query, or another find it is asked for each answer, with the variables that answer has bound.
  • An aggregate of a find combines what it found, also as a whole argument of a rule head. A find with no match is an empty list, so a count of it is 0.
["begin",
  ["relation", "customer", ["name"]],
  ["relation", "order", ["id", "customer", "amount"]],
  ["fact", ["customer", "ana"], ["customer", "bo"], ["customer", "cy"]],
  ["fact", ["order", 1, "ana", 30], ["order", 2, "ana", 20], ["order", 3, "bo", 50]],
  ["find",
    {"customer": "?c",
     "orders": ["find", "?id", ["order", "?id", "?c", "?_"]],
     "total": ["aggregate/sum", ["find", "?amount", ["order", "?_", "?c", "?amount"]]]},
    ["customer", "?c"]]]
result
[
  {"customer":"ana","orders":[1,2],"total":50},
  {"customer":"bo","orders":[3],"total":50},
  {"customer":"cy","orders":[],"total":0}
]

assuming

["assuming", change, ..., expression]
  • Returns what expression gives in the database as it would be after the changes, and leaves the database as it is. Each change is a fact, retract, or rule form, made in order as that form would make it: a key replaces a row, a merge takes a candidate, a rule form adds its rule, a fact or retract states rows with exists as it does on its own, and a retract takes back the rules and invariants it names as well as facts. Each change has its own form's shape, checked as that form checks it. No invariant refuses the change, not even the one an assumed rule that says two values are the same holds as: an invariant keeps the database, and the change is only assumed. So an invariant can ask with assuming without asking itself again.
  • The expression is asked there: a goal is true or false, a find is what it finds, and any other expression is its value. As a goal of a rule or query, the expression must be a goal.
  • An assuming is a question: in plain code it is asked right away, and in a rule, query, or find it is asked for each answer, with the values the answer bound in place. The facts a change states must be known then; every other variable of the expression is its own. A rule a change adds or takes back has variables of its own too: those the answer bound take their values, and the rest are the held rule's.
  • An inner assuming starts from the database the outer one assumed. A rule cannot ask, through one, about a relation that depends on the rule's own head.
  • Each assuming derives what its expression needs in a database of its own, which shares the facts it does not change. Asked for each answer of a rule, it derives once per answer.
["begin",
  ["relation", "road", ["from", "to"]],
  ["relation", "reaches", ["from", "to"]],
  ["fact", ["road", "a", "b"], ["road", "b", "c"]],
  ["rule", ["reaches", "?x", "?y"], ["road", "?x", "?y"]],
  ["rule", ["reaches", "?x", "?z"], ["road", "?x", "?y"], ["reaches", "?y", "?z"]],
  ["invariant", ["road", "?_", "a"], {"assert": "none"}],
  {"with c to d": ["assuming", ["fact", ["road", "c", "d"]], ["find", "?t", ["reaches", "a", "?t"]]],
   "without b to c": ["assuming", ["retract", ["road", "b", "c"]], ["reaches", "a", "c"]],
   "if reaching went both ways": ["assuming",
     ["rule", ["reaches", "?y", "?x"], ["reaches", "?x", "?y"]],
     ["find", "?t", ["reaches", "c", "?t"]]],
   "without the rule that goes on": ["assuming",
     ["retract", ["rule", ["reaches", "?x", "?z"], ["road", "?x", "?y"], ["reaches", "?y", "?z"]]],
     ["find", "?t", ["reaches", "a", "?t"]]],
   "with c to a, which the invariant keeps out": ["assuming", ["fact", ["road", "c", "a"]], ["reaches", "c", "b"]],
   "through a town nobody has named": ["assuming",
     ["fact", ["exists", ["?m"], ["and", ["road", "c", "?m"], ["road", "?m", "e"]]]],
     ["reaches", "a", "e"]],
   "as it is": ["find", "?t", ["reaches", "a", "?t"]]}]
result
{
  "with c to d": ["b","c","d"],
  "without b to c": false,
  "if reaching went both ways": ["a","b"],
  "without the rule that goes on": ["b"],
  "with c to a, which the invariant keeps out": true,
  "through a town nobody has named": true,
  "as it is": ["b","c"]
}

why

["why", fact]
  • Returns a tree that explains how fact, a relation call with no variables or exists over one, holds, or why it does not.
  • When several answers give a fact, why tells the one deriving from nothing finds first: of the answers at the level the fact is held from, the least of the first rule that has one. The tree does not depend on the order the facts came in.
  • A node for a fact that holds has the fact, and either "given": true, "computed": true for a graph algorithm's row, or the rule that derived it with the premises it used under because.
  • A row that a rule which invents gives only because a key or an equality rule made its unknown equal to another value ends with {"same": [unknown, value]}: the unknown the rule named, and the value it was made. See Say that something exists.
  • Premises are facts, {"absent": goal} for a goal under not, and {"check": goal} for every other goal that held: a filter, a schema, an in, and an =, which shows a computed value with the arithmetic that made it, as ["=", 26.4, ["number/divide", …]]. Each is written with the answer's values in place of its variables, so a check, asked as it stands, is true, and an absent is false. A variable that a question binds for itself keeps its name. See Explain a result.
  • A goal that does not hold is {"absent": goal, "because": [way, ...]}, whether it is the fact asked about or a goal under not. A way is something that could have made the goal hold. For a relation call, each rule whose head can give a row it matches is a way, and for a goal made of others, each of its alternatives. A fact no rule could give has an empty because.
  • A way is told once for each answer of its first goals that its next goal stops: {"rule": rule, "because": [premise, ...], "but": node}, without rule for an alternative of a goal. because holds the goals that held, and but the other side of the goal that did not: an absent goal, or for a not, what it denies as it holds, a fact or a check. A rule's body runs from the values the goal gives its head, in the order that reaches them first.
  • When a rule's whole body holds, the rule gave another row than the one asked about: its head computes, combines, or invents a value. That way is {"rule": rule, "but": node}, where the node explains the row the rule gave.
  • An absent goal is explained once in a tree. Where the tree comes to it again, as recursion does, it is written without because. So is a filter, and a goal over a computed relation, which have no ways.
  • "assumed": true marks what could change once an unknown is known: an absent goal that could come to hold, a check that computes with an unknown, and a row that combines matches when one holds an unknown or its rule's body could gain one. An absent goal that is not marked stays absent whatever the unknowns are, and a fact holds whatever they are when nothing it rests on is marked. The mark is safe, not exact: a goal that is marked may still not change. See Explain a result.
  • A row that several answers give is explained the way a database that derives it from the facts as they now are finds it first: by the first rule, in the order rules were added, that gives it in the earliest round, and the least of that rule's answers, comparing the values its body binds in the order it binds them. The tree does not depend on the order facts were added in, or on what the database derived before they changed. See Explain a result.
  • An aggregated fact lists every match it combines under matches, in the order of their answers; for min, max, and shortest, it explains the match that produced the value, the least where several did.
  • A relation goal's premise is the row it matched, also when the goal says which rows with a pattern or a predicate. When several rows fit, since a variable of the goal is its own, it is the row that sorts first. A schema check that held is a check.
  • Explanations use every relation computed in full.
  • why is a question, like find and assuming: inside a query, find, rule, cond, or assuming, it waits for the variables in fact to be bound and explains the row against the current (or assumed) database.
["begin",
  ["relation", "inbox", ["doc"]],
  ["relation", "order", ["id"]],
  ["schema", "Order", {"id": "value/integer?", "status": ["schema/anyOf", "open", "shipped"]}],
  ["fact", ["inbox", {"id": 1, "status": "open"}], ["inbox", {"id": 2, "status": "opne"}]],
  ["rule", ["order", "?id"],
    ["inbox", "?doc"], ["Order", "?doc"],
    ["inbox", ["schema/open", {"id": "?id"}]]],
  {"direct": ["why", ["order", 1]],
   "in find": ["find", {"id": "?id", "proof": ["why", ["order", "?id"]]}, ["order", "?id"]]}]
result
{
  "direct": {
    "fact": ["order",1],
    "rule": [
      "rule",
      ["order","?id"],
      ["inbox","?doc"],
      ["Order","?doc"],
      ["inbox",["schema/open",{"id":"?id"}]]
    ],
    "because": [
      {"fact":["inbox",{"id":1,"status":"open"}],"given":true},
      {"fact":["inbox",{"id":1,"status":"open"}],"given":true},
      {"check":["Order",["quote",{"id":1,"status":"open"}]]}
    ]
  },
  "in find": [
    {
      "id": 1,
      "proof": {
        "fact": ["order",1],
        "rule": [
          "rule",
          ["order","?id"],
          ["inbox","?doc"],
          ["Order","?doc"],
          ["inbox",["schema/open",{"id":"?id"}]]
        ],
        "because": [
          {
            "fact": ["inbox",{"id":1,"status":"open"}],
            "given": true
          },
          {
            "fact": ["inbox",{"id":1,"status":"open"}],
            "given": true
          },
          {"check":["Order",["quote",{"id":1,"status":"open"}]]}
        ]
      }
    },
    {
      "id": 2,
      "proof": {
        "fact": ["order",2],
        "rule": [
          "rule",
          ["order","?id"],
          ["inbox","?doc"],
          ["Order","?doc"],
          ["inbox",["schema/open",{"id":"?id"}]]
        ],
        "because": [
          {
            "fact": ["inbox",{"id":2,"status":"opne"}],
            "given": true
          },
          {
            "fact": ["inbox",{"id":1,"status":"open"}],
            "given": true
          },
          {"check":["Order",["quote",{"id":1,"status":"open"}]]}
        ]
      }
    }
  ]
}

No document has the id 3, and why says where the rule stopped: at the goal that looks for one.

["begin",
  ["relation", "inbox", ["doc"]],
  ["relation", "order", ["id"]],
  ["schema", "Order", {"id": "value/integer?", "status": ["schema/anyOf", "open", "shipped"]}],
  ["fact", ["inbox", {"id": 1, "status": "open"}], ["inbox", {"id": 2, "status": "opne"}]],
  ["rule", ["order", "?id"],
    ["inbox", "?doc"], ["Order", "?doc"],
    ["inbox", ["schema/open", {"id": "?id"}]]],
  ["why", ["order", 3]]]
result
{
  "absent": ["order",3],
  "because": [
    {
      "rule": [
        "rule",
        ["order","?id"],
        ["inbox","?doc"],
        ["Order","?doc"],
        ["inbox",["schema/open",{"id":"?id"}]]
      ],
      "because": [],
      "but": {"absent":["inbox",["schema/open",{"id":3}]],"because":[]}
    }
  ]
}

not

["not", goal]

Holds when the goal has no match. The goal can be any goal: a relation call, a filter, =, in, or a combination of goals with and, or, and not. It is a question, so a variable that appears nowhere else in the rule or query is its own, and it can join relations on such a variable. A filter in it still needs its variables bound. With a boolean, returns its negation.

["begin",
  ["relation", "order", ["id", "amount"]],
  ["fact", ["order", 1, 30], ["order", 2, 120], ["order", 3, 75]],
  ["query",
    ["and", ["order", "?id", "?amount"],
      ["not", ["or", ["number/lessThan", "?amount", 50], ["number/greaterThan", "?amount", 100]]]]]]
result
[{"id":3,"amount":75}]
["begin",
  ["relation", "author", ["person", "paper"]],
  ["relation", "cites", ["paper", "cited"]],
  ["fact", ["author", "ann", "p1"], ["author", "bob", "p2"], ["author", "cyd", "p3"]],
  ["fact", ["cites", "p1", "p3"], ["cites", "p3", "p1"]],
  ["query",
    ["and", ["author", "?person", "?_"],
      ["not", ["and", ["author", "?person", "?paper"], ["cites", "?_", "?paper"]]]]]]
result
[{"person":"bob"}]

and

["and", goal, ...]

Holds when every goal holds, sharing variables between them. On booleans it is the boolean operator: it reads its arguments in order and stops at the first that is false, so later arguments are not evaluated. With no goals it holds: ["and"] is true, as (and) is in Scheme.

or

["or", goal, ...]

Holds when any goal holds. On booleans it is the boolean operator, and stops at the first argument that is true. With no goals it does not hold: ["or"] is false. An answer leaves out a variable that the alternative it came from does not bind. A choice between filters is one test; goals that combine and and or over relations may expand to at most 64 alternatives.

{"and": ["and", true, false],
 "or": ["or", false, true],
 "not": ["not", true],
 "stops early": ["and", false, ["number/divide", 1, 0]],
 "of none": ["array/make", ["and"], ["or"]]}
result
{
  "and": false,
  "or": true,
  "not": false,
  "stops early": false,
  "of none": [true,false]
}

=

["=", term, term]

Binds an unbound variable on either side to the other side's value, or tests that both sides are equal. A side can be a record or list with variables in it, a pattern that takes the other side apart. Without logic variables, it is structural equality of JSON values, and identity for other values. An unknown equals only an unknown written the same way. The numbers 0 and -0 are equal, as JSON writes both as 0.

["=", ["quote", {"a": [1, 2]}], {"a": ["array/make", 1, 2]}]
result
true

in

["in", element, list]

With an unbound element, binds it to each distinct item of the list; with a bound one, tests membership. The element can be a record or list with variables in it, a pattern for the items. The list must be bound first. Without logic variables, it is plain membership and returns a boolean.

["in", "b", ["array/make", "a", "b"]]
result
true

exists

["exists", [variable, ...], goal]
  • Holds when goal holds for some value of each listed variable. The variables must be named logic variables, each listed once, and the goal must mention each.
  • The listed variables are its own wherever it stands, as a question's own variables are: they never bind or meet a variable of the same name outside it, and they never appear in an answer.
  • It is a question, also when its goal has no relation in it. As a value it is true or false, and it works in a query, a rule body, under not, in a find, as a value, and in an invariant.
  • As a rule head, over a relation call or an and of them, it says the head holds for values nobody has given. For each answer of the body whose head does not hold already, the rule invents an unknown for each listed variable. It cannot list a variable the body binds, and a rule that invents cannot aggregate. A listed variable can stand as an argument of the head, or inside a record or list there, but nothing can compute with it.
  • Rules that invent wait until every rule that invents nothing has finished. Then every rule that invents, and whose head does not hold, invents, all at once. The other rules then run on what was invented, and so on until nothing more is invented. The result does not depend on the order rules or facts were added in.
  • Rules that invent may recurse only as long as what they invent never flows back into inventing more; see Termination. A relation that rules invent rows of is derived in full, as an aggregated relation is.
  • In a fact or retract, it states the rows that the same head would invent, whether or not the head holds already. why takes one too.
  • A key makes unknowns equal. When two rows of a keyed relation have the same key and differ only where one holds an unknown that a rule of the keyed relation, or of a relation in a recursive cycle with it, invented, the unknown takes the other row's value: a given value, or, when both are such unknowns, the one that nests fewer unknowns, and of those the one that sorts first. Every row that holds it is then replaced, and the value kept never depends on the order rules or facts were added in. Two different values that are not such unknowns are still an error, and an unknown that a fact holds is given, so a key never changes it.
["begin",
  ["relation", "link", ["from", "to"]],
  ["relation", "node", ["id"]],
  ["fact", ["link", 3, 4], ["node", 3], ["node", 5]],
  ["rule", ["exists", ["?next"], ["link", "?n", "?next"]], ["node", "?n"]],
  {"3 links": ["exists", ["?y"], ["link", 3, "?y"]],
   "a value": ["exists", ["?y"], ["=", "?y", 1]],
   "links": ["query", ["link", "?from", "?to"], {"order": "from"}]}]
result
{
  "3 links": true,
  "a value": true,
  "links": [
    {"from":3,"to":4},
    {"from":5,"to":["some","?next",["link",5,"?next"]]}
  ]
}
["begin",
  ["relation", "person", ["name"]],
  ["relation", "mother", ["child", "mother"]],
  ["rule", ["exists", ["?m"], ["mother", "?c", ["string/concat", "?m", "!"]]], ["person", "?c"]]]
error
LogicError: Rule head ["exists",["?m"],["mother","?c",["string/concat","?m","!"]]] computes with a variable that "exists" owns. An unknown can stand as an argument, or inside a record or list, but nothing can compute with it.

some

["some", variable, goal]
  • The unknown that variable stands for in a match of goal: a value that exists, though nobody has said what it is. A rule that invents gives its unknowns this form, as in ["some", "?m", ["mother", "ben", "?m"]], the value ?m stands for in a row ["mother", "ben", ?m]. Evaluating the form gives the same unknown, so a program can write one.
  • The goal is a relation call or an and of them, and mentions the variable. With an and, the unknown is in every row of it; with several variables in exists, each has its own unknown, and its goal mentions the others.
  • An argument of the goal can be a value, one of its variables, or a record or list of those. A question among the arguments is asked. Nothing may compute with one of its own variables; that is an error.
  • In plain code every variable of the goal is its own. Inside a rule, query, or find, some waits for the variables the rule binds, and every other variable of its goal is its own, so ["some", "?m", ["mother", "?c", "?m"]] is the unknown mother of each ?c.
  • An unknown is data, as a string is: rows, facts, answers, finds, and aggregates hold it. It equals itself and nothing else, as a constant does, and two unknowns are the same when they are written the same way. It sorts after every record, and unknowns sort by how they are written.
  • value/unknown? is true for an unknown, and value/object? is false for one. A function that needs a number or a string fails on one, as it does on any value of the wrong kind.
  • Lion stays closed-world: not holds for anything that is not known, so ["not", ["=", "?m", "eve"]] holds for an unknown ?m.
["begin",
  ["relation", "person", ["name"]],
  ["relation", "mother", ["child", "mother"]],
  ["relation", "tall", ["name"]],
  ["fact", ["person", "ben"], ["person", "cy"]],
  ["rule", ["exists", ["?m"], ["mother", "?c", "?m"]], ["person", "?c"]],
  ["fact", ["tall", ["some", "?m", ["mother", "ben", "?m"]]]],
  {"written": ["some", "?m", ["mother", "ben", "?m"]],
   "in a query": ["query", ["and", ["person", "?p"], ["tall", ["some", "?m", ["mother", "?p", "?m"]]]]],
   "not eve": ["find", "?c", ["and", ["mother", "?c", "?m"], ["not", ["=", "?m", "eve"]]]]}]
result
{
  "written": ["some","?m",["mother","ben","?m"]],
  "in a query": [{"p":"ben"}],
  "not eve": ["ben","cy"]
}

snapshot

["snapshot"]
  • Returns a begin program that rebuilds the current database: a relation form per relation, a schema form for the schemas each schema form declared, every rule, one fact form with every fact, and every invariant, in that order. Loading it checks the facts and the invariants once, against the whole program, as the database was checked, so facts that hold only beside every rule load as they were saved.
  • A schema is written with the form of its shape, and schemas that one form declared are written in one form, so they can name each other when it is loaded. The schema of a relation's rows is written as the invariant it stands for.
  • Strings that would evaluate to something else are written inside quote: logic variable names, relation names, names bound in the environment, and namespaced names such as "number/add". Lists and records are quoted too.
  • A function is written by the name the environment binds it to, so a rule that calls number/add under another name is written with number/add.
  • A cond, match, or record that waits is written as it was, and a lambda as its lambda form. A name in it that would not evaluate to the same value when loaded is bound by a lambda around it.
  • A function that another function built is written as the call that built it, such as ["func/partial", "number/lessThan", 3] or ["schema/arrayOf", "value/number?"].
  • A rule whose head says exists is written as it was, and an unknown in a fact as its some form.
  • Recursive and mutually recursive lambdas are closed into self-contained blocks, so they snapshot, deduplicate, and retract cleanly. Fails only if a rule or invariant holds a function that the environment does not name and that is neither a lambda nor built by a function it can write.
["begin",
  ["relation", "note", ["text"]],
  ["fact", ["note", "plain"], ["note", ["quote", "?x"]], ["note", ["array/make", 1, 2]]],
  ["snapshot"]]
result
[
  "begin",
  ["relation","note",["text"]],
  [
    "fact",
    ["note","plain"],
    ["note",["quote","?x"]],
    ["note",["quote",[1,2]]]
  ]
]
["begin",
  ["define", "fact-fn", ["lambda", ["n"],
    ["cond", [["number/lessThanOrEqualTo", "n", 1], 1],
             ["else", ["number/multiply", "n", ["fact-fn", ["number/subtract", "n", 1]]]]]]],
  ["relation", "num", ["n"]],
  ["relation", "factorial", ["n", "f"]],
  ["fact", ["num", 4]],
  ["rule", ["factorial", "?n", ["fact-fn", "?n"]], ["num", "?n"]],
  {"rows": ["query", ["factorial", "?n", "?f"]],
   "saved": ["snapshot"]}]
result
{
  "rows": [{"n":4,"f":24}],
  "saved": [
    "begin",
    ["relation","num",["n"]],
    ["relation","factorial",["n","f"]],
    [
      "rule",
      [
        "factorial",
        "?n",
        [
          [
            "lambda",
            ["n","fact-fn"],
            [
              "cond",
              [["number/lessThanOrEqualTo","n",1],1],
              [
                "else",
                [
                  "number/multiply",
                  "n",
                  ["fact-fn",["number/subtract","n",1]]
                ]
              ]
            ]
          ],
          "?n",
          [
            [
              "lambda",
              [],
              [
                "begin",
                [
                  "define",
                  "fact-fn",
                  [
                    "lambda",
                    ["n"],
                    [
                      "cond",
                      [["number/lessThanOrEqualTo","n",1],1],
                      [
                        "else",
                        [
                          "number/multiply",
                          "n",
                          ["fact-fn",["number/subtract","n",1]]
                        ]
                      ]
                    ]
                  ]
                ],
                "fact-fn"
              ]
            ]
          ]
        ]
      ],
      ["num","?n"]
    ],
    ["fact",["num",4]]
  ]
}
["begin",
  ["schema",
    "Expr", ["schema/anyOf", "value/number?", "Sum"],
    "Sum", {"add": ["schema/arrayOf", "Expr"]}],
  ["schema", "Order", ["schema/open", {"id": "value/integer?", "total": "Expr"}]],
  ["relation", "order", ["id", "total", "note"], {"key": "id", "schema": "Order"}],
  ["relation", "summed", ["id"]],
  ["fact", ["order", 1, ["quote", {"add": [2, 3]}], "gift"]],
  ["rule", ["summed", "?id"], ["order", "?id", {"add": "?parts"}, "?_"]],
  ["snapshot"]]
result
[
  "begin",
  ["relation","order",["id","total","note"],{"key":["id"]}],
  ["relation","summed",["id"]],
  [
    "schema",
    "Expr",
    ["schema/anyOf","value/number?","Sum"],
    "Sum",
    {"add":["schema/arrayOf","Expr"]}
  ],
  [
    "schema",
    "Order",
    ["schema/open",{"id":"value/integer?","total":"Expr"}]
  ],
  [
    "rule",
    ["summed","?id"],
    ["order","?id",{"add":"?parts"},"?_"]
  ],
  ["fact",["order",1,["quote",{"add":[2,3]}],"gift"]],
  [
    "invariant",
    [
      "and",
      ["order","?id","?total","?note"],
      [
        "not",
        ["Order",{"id":"?id","total":"?total","note":"?note"}]
      ]
    ],
    {"assert":"none"}
  ]
]

invariant

["invariant", goal, {"assert": "none"}]
["invariant", goal, {"assert": "some"}]
  • Adds a query assertion the database keeps: the goal must have no answers ("none") or at least one ("some"). Returns the invariant as written.
  • The goal is compiled and checked like a query's. The options record is read as written and must hold exactly "assert".
  • The invariant must hold when added; otherwise it is not added.
  • After that, every fact, retract, and rule form is checked against every invariant once it has made all of its changes. A form that breaks one, or whose check fails, is undone and fails, leaving the database exactly as it was.
  • Adding an invariant the database already holds changes nothing. ["retract", ["invariant", goal, options]] takes one back.
["begin",
  ["relation", "edge", ["from", "to"]],
  ["invariant", ["edge", "?x", "?x"], {"assert": "none"}],
  ["fact", ["edge", "a", "b"], ["edge", "c", "c"]]]
error
LogicError: Adding these facts breaks an invariant, so nothing changed. The invariant expected no answers but found 1, such as {"x":"c"}: ["edge","?x","?x"].

Reference · information-oriented

Query options

The options record of a query: order, offset, limit, and assert, and the order Lion sorts values in.

A record after a query's goal sorts, pages, and asserts on its answers. Options are read as written, not evaluated. An unknown option, or an option with a value of the wrong kind, fails with a message that names it.

["query", goal, {"order": ["-points", "player"], "offset": 10, "limit": 5, "assert": "some"}]
OptionValueMeaning
"order"A variable name, or a list of themSorts answers by each variable in turn. A leading - sorts that variable from largest to smallest. The ? is optional. Each must be a variable of the query.
"offset"A whole number of at least 0Skips that many answers, after sorting.
"limit"A whole number of at least 0Returns at most that many answers, after the offset.
"assert""some" or "none"Fails the query when it has no answers ("some") or any ("none"). It sees every answer, before offset and limit.

Value order

Sorting compares values of different types in a fixed order: null, then booleans (false before true), numbers, strings, lists, records, and unknowns. Lists compare item by item, records by their entries sorted by key, and unknowns by how they are written. Strings compare by UTF-16 code units, so uppercase letters sort before lowercase ones.

["begin",
  ["relation", "item", ["value"]],
  ["fact", ["item", "b"], ["item", 2], ["item", null], ["item", true],
    ["item", "B"], ["item", ["array/make", 1]], ["item", {"k": 1}],
    ["item", ["some", "?v", ["item", "?v"]]]],
  ["query", ["item", "?value"], {"order": "value"}]]
result
[
  {"value":null},
  {"value":true},
  {"value":2},
  {"value":"B"},
  {"value":"b"},
  {"value":[1]},
  {"value":{"k":1}},
  {"value":["some","?v",["item","?v"]]}
]

Assertion messages

A failed assertion reports the goal and, for "none", how many answers it found and the first one:

["begin",
  ["relation", "edge", ["from", "to"]],
  ["fact", ["edge", "a", "b"]],
  ["query", ["edge", "?from", "?to"], {"assert": "none"}]]
error
LogicError: The query expected no answers but found 1, such as {"from":"a","to":"b"}: ["edge","?from","?to"].

An invariant uses the same assertions and the same wording.

Reference · information-oriented

Standard library

Every function in Lion's default environment, by module: number, boolean, string, array, value, schema, object, func, console, aggregate, and graph.

The default environment, stdlib, names each function module/function. Functions check their arguments. A call with an argument of the wrong kind fails and says which argument, what the function takes there, and what it got, as in "number/add" takes a number as argument 1 but got "one". Each says how many arguments it takes, and a call with any other number fails in the same form, as in "number/subtract" takes 2 arguments but got 3. Each module's example below calls every function in the module.

Every function waits when it is called with a logic variable among its arguments, so all of them work as filters and computed values in rules and queries. A function that is given a goal gets its answer, true or false; see Asking questions. Functions of the aggregate and graph modules take logic variables as they are, to build aggregates and goals.

number

Every argument must be a number. Every number is exact, as Scheme's exact numbers are: an integer of any size or a fraction. A number a program writes is the exact value its digits write, so 0.1 is one tenth, and arithmetic is exact: 0.1 + 0.2 is 0.3, no sum or product overflows, and 1 ÷ 3 is the fraction one third. JSON cannot hold a fraction no decimal writes, so a result that holds one fails to print with ArithmeticError: write it as text with number/toString, or round it with number/round.

FunctionReturns
["number/add", a, b, ...]a + b, and so on for any number of numbers; 0 for none
["number/subtract", a, b]a - b
["number/multiply", a, b, ...]a × b, and so on for any number of numbers; 1 for none
["number/divide", a, b]a ÷ b, exactly: 1 ÷ 3 is the fraction one third. Dividing by 0 fails with ArithmeticError.
["number/remainder", a, b]What is left of a after dividing by b, with the sign of a. A remainder by 0 fails with ArithmeticError.
["number/power", a, b]a to the power of b: exact for a whole b, and failing with ArithmeticError past 4,300 digits; for any other b, such as 0.5, the nearest double
["number/min", a, b, ...]The smallest of one or more numbers
["number/max", a, b, ...]The largest of one or more numbers
["number/absolute", a]a without its sign
["number/floor", a]The largest whole number that is at most a
["number/ceiling", a]The smallest whole number that is at least a
["number/round", a]
["number/round", a, places]
The nearest whole number, or with places, the nearest number with that many digits after the point; a half rounds up
["number/toString", a]
["number/toString", a, separator]
a as text, the way JSON writes it, and a fraction no decimal writes as Scheme writes it, "1/3". With a separator, a string, the whole part is written in groups of three digits with it between them: "1,234,567.5"
["number/fromString", text]
["number/fromString", text, separator]
The number text writes, as string->number reads it in Scheme, exactly, "1/3" among them, or null when text is not one number. With a separator, the whole part may be in groups of three digits with it between them, so it reads back what number/toString writes with the same separator
["number/equals?", a, b]Whether a equals b
["number/lessThan", a, b]Whether a < b
["number/greaterThan", a, b]Whether a > b
["number/lessThanOrEqualTo", a, b]Whether a ≤ b
["number/greaterThanOrEqualTo", a, b]Whether a ≥ b
{"add": ["number/add", 7, 3],
 "add-three": ["number/add", 7, 3, 1],
 "add-none": ["number/add"],
 "subtract": ["number/subtract", 7, 3],
 "multiply": ["number/multiply", 7, 3],
 "divide": ["number/divide", 7, 2],
 "a third, as text": ["number/toString", ["number/divide", 1, 3]],
 "exact decimals": ["number/add", 0.1, 0.2],
 "past 2^53": ["number/add", 9007199254740991, 2],
 "remainder": ["number/remainder", 7, 3],
 "power": ["number/power", 2, 10],
 "min": ["number/min", 7, 3],
 "max": ["number/max", 7, 3],
 "absolute": ["number/absolute", -7],
 "floor": ["number/floor", 2.7],
 "ceiling": ["number/ceiling", 2.1],
 "round": ["number/round", 2.5],
 "round to places": ["number/round", ["number/divide", 2, 3], 2],
 "toString": ["string/concat", "order ", ["number/toString", 42]],
 "grouped": ["number/toString", 1234567.5, ","],
 "fromString": ["number/fromString", "1,234,567.5", ","],
 "not a number": ["number/fromString", "12 apples"],
 "equals?": ["number/equals?", 7, 7],
 "lessThan": ["number/lessThan", 7, 3],
 "greaterThan": ["number/greaterThan", 7, 3],
 "lessThanOrEqualTo": ["number/lessThanOrEqualTo", 3, 3],
 "greaterThanOrEqualTo": ["number/greaterThanOrEqualTo", 2, 3]}
result
{
  "add": 10,
  "add-three": 11,
  "add-none": 0,
  "subtract": 4,
  "multiply": 21,
  "divide": 3.5,
  "a third, as text": "1/3",
  "exact decimals": 0.3,
  "past 2^53": 9007199254740993,
  "remainder": 1,
  "power": 1024,
  "min": 3,
  "max": 7,
  "absolute": 7,
  "floor": 2,
  "ceiling": 3,
  "round": 3,
  "round to places": 0.67,
  "toString": "order 42",
  "grouped": "1,234,567.5",
  "fromString": 1234567.5,
  "not a number": null,
  "equals?": true,
  "lessThan": false,
  "greaterThan": true,
  "lessThanOrEqualTo": true,
  "greaterThanOrEqualTo": false
}
["number/divide", 1, 0]
error
ArithmeticError: number/divide: 1 ÷ 0 has no finite result.

boolean

Every argument must be a boolean.

FunctionReturns
["boolean/not", a]The negation of a
["boolean/and", a, b]Whether both are true
["boolean/or", a, b]Whether either is true
["boolean/xor", a, b]Whether exactly one is true
["boolean/nand", a, b]Whether not both are true
["boolean/nor", a, b]Whether neither is true
["boolean/equals?", a, b]Whether a equals b
{"not": ["boolean/not", true],
 "and": ["boolean/and", true, false],
 "or": ["boolean/or", true, false],
 "xor": ["boolean/xor", true, false],
 "nand": ["boolean/nand", true, true],
 "nor": ["boolean/nor", false, false],
 "equals?": ["boolean/equals?", true, true]}
result
{
  "not": false,
  "and": false,
  "or": true,
  "xor": true,
  "nand": false,
  "nor": true,
  "equals?": true
}

string

Every argument must be a string. Functions that search take the text first. Lengths and positions count UTF-16 code units, as JavaScript does.

FunctionReturns
["string/length", text]The length of text
["string/concat", a, b, ...]a followed by b, and so on for any number of strings; "" for none
["string/startsWith", text, prefix]Whether text starts with prefix
["string/endsWith", text, suffix]Whether text ends with suffix
["string/includes", text, search]Whether text contains search
["string/indexOf", text, search]The position of the first search in text, or -1
["string/join", list, separator]
["string/join", list, separator, last]
The strings of list with separator between them. With last, that string stands before the last item in place of the separator: "a, b and c". Every item must be a string
["string/split", text, separator]The parts of text between each separator; joining them with the same separator gives text back
["string/chars", text]The Unicode characters of text in order, keeping astral characters such as "𝄞" whole
["string/slice", text, start]
["string/slice", text, start, end]
The part of text from start up to, but not including, end, or to the end without it. A negative position counts from the end, and one past either end stops there, as JavaScript's slice cuts
["string/padStart", text, length, fill]text made length long with copies of fill before it; unchanged when it is already that long
["string/padEnd", text, length, fill]The same, with the copies after it
["string/trim", text]text with leading and trailing whitespace removed
["string/toLowerCase", text]text converted to lowercase
["string/toUpperCase", text]text converted to uppercase
["string/replaceAll", text, search, replacement]text with every occurrence of search replaced literally by replacement
["string/matches?", text, pattern]
["string/matches?", text, pattern, flags]
Whether text matches the Unicode regular expression pattern (optional flags from "i", "m", "s")
["string/match", text, pattern]
["string/match", text, pattern, flags]
The first match as {"match", "index", "groups", "named"}, or null when nothing matches
["string/matchAll", text, pattern]
["string/matchAll", text, pattern, flags]
Every non-overlapping match in order as a list of match records
["string/normalize", text]Canonical text for quote verification and entity matching: NFKC, typographic quotes/dashes/ellipsis normalized to ASCII, whitespace collapsed to single spaces and trimmed
["string/numbers", text]
["string/numbers", text, separator]
Every number written in text, in order, each read as number/fromString reads it with the same separator. A minus sign counts only where no letter, digit, or point is right before it, so "2023-24" holds 2023 and 24. Words for amounts are not read: "$1.2 billion" holds 1.2
["string/sha256", text]Deterministic lowercase 64-character hex SHA-256 digest of UTF-8 text
["string/base64-encode", text]Standard Base64 encoding of UTF-8 text
["string/base64-decode", encoded]Decodes standard Base64 text back to UTF-8, failing if malformed
["string/equals?", a, b]Whether a equals b
["string/lessThan", a, b]Whether a comes before b in code-unit order (the same order query "order", array/sort, and aggregate/min use)
["string/greaterThan", a, b]Whether a comes after b in code-unit order
["string/lessThanOrEqualTo", a, b]Whether a is less than or equal to b in code-unit order
["string/greaterThanOrEqualTo", a, b]Whether a is greater than or equal to b in code-unit order
{"length": ["string/length", "lion"],
 "concat": ["string/concat", "lion", "ized"],
 "startsWith": ["string/startsWith", "lion", "li"],
 "endsWith": ["string/endsWith", "lion", "on"],
 "includes": ["string/includes", "lion", "io"],
 "indexOf": ["string/indexOf", "lion", "o"],
 "missing": ["string/indexOf", "lion", "z"],
 "join": ["string/join", ["array/make", "a", "b", "c"], ", "],
 "listed": ["string/join", ["array/make", "a", "b", "c"], ", ", " and "],
 "split": ["string/split", "2026-11-13", "-"],
 "chars": ["string/chars", "a𝄞b"],
 "slice": ["string/slice", "2026-11-13", 0, 7],
 "last": ["string/slice", "lionlang", -4],
 "padStart": ["string/padStart", "7", 2, "0"],
 "padEnd": ["string/padEnd", "7", 3, "."],
 "trim": ["string/trim", "  lion  "],
 "toLowerCase": ["string/toLowerCase", "Lion"],
 "toUpperCase": ["string/toUpperCase", "Lion"],
 "replaceAll": ["string/replaceAll", "a-b-c", "-", "_"],
 "matches?": ["string/matches?", "CVE-2026-0091", "^CVE-\\d{4}-\\d{4}$"],
 "match": ["string/match", "feat(core): add time", "^(?<type>[a-z]+)\\((?<scope>[a-z]+)\\):"],
 "matchAll": ["array/map", ["string/matchAll", "See [1] and [2].", "\\[(\\d+)\\]"], ["lambda", ["m"], ["object/get", "m", "match"]]],
 "normalize": ["string/normalize", " “Acme’s FY25”\n— up 12%… "],
 "numbers": ["string/numbers", "$1,250.5M in fiscal 2023-24, down -3%", ","],
 "sha256": ["string/sha256", "lion"],
 "base64": ["string/base64-decode", ["string/base64-encode", "lion"]],
 "equals?": ["string/equals?", "lion", "lion"],
 "lessThan": ["string/lessThan", "2025-02-01", "2026-03-03"],
 "greaterThan": ["string/greaterThan", "b", "a"],
 "lessThanOrEqualTo": ["string/lessThanOrEqualTo", "a", "a"],
 "greaterThanOrEqualTo": ["string/greaterThanOrEqualTo", "b", "b"]}
result
{
  "length": 4,
  "concat": "lionized",
  "startsWith": true,
  "endsWith": true,
  "includes": true,
  "indexOf": 2,
  "missing": -1,
  "join": "a, b, c",
  "listed": "a, b and c",
  "split": ["2026","11","13"],
  "chars": ["a","𝄞","b"],
  "slice": "2026-11",
  "last": "lang",
  "padStart": "07",
  "padEnd": "7..",
  "trim": "lion",
  "toLowerCase": "lion",
  "toUpperCase": "LION",
  "replaceAll": "a_b_c",
  "matches?": true,
  "match": {
    "match": "feat(core):",
    "index": 0,
    "groups": ["feat","core"],
    "named": {"type":"feat","scope":"core"}
  },
  "matchAll": ["[1]","[2]"],
  "normalize": "\"Acme's FY25\" - up 12%...",
  "numbers": [1250.5,2023,24,-3],
  "sha256": "fc59487712bbe89b488847b77b5744fb6b815b8fc65ef2ab18149958edb61464",
  "base64": "lion",
  "equals?": true,
  "lessThan": true,
  "greaterThan": true,
  "lessThanOrEqualTo": true,
  "greaterThanOrEqualTo": true
}

array

List arguments must be lists. A function argument is called with each item, and can be a lambda, a standard function, or a host function.

FunctionReturns
["array/make", item, ...]A list of the evaluated items
["array/range", start, end]Whole numbers from start up to, but not including, end; at most 1,000,000 of them. Both must be whole numbers.
["array/length", list]The number of items
["array/head", list]The first item. An empty list has none, and fails, as Scheme's car does
["array/tail", list]Every item after the first. An empty list fails, as Scheme's cdr does
["array/at", list, index]
["array/at", list, index, missing]
The item at whole-number index (negative indices count from the end). Out of range, returns missing when given, or fails with IndexOutOfBoundsError
["array/slice", list, start]
["array/slice", list, start, end]
The items from start up to, but not including, end, or to the end without it, counting a negative position from the end, as string/slice cuts text
["array/concat", a, b, ...]The items of a followed by those of b, and so on for any number of lists; [] for none
["array/zip", a, b, ...]The items of one or more lists paired up: a list of the first items, then of the second, up to the end of the shortest list, as Scheme's map goes over several lists
["array/includes?", list, item]Whether the list holds a value equal to item, comparing lists and records by structure
["array/indexOf", list, item]The first index of a value equal to item (comparing by structure), or -1 when absent
["array/find", list, function]
["array/find", list, function, missing]
The first item for which function gives true, stopping there. If none matches, returns missing when given, or fails with LogicError
["array/map", list, function]The list of function's results for each item
["array/filter", list, function]The items of list in order for which function gives true. function gives true or false, as a condition does
["array/flat-map", list, function]The concatenation of the lists function returns for each item
["array/reverse", list]The items of list in reverse order
["array/sort", list]
["array/sort", list, before]
The items of list in ascending canonical order, or stably sorted by before, a function of two items that gives true when the first comes before the second
["array/reduce", list, initial, function]The result of calling function with the running value, starting at initial, and each item in turn
["array/reductions", list, initial, function]Every running value array/reduce passes through, starting with initial; the last is what array/reduce gives. The states a run of steps goes through
["array/some?", list, function]Whether function is true for some item, stopping at the first that is, as Racket's ormap does. function gives true or false, as a condition does
["array/every?", list, function]Whether function is true for every item, stopping at the first that is not, as Racket's andmap does
{"make": ["array/make", 1, 2, 3],
 "range": ["array/range", 0, 4],
 "length": ["array/length", ["array/make", 1, 2, 3]],
 "head": ["array/head", ["array/make", 1, 2, 3]],
 "tail": ["array/tail", ["array/make", 1, 2, 3]],
 "at": ["array/at", ["array/make", 10, 20, 30], -1],
 "at fallback": ["array/at", ["array/make", 10, 20, 30], 9, null],
 "slice": ["array/slice", ["array/make", 1, 2, 3, 4], 1, 3],
 "lastTwo": ["array/slice", ["array/make", 1, 2, 3, 4], -2],
 "concat": ["array/concat", ["array/make", 1], ["array/make", 2, 3]],
 "zip": ["array/zip", ["array/make", 1, 2, 3], ["array/make", "a", "b"]],
 "sums of pairs": ["array/map", ["array/zip", ["array/make", 1, 2, 3], ["array/make", 10, 20, 30]], ["lambda", ["pair"], ["aggregate/sum", "pair"]]],
 "includes?": ["array/includes?", ["quote", [1, {"a": 2}]], {"a": 2}],
 "indexOf": ["array/indexOf", ["quote", [1, {"a": 2}, 3]], {"a": 2}],
 "find": ["array/find", ["array/make", 1, 5, 2, 4], ["lambda", ["x"], ["number/greaterThan", "x", 3]]],
 "find fallback": ["array/find", ["array/make", 1, 2], ["lambda", ["x"], ["number/greaterThan", "x", 3]], null],
 "map": ["array/map", ["array/make", 1, 2], ["lambda", ["x"], ["number/add", "x", 1]]],
 "filter": ["array/filter", ["array/make", 1, 5, 2, 4], ["lambda", ["x"], ["number/greaterThan", "x", 2]]],
 "flat-map": ["array/flat-map", ["array/make", 1, 2], ["lambda", ["x"], ["array/make", "x", "x"]]],
 "reverse": ["array/reverse", ["array/make", 1, 2, 3]],
 "sort": ["array/sort", ["array/make", 3, 1, 2]],
 "sort descending": ["array/sort", ["array/make", 3, 1, 2], "number/greaterThan"],
 "reduce": ["array/reduce", ["array/make", 1, 2, 3], 0, ["lambda", ["acc", "x"], ["number/add", "acc", "x"]]],
 "reductions": ["array/reductions", ["array/make", 1, 2, 3], 0, ["lambda", ["acc", "x"], ["number/add", "acc", "x"]]],
 "some?": ["array/some?", ["array/make", 1, 5, 2], ["lambda", ["x"], ["number/greaterThan", "x", 4]]],
 "every?": ["array/every?", ["array/make", 1, 5, 2], ["lambda", ["x"], ["number/greaterThan", "x", 0]]]}
result
{
  "make": [1,2,3],
  "range": [0,1,2,3],
  "length": 3,
  "head": 1,
  "tail": [2,3],
  "at": 30,
  "at fallback": null,
  "slice": [2,3],
  "lastTwo": [3,4],
  "concat": [1,2,3],
  "zip": [[1,"a"],[2,"b"]],
  "sums of pairs": [11,22,33],
  "includes?": true,
  "indexOf": 1,
  "find": 5,
  "find fallback": null,
  "map": [2,3],
  "filter": [5,4],
  "flat-map": [1,1,2,2],
  "reverse": [3,2,1],
  "sort": [1,2,3],
  "sort descending": [3,2,1],
  "reduce": 6,
  "reductions": [0,1,3,6],
  "some?": true,
  "every?": true
}

value

Predicates tell JSON's kinds of value apart: value/object? is true for records, and value/array? for lists. value/unknown? tells an unknown, a value a rule invented, from a value that was given.

FunctionReturns
["value/number?", x]Whether x is a number
["value/integer?", x]Whether x is a whole number
["value/string?", x]Whether x is a string
["value/boolean?", x]Whether x is a boolean. As a schema it lists false and true.
["value/null?", x]Whether x is null. As a schema it lists null.
["value/array?", x]Whether x is a list
["value/object?", x]Whether x is a record, or another object that is not a list or an unknown, such as a host object
["value/unknown?", x]Whether x is an unknown, such as a value a rule whose head says exists invented
["value/function?", x]Whether x is a function
["value/undefined?", x]Whether x is JavaScript's undefined, which only host values produce
["value/symbol?", x]Whether x is a JavaScript symbol
["value/any?", x]true for every value: the schema that anything fits
["value/equals?", a, b]Structural equality on any two values, the same rule = and in use
["value/compare", a, b]Total value order (-1, 0, or 1), the same order array/sort and query "order" use
["value/identity", x]x
["value/promise?", x]Whether x is a promise delay made
["value/force", x]The value of a promise: its expression run the first time, and kept, as Racket's force gives it; any other x as it is
{"number?": ["value/number?", 1],
 "integer?": ["value/integer?", 1.5],
 "string?": ["value/string?", "a"],
 "boolean?": ["value/boolean?", false],
 "null?": ["value/null?", null],
 "array?": ["value/array?", ["array/make"]],
 "object? of a record": ["value/object?", {}],
 "object? of a list": ["value/object?", ["array/make"]],
 "function?": ["value/function?", "number/add"],
 "undefined?": ["value/undefined?", null],
 "symbol? of a module's own symbol": ["value/symbol?", "number/symbol"],
 "symbol? of text": ["value/symbol?", ["quote", "number/symbol"]],
 "any?": ["value/any?", null],
 "equals?": ["value/equals?", {"a": 1}, {"a": 1}],
 "compare": ["value/compare", {"a": 1}, {"a": 2}],
 "identity": ["value/identity", 42],
 "promise?": ["value/promise?", ["delay", 1]],
 "force": ["value/force", ["delay", ["number/add", 1, 2]]],
 "force of a plain value": ["value/force", 3]}
result
{
  "number?": true,
  "integer?": false,
  "string?": true,
  "boolean?": true,
  "null?": true,
  "array?": true,
  "object? of a record": true,
  "object? of a list": false,
  "function?": true,
  "undefined?": false,
  "symbol? of a module's own symbol": true,
  "symbol? of text": false,
  "any?": true,
  "equals?": true,
  "compare": -1,
  "identity": 42,
  "promise?": true,
  "force": 3,
  "force of a plain value": 3
}

A rule that invents gives unknowns, and value/unknown? keeps them apart from the values that were given:

["begin",
  ["relation", "team", ["name"]],
  ["relation", "lead", ["team", "person"]],
  ["fact", ["team", "web"], ["team", "data"], ["lead", "web", "ana"]],
  ["rule", ["exists", ["?p"], ["lead", "?t", "?p"]], ["team", "?t"]],
  {"leads": ["find", ["array/make", "?t", "?p", ["value/unknown?", "?p"]], ["lead", "?t", "?p"]],
   "known leads": ["find", "?p", ["and", ["lead", "?_", "?p"], ["not", ["value/unknown?", "?p"]]]],
   "object? of an unknown": ["value/object?", ["some", "?p", ["lead", "data", "?p"]]]}]
result
{
  "leads": [
    ["data",["some","?p",["lead","data","?p"]],true],
    ["web","ana",false]
  ],
  "known leads": ["ana"],
  "object? of an unknown": false
}

schema

Checks values against schemas, and builds schemas out of others. Anything is a schema; see What fits a schema. The functions that check take the value first, then the schema. schema gives a schema a name.

FunctionReturns
["schema/fits?", value, schema]Whether the value fits the schema. With a logic variable in it, it is a goal that also binds the variables of the schema, and binds the value to each value the schema allows when the schema can list them; see Patterns.
["schema/problems", value, schema]Every place where the value does not fit, in the order of their paths; an empty list when it fits. A problem is a record with a path, the keys and positions that lead to the part. A part with the wrong value has what was expected, a schema written as the expression that makes it, and what was found. A part that is missing has only expected, and a key the schema does not name has only found.
["schema/includes?", a, b]Whether every value a allows fits b: decided exactly, by listing a's values when it can list them and by the solver otherwise. Fails, and says why, when neither can decide it.
["schema/assert", value, schema]The value, when it fits. When it does not, fails with a message that says where. As a value in a rule or find, it fails the query that runs it.
["schema/anyOf", schema, ...]A schema that fits a value which fits at least one of the schemas. Of plain values it is a list of choices. It reports one problem, at the value that fits none.
["schema/allOf", schema, ...]A schema that fits a value which fits every one of the schemas. It reports the problems of each schema the value does not fit.
["schema/arrayOf", schema]
["schema/arrayOf", schema, most]
A schema that fits a list whose every item fits the schema. With most, a whole number, the list has at most that many items, so a schema whose items can be listed lists every such list.
["schema/recordOf", schema]A schema that fits a record whose every value fits the schema
["schema/optional", schema]As the schema of a record's key, lets the key be left out; a key that is there must fit. Anywhere else it is the schema itself.
["schema/open", record]
["schema/open", record, rest]
A schema that fits a record which fits the record of schemas, or the named schema of one, whatever other keys it has. With rest, the record of its other keys must fit rest. A list of schemas works the same way, with the items after the ones it names as the rest. A record or list of schemas on its own leaves nothing for its rest.

What the building functions return is a function: called with a value, it says whether the value fits. A snapshot writes it as the call that built it.

{"fits?": ["schema/fits?", 3, "value/number?"],
 "problems": ["schema/problems",
   {"id": "x"},
   {"id": "value/integer?", "name": "value/string?"}],
 "assert": ["schema/assert", 3, "value/number?"],
 "includes?": ["schema/includes?", "value/integer?", "value/number?"],
 "numbers not all whole": ["schema/includes?", "value/number?", "value/integer?"],
 "strings not numbers": ["schema/includes?", "value/string?", "value/number?"],
 "anyOf": ["schema/fits?", null, ["schema/anyOf", "value/string?", null]],
 "allOf": ["schema/fits?", 5,
   ["schema/allOf", "value/integer?", ["lambda", ["n"], ["number/lessThan", "n", 3]]]],
 "arrayOf": ["schema/fits?", ["array/make", 1, 2], ["schema/arrayOf", "value/number?"]],
 "at most two": ["schema/fits?", ["array/make", 1, 2, 3], ["schema/arrayOf", "value/number?", 2]],
 "every value": ["find", "?x", ["schema/fits?", "?x", {"on": "value/boolean?", "size": ["schema/anyOf", "s", "m"]}]],
 "recordOf": ["schema/fits?", {"a": 1, "b": "x"}, ["schema/recordOf", "value/number?"]],
 "optional": ["schema/fits?", {}, {"note": ["schema/optional", "value/string?"]}],
 "extra key": ["schema/problems", {"id": 1, "extra": true}, {"id": "value/integer?"}],
 "open": ["schema/fits?", {"id": 1, "extra": true}, ["schema/open", {"id": "value/integer?"}]],
 "open with a rest": ["schema/problems", {"id": 1, "size": "m", "count": 2},
   ["schema/open", {"id": "value/integer?"}, ["schema/recordOf", "value/string?"]]],
 "called": [["schema/arrayOf", "value/number?"], ["array/make", 1, "two"]]}
result
{
  "fits?": true,
  "problems": [
    {"path":["id"],"expected":"value/integer?","found":"x"},
    {"path":["name"],"expected":"value/string?"}
  ],
  "assert": 3,
  "includes?": true,
  "numbers not all whole": false,
  "strings not numbers": false,
  "anyOf": true,
  "allOf": false,
  "arrayOf": true,
  "at most two": false,
  "every value": [
    {"on":false,"size":"m"},
    {"on":false,"size":"s"},
    {"on":true,"size":"m"},
    {"on":true,"size":"s"}
  ],
  "recordOf": false,
  "optional": true,
  "extra key": [{"path":["extra"],"found":true}],
  "open": true,
  "open with a rest": [{"path":["count"],"expected":"value/string?","found":2}],
  "called": false
}
["schema/assert",
  {"id": 7, "tags": ["array/make", "new", 3]},
  {"id": "value/integer?", "tags": ["schema/arrayOf", "value/string?"]}]
error
LogicError: {"id":7,"tags":["new",3]} does not fit {"id":"value/integer?","tags":["schema/arrayOf","value/string?"]}: "tags.1" must fit "value/string?" but is 3.

object

For records and host objects. Paths are dot-separated keys; a numeric segment indexes a list. Keys belong to objects, so reading one needs an object, but a method can belong to any value except null, so the method functions also work on strings, numbers, and lists.

FunctionReturns
["object/get", object, key, missing?]The value under a key the object has, null among them. For a key it does not have, missing, as Racket's hash-ref takes a failure result; without it the call fails with KeyNotFoundError, as object/get-path does. Only the object's own keys count. Fails with NotAnObjectError for a non-object.
["object/has?", record, key]Whether the record has the key, as Racket's hash-has-key? says: true for a key that holds null, and false for one it does not have.
["object/get-path", object, path]The value at path, such as "users.1.name". Fails with KeyNotFoundError, IndexOutOfBoundsError, NotAnArrayError, or PathTraversalError when the path does not lead to a value.
["object/keys", record]The record's keys
["object/values", record]The record's values
["object/entries", record]The record's [key, value] pairs
["object/fromEntries", pairs]A record built from [key, value] pairs; refuses "__proto__"
["object/set", record, key, value]A new record with key holding value, as hash-set gives in Racket. The record it was given is unchanged.
["object/remove", record, key]A new record without key, as hash-remove gives in Racket. Removing a key the record does not hold gives the same record.
["object/merge", record, ...]A new record combining zero or more records left to right (later keys override earlier ones)
["object/json-stringify", value, replacer, space]Any JSON value as JSON text, like JSON.stringify. The replacer and the indent are optional.
["object/json-parse", text]Parses JSON text into a Lion value, keeping decimals and large integers exact
["object/call-method", value, name, argument, ...]The result of calling value's method name. Fails with NotAFunctionError when there is no such method, and NotAnObjectError when value is null.
["object/get-method", value, name]The method name of value, bound to it. Fails like object/call-method.
["object/call-method-path", object, path, argument, ...]The result of calling the method at the end of path, with this set to the value before it. Every value the path passes through must be an object; the last can be any value except null.
["object/get-method-path", object, path]The method at the end of path, bound to the value before it
["object/new", class, argument, ...]A new instance of class. Fails with NotAConstructorError for a non-function.
["begin",
  ["define", "data", ["quote", {"users": [{"name": "ana"}, {"name": "bo"}], "port": 8080}]],
  {"get": ["object/get", "data", "port"],
   "get-path": ["object/get-path", "data", "users.1.name"],
   "keys": ["object/keys", "data"],
   "values": ["object/values", ["quote", {"a": 1, "b": 2}]],
   "entries": ["object/entries", ["quote", {"a": 1, "b": 2}]],
   "fromEntries": ["object/fromEntries", ["quote", [["a", 1], ["b", 2]]]],
   "set": ["object/set", ["quote", {"a": 1}], "b", 2],
   "remove": ["object/remove", ["quote", {"a": 1, "b": 2}], "a"],
   "merge": ["object/merge", ["quote", {"a": 1, "b": 2}], ["quote", {"b": 3, "c": 4}]],
   "keys without port": ["object/keys", ["object/remove", "data", "port"]],
   "json-stringify": ["object/json-stringify", ["quote", {"a": [1, 2]}], null, 0],
   "json-parse exact": ["number/add", ["object/get", ["object/json-parse", "{\"x\": 0.1}"], "x"], 0.2],
   "missing, with a value to use": ["object/get", "data", "host", "localhost"],
   "has?": ["object/has?", "data", "port"],
   "has? a key that holds null": ["object/has?", ["quote", {"host": null}], "host"],
   "call-method": ["object/call-method", "lion", "toUpperCase"],
   "call-method-path": ["object/call-method-path", "data", "users.0.name.toUpperCase"],
   "get-method": [["object/get-method", ["array/make", 1, 2], "join"], "+"],
   "get-method-path": [["object/get-method-path", "data", "users.1.name.padStart"], 4, "."]}]
result
{
  "get": 8080,
  "get-path": "bo",
  "keys": ["users","port"],
  "values": [1,2],
  "entries": [["a",1],["b",2]],
  "fromEntries": {"a":1,"b":2},
  "set": {"a":1,"b":2},
  "remove": {"b":2},
  "merge": {"a":1,"b":3,"c":4},
  "keys without port": ["users"],
  "json-stringify": "{\"a\":[1,2]}",
  "json-parse exact": 0.3,
  "missing, with a value to use": "localhost",
  "has?": true,
  "has? a key that holds null": true,
  "call-method": "LION",
  "call-method-path": "ANA",
  "get-method": "1+2",
  "get-method-path": "..bo"
}

object/new constructs a class that host code binds, as in Call host objects. A value that is not a class fails:

["object/new", 42]
error
NotAConstructorError: Expected a class to construct, but found 42.

quantity

Numbers that carry their units, checked when the program runs, as Pint checks them. A quantity is data: a record of a value and a unit, the unit a record from each base unit's name to its whole exponent, so {"value": 15, "unit": {"m": 1, "s": -1}} is 15 metres a second. A plain number is a quantity with no unit, and a result with no unit left is its plain number. Units are equal when their records are; to convert, multiply by a quantity such as {"value": 1000, "unit": {"m": 1, "km": -1}}. A quantity is a record, so a schema says what unit a value has: {"value": "value/number?", "unit": {"m": 1}}.

FunctionReturns
["quantity/add", a, b, ...]The sum of quantities of one unit, in that unit; quantities of different units fail with ArithmeticError
["quantity/subtract", a, b]The difference of two quantities of one unit
["quantity/multiply", a, b, ...]The product: the values multiplied, each base unit's exponents added
["quantity/divide", a, b]The quotient: the values divided, the divisor's exponents taken away
["quantity/power", a, n]a to the whole power n: each exponent multiplied by n
["quantity/in", a, unit]The number a is in unit, when that is its unit; any other unit fails
["begin",
  ["define", "distance", ["quote", {"value": 120, "unit": {"m": 1}}]],
  ["define", "duration", ["quote", {"value": 8, "unit": {"s": 1}}]],
  ["define", "metres per km", ["quote", {"value": 1000, "unit": {"m": 1, "km": -1}}]],
  {"speed": ["quantity/divide", "distance", "duration"],
   "twice as far": ["quantity/add", "distance", "distance"],
   "a little less": ["quantity/subtract", "distance", ["quote", {"value": 20, "unit": {"m": 1}}]],
   "back to a distance": ["quantity/multiply", ["quantity/divide", "distance", "duration"], "duration"],
   "no unit left": ["quantity/divide", "distance", "distance"],
   "area": ["quantity/power", "distance", 2],
   "in km": ["quantity/in", ["quantity/divide", "distance", "metres per km"], {"km": 1}],
   "farther than 100 m?": ["number/greaterThan", ["quantity/in", "distance", {"m": 1}], 100]}]
result
{
  "speed": {"value":15,"unit":{"m":1,"s":-1}},
  "twice as far": {"value":240,"unit":{"m":1}},
  "a little less": {"value":100,"unit":{"m":1}},
  "back to a distance": {"value":120,"unit":{"m":1}},
  "no unit left": 1,
  "area": {"value":14400,"unit":{"m":2}},
  "in km": 0.12,
  "farther than 100 m?": true
}

A length and a time cannot be added:

["quantity/add", ["quote", {"value": 120, "unit": {"m": 1}}], ["quote", {"value": 8, "unit": {"s": 1}}]]
error
ArithmeticError: quantity/add: 120 {"m":1} and 8 {"s":1} have different units.

func

For working with functions, especially host functions.

FunctionReturns
["func/partial", function, argument, ...]A function that calls function with these arguments followed by its own, exactly as a call written out in full would. Made from a relation, it builds goals, as the relation does. Made from a logic variable in a rule or query, it waits for the variable, so ["func/partial", "number/lessThan", "?max"] is a predicate for values above ?max.
["func/catch", thunk, handler]What thunk, a function of no arguments, gives; when it fails, what handler gives for the failure as data, as Racket's with-handlers: {"failure": kind, "message": text}, and for a failure func/raise made, "failure": "raised" and the value. A call that waits for a logic variable is no failure
["func/raise", value]Fails with value, as Racket's raise: its message is the value, a string as it is, and func/catch gives back the value
["func/reset", thunk]What thunk, a function of no arguments, gives, or what the handler of a func/shift inside it gives: the delimited part of a continuation, as Racket's reset
["func/shift", handler]Stops the delimited part where it stands; its func/reset gives what handler gives for k, the rest of the delimited part. A call of k with a value resumes it there, once, and gives what the rest gives, as Racket's shift, but resumed once
["func/apply", function, this, argument, ..., list]What calling function with this, the arguments, and then the items of list returns, as Scheme's apply spreads its last argument
["func/bind", function, this, argument, ...]function with this and leading arguments fixed
["func/callback", function]A JavaScript function that calls function with as many of the arguments it is given as function takes, and returns its result, or a Promise of it when the work is asynchronous. The callback keeps the environment and database it was created in.
{"partial": [["func/partial", "number/add", 10], 5],
 "apply": ["func/apply", "number/subtract", null, ["array/make", 10, 4]],
 "apply after one": ["func/apply", "number/add", null, 1, ["array/make", 2, 3]],
 "bind": [["func/bind", "number/multiply", null, 3], 7],
 "callback": ["value/function?", ["func/callback", "number/add"]]}
result
{
  "partial": 15,
  "apply": 6,
  "apply after one": 6,
  "bind": 21,
  "callback": true
}

A continuation stops a computation and resumes it later: an early exit, a resumed one, and a generator that yields its items one at a time:

["begin",
  ["define", "generator", ["lambda", ["items"],
    ["func/reset", ["lambda", [],
      ["begin",
        ["array/map", "items", ["lambda", ["item"], ["func/shift", ["lambda", ["k"], {"value": "item", "rest": "k"}]]]],
        {"value": null, "rest": null}]]]]],
  ["define", "first", ["generator", ["array/make", "a", "b"]]],
  ["define", "second", [["object/get", "first", "rest"], null]],
  {"early exit": ["func/reset", ["lambda", [], ["number/add", 1, ["func/shift", ["lambda", ["k"], 42]]]]],
   "resumed": ["func/reset", ["lambda", [], ["number/add", 1, ["func/shift", ["lambda", ["k"], ["number/multiply", 10, ["k", 5]]]]]]],
   "yielded": ["array/make", ["object/get", "first", "value"], ["object/get", "second", "value"]]}]
result
{"early exit":42,"resumed":60,"yielded":["a","b"]}

A failure is data a program can catch, read, and raise:

["begin",
  ["define", "safe divide", ["lambda", ["a", "b"],
    ["func/catch", ["lambda", [], ["number/divide", "a", "b"]],
      ["lambda", ["failure"], {"failed": ["object/get", "failure", "message"]}]]]],
  ["define", "checked", ["lambda", ["n"],
    ["cond", [["number/lessThan", "n", 0], ["func/raise", {"code": "negative", "n": "n"}]], ["else", "n"]]]],
  {"divided": ["safe divide", 6, 3],
   "by zero": ["safe divide", 1, 0],
   "raised": ["func/catch", ["lambda", [], ["checked", -2]], ["lambda", ["failure"], "failure"]]}]
result
{
  "divided": 2,
  "by zero": {"failed":"number/divide: 1 ÷ 0 has no finite result."},
  "raised": {
    "failure": "raised",
    "message": "{\"code\":\"negative\",\"n\":-2}",
    "value": {"code":"negative","n":-2}
  }
}

console

Effects for output. On this page, output appears above the result.

FunctionReturns
["console/log", message]Prints message and returns it
["console/log-json", value]Prints value as indented JSON and returns that text
["begin",
  ["console/log", "starting"],
  ["console/log-json", {"step": 1}],
  "done"]
result
"done"

aggregate

Called on a list, each function combines the list. Called on anything else, it waits for the list its argument turns out to be; a find is the list of what it found. Only as a whole argument of a rule's head, and not on a find, it combines one value from each of the rule's matches instead, grouped by the head's other columns; see Summarize groups of facts. Each function takes exactly one argument.

FunctionReturnsOf nothing
["aggregate/count", values]How many values0
["aggregate/countUnique", values]How many distinct values0
["aggregate/sum", values]The exact sum, so the order of the values never changes it; values must be numbers0
["aggregate/mean", values]The exact mean: the sum divided by how many values there are, which may be a fraction such as 7/3; values must be numbersnull
["aggregate/median", values]The exact median: the middle number for an odd count, or the exact midpoint of the two middle numbers for an even count; values must be numbersnull
["aggregate/argMin", pairs]The value of the [key, value] pair with the smallest key (all numbers or all strings); ties go to the smaller valuenull
["aggregate/argMax", pairs]The value of the [key, value] pair with the largest key (all numbers or all strings); ties go to the smaller valuenull
["aggregate/min", values]The smallest; all numbers or all strings. Lattice.null
["aggregate/max", values]The largest; all numbers or all strings. Lattice.null
["aggregate/shortest", values]The shortest list or string; ties go to the smaller value. Lattice.null
["aggregate/union", values]Every item of every list, distinct and sorted. Lattice.[]
["aggregate/collect", values]Every value, sorted, duplicates kept[]
["aggregate/unique", values]The distinct values, sorted[]

A sum is exact, so adding the same numbers in another order, as the matches of a rule or the candidates of a key may come, gives the same number:

{"forward": ["aggregate/sum", ["array/make", 1e16, 0.1, -1e16, 0.2]],
 "backward": ["aggregate/sum", ["array/make", 0.2, -1e16, 0.1, 1e16]]}
result
{"forward":0.3,"backward":0.3}

Lattice aggregates only move one way as values arrive, so they may aggregate through recursion. See Logic database guarantees.

["begin",
  ["define", "values", ["array/make", 3, 1, 3, 2]],
  {"count": ["aggregate/count", "values"],
   "countUnique": ["aggregate/countUnique", "values"],
   "sum": ["aggregate/sum", "values"],
   "mean": ["aggregate/mean", "values"],
   "median": ["aggregate/median", "values"],
   "argMin": ["aggregate/argMin", ["quote", [[2024, "draft"], [2025, "final"]]]],
   "argMax": ["aggregate/argMax", ["quote", [[2024, "draft"], [2025, "final"]]]],
   "min": ["aggregate/min", "values"],
   "max": ["aggregate/max", "values"],
   "shortest": ["aggregate/shortest", ["quote", [[1, 2], [3], "ab"]]],
   "union": ["aggregate/union", ["quote", [[2, 1], [3, 1]]]],
   "collect": ["aggregate/collect", "values"],
   "unique": ["aggregate/unique", "values"]}]
result
{
  "count": 4,
  "countUnique": 3,
  "sum": 9,
  "mean": 2.25,
  "median": 2.5,
  "argMin": "draft",
  "argMax": "final",
  "min": 1,
  "max": 3,
  "shortest": [3],
  "union": [1,2,3],
  "collect": [1,2,3,3],
  "unique": [1,2,3]
}

graph

Algorithms over an edge relation whose first two columns are from and to. Each call is a goal: give the edge relation, any other inputs, then one term per output column. An input is a value, or a variable that another goal binds; the algorithm then runs once for each value. Results never depend on the order facts were added.

GoalRows
["graph/shortestPath", edges, start, to, cost, path]Dijkstra's algorithm from start, in order of cost, starting with start itself at cost 0. A third edge column is the weight, at least 0; without one, each edge costs 1.
["graph/simplePaths", edges, start, end, maxHops, cost, path]Every cycle-free directed path from start to end of at most maxHops edges, with optional non-negative third-column weights, ordered by cost then path
["graph/lca", edges, a, b, lca, distA, distB]Lowest (most specific) common ancestors of a and b in a DAG following edges from child to parent, with shortest hop distances from a and b
["graph/dominators", edges, start, node, dominator]Immediate dominator tree for every node reachable from start (excluding start itself, so the output edges form a rooted tree DAG)
["graph/influence", edges, start, to, weight]Exact weighted influence from start to each reachable node: sum over all directed simple paths of the product of edge weights (optional third column, defaulting to 1)
["graph/pageRank", edges, node, rank]PageRank with damping 0.85, rounded to 6 decimal places. Ranks add up to 1.
["graph/betweenness", edges, node, score]Directed betweenness centrality by Brandes's algorithm, rounded to 6 decimal places. A third edge column is a non-negative weight; without one, each edge costs 1.
["graph/components", edges, node, component]Connected components, ignoring direction, named after their smallest node
["graph/stronglyConnected", edges, node, component]Strongly connected components, named after their smallest node
["graph/cycles", edges, component, cycle]One canonical shortest directed cycle per cyclic strongly connected component (including self-loops), named after its smallest node; empty on an acyclic graph
["graph/transitiveReduction", edges, from, to]The unique minimal edge set of a DAG with the same reachability (Hasse diagram), or an error naming a cycle
["graph/topologicalOrder", edges, node, position]Positions from 0 in a topological order, or an error that names a cycle
["begin",
  ["relation", "edge", ["from", "to"]],
  ["fact", ["edge", "a", "b"], ["edge", "b", "c"], ["edge", "c", "d"], ["edge", "a", "c"]],
  {"shortestPath": ["query", ["graph/shortestPath", "edge", "a", "d", "?cost", "?path"]],
   "simplePaths": ["query", ["graph/simplePaths", "edge", "a", "d", 3, "?cost", "?path"], {"order": ["cost", "path"]}],
   "lca": ["query", ["graph/lca", "edge", "a", "b", "?lca", "?da", "?db"]],
   "dominators": ["query", ["graph/dominators", "edge", "a", "?node", "?dom"], {"order": "node"}],
   "influence": ["query", ["graph/influence", "edge", "a", "?node", "?weight"], {"order": "node"}],
   "pageRank": ["query", ["graph/pageRank", "edge", "?node", "?rank"], {"order": "-rank", "limit": 1}],
   "betweenness": ["query", ["graph/betweenness", "edge", "?node", "?score"], {"order": "-score", "limit": 1}],
   "components": ["query", ["graph/components", "edge", "?node", "?c"], {"limit": 1}],
   "stronglyConnected": ["query", ["graph/stronglyConnected", "edge", "c", "?c"]],
   "cycles": ["query", ["graph/cycles", "edge", "?component", "?cycle"]],
   "transitiveReduction": ["query", ["graph/transitiveReduction", "edge", "?from", "?to"], {"order": ["from", "to"]}],
   "topologicalOrder": ["query", ["graph/topologicalOrder", "edge", "?node", "?position"], {"order": "position"}]}]
result
{
  "shortestPath": [{"cost":2,"path":["a","c","d"]}],
  "simplePaths": [
    {"cost":2,"path":["a","c","d"]},
    {"cost":3,"path":["a","b","c","d"]}
  ],
  "lca": [{"lca":"b","da":1,"db":0}],
  "dominators": [
    {"node":"b","dom":"a"},
    {"node":"c","dom":"a"},
    {"node":"d","dom":"c"}
  ],
  "influence": [
    {"node":"b","weight":1},
    {"node":"c","weight":2},
    {"node":"d","weight":2}
  ],
  "pageRank": [{"node":"d","rank":0.390362}],
  "betweenness": [{"node":"c","score":2}],
  "components": [{"node":"a","c":"a"}],
  "stronglyConnected": [{"c":"c"}],
  "cycles": [],
  "transitiveReduction": [
    {"from":"a","to":"b"},
    {"from":"b","to":"c"},
    {"from":"c","to":"d"}
  ],
  "topologicalOrder": [
    {"node":"a","position":0},
    {"node":"b","position":1},
    {"node":"c","position":2},
    {"node":"d","position":3}
  ]
}

proof

Checks proof values with a small trusted kernel (without invoking the solver), proves universal or empirical goals, computes exact tight symbolic and relational bounds, and proves universal properties of rule-defined relations by rule induction. See Prove that every command keeps a rule.

proof/valid?
Whether a proof value (linear refutation certificate, Omega integer split tree, case split, induction proof, lemma composition, proof/prove, proof/bounds, or proof/optimize result, or why derivation) checks out under the trusted kernel. With a second claim argument (such as {"atLeast": 0.28}, a relation name, or a ground fact), also checks that the proof establishes that exact claim.
proof/prove
Proves a universal (["not", ["exists", ...]]) or empirical goal, returning a kernel-verifiable proof (with facts and assumptions for database derivations) or a concrete counterexample witness when a universal claim fails.
proof/bounds
Computes exact tight min and max bounds of an expression subject to a goal across continuous linear, mixed-integer linear, integer & continuous linear-fractional ratios (Charnes-Cooper & Dinkelbach), bilinear/quadratic products, and relational database constraints, returning endpoint witnesses and kernel-checkable minProof / maxProof certificates.
proof/optimize
Computes the exact minimum ("min") or maximum ("max") of a numeric objective over every match/solution of a goal, returning {kind: "optimize", direction, status, optimal, inclusive, witness, proof} where proof/valid? independently verifies both the duality certificate and exact bound binding (rejecting any tampered optimal value).
proof/sensitivity
All-derivations epistemic fragility analysis for a closed goal: identifies single-point-of-failure critical facts, redundant facts backed by alternative derivations, resilient status, and minimal size-1/size-2 retraction cut-sets (minimalCuts).
proof/rules
Takes a relation and a target schema, or a record mapping mutually recursive relation names to schemas, and proves by rule induction that every derived row fits its schema across all databases whose base relations fit their declared schemas (including single-column schema invariants, nested pattern destructuring, and aggregate output domains).
proof/facts
Returns the sorted, deduplicated list of recorded (given: true) base facts that a why explanation rests on.
proof/assumptions
Returns the sorted, deduplicated list of leaf absent goals (closed-world negative premises or missing facts) that a why explanation rests on.
proof/liveness
Checks TLA+-style temporal liveness over finite or unbounded state systems: p ~> q under weak (wf) and strong (sf) fairness, general LTL formulas (always, eventually, until, weak-until, leads-to, next), deadlockFree checks, safety-only symmetry reduction, and unbounded symbolic variant ranking proofs.
proof/refines
Checks stuttering-invariant refinement mapping a concrete state machine to an abstract specification, supporting both explicit finite-state BFS (with replayable certificates) and unbounded symbolic SMT refinement (concrete.vars).
proof/invariant
Proves TLAPS-style inductive invariants (initiation, consecution, optional safety, two-state actionProperty, and enabled deadlock freedom) over unbounded symbolic state spaces, with named actions/invariant attribution, automated k-induction, and frame-based IC3/PDR + Farkas interpolation (strengthen: true).
proof/bmc
Apalache-style symbolic bounded model checking up to depth, checking property, two-state actionProperty, traceInvariant, and enabled deadlock freedom, returning a kernel-verifiable bmc certificate or a minimal symbolic counterexample trace.
proof/simp
Normalizes terms or proves equivalence under directed, conditional ([lhs, rhs, when]), or certified (using) rewrite rules with a kernel-replayable rewrite / rewrite-eq certificate.
proof/sat
CDCL SAT solver with two-watched-literals, VSIDS, Luby restarts, and 1-UIP clause learning over DIMACS CNF or propositional formulas, returning a satisfying model, a kernel-verifiable RUP/LRAT UNSAT proof, or unknown on decision limit.
proof/smt
Native lazy DPLL(T) SMT solver combining CDCL SAT, exact LIA/LRA arithmetic, polynomial sum-of-squares, EUF congruence closure, McCarthy arrays with extensionality, bit-vectors, ADTs, Skolemization, and iterative E-graph forall E-matching with claim-bound dpll-t certificates.
proof/calc
Lean-style structured equational and inequality reasoning chains (=, <=, <, >=, >), verifying every step via SMT or proof/simp and emitting a kernel-verifiable calc certificate.
proof/trace
Validates concrete execution or WAL traces against a TLA+-style transition spec (init, next or named actions, optional invariant, actionProperty, and abstraction map), reconstructing firing actions and emitting a kernel-checked trace certificate.
["begin",
  ["schema", "PosRow", {"id": "value/string?", "score": ["schema/allOf", "value/integer?", ["lambda", ["n"], ["number/greaterThanOrEqualTo", "n", 1]]]}],
  ["relation", "base", ["id", "score"], {"schema": "PosRow"}],
  ["relation", "blocked", ["id"]],
  ["relation", "reach", ["id", "score"]],
  ["fact", ["base", "a", 2]],
  ["rule", ["reach", "?x", ["aggregate/min", "?s"]], ["base", "?x", "?s"], ["not", ["blocked", "?x"]]],
  ["rule", ["reach", "?x", ["aggregate/min", ["number/add", "?s", 1]]], ["reach", "?x", "?s"]],
  ["define", "p", ["proof/rules", "reach", "PosRow"]],
  ["define", "w", ["why", ["reach", "a", 2]]],
  ["define", "b", ["proof/bounds",
    ["number/divide", ["number/subtract", "?r", "?c"], "?r"],
    ["and",
      ["schema/fits?", "?r", "value/number?"], ["schema/fits?", "?c", "value/number?"],
      ["number/greaterThanOrEqualTo", "?r", 238], ["number/lessThanOrEqualTo", "?r", 242],
      ["number/greaterThanOrEqualTo", "?c", 161], ["number/lessThanOrEqualTo", "?c", 165]]]],
  ["define", "cov", ["proof/prove", ["not", ["exists", ["?r", "?c"],
    ["and",
      ["schema/fits?", "?r", "value/number?"], ["schema/fits?", "?c", "value/number?"],
      ["number/greaterThanOrEqualTo", "?r", 238], ["number/lessThanOrEqualTo", "?r", 242],
      ["number/greaterThanOrEqualTo", "?c", 161], ["number/lessThanOrEqualTo", "?c", 165],
      ["number/lessThan", ["number/divide", ["number/subtract", "?r", "?c"], "?r"], 0.32]]]]]],
  {"rulesProved": ["object/get", "p", "proved"],
   "rulesValid": ["proof/valid?", "p"],
   "minPct": ["number/round", ["number/multiply", 100, ["object/get", "b", "min"]], 2],
   "maxPct": ["number/round", ["number/multiply", 100, ["object/get", "b", "max"]], 2],
   "boundsValid": ["proof/valid?", "b"],
   "boundsClear30": ["proof/valid?", "b", {"atLeast": 0.30}],
   "sensitivity": ["proof/sensitivity", ["reach", "a", 2]],
   "covenantProved": ["object/get", "cov", "proved"],
   "counterexample": ["object/get", "cov", "counterexample"],
   "facts": ["proof/facts", "w"],
   "assumptions": ["proof/assumptions", "w"]}]
result
{
  "rulesProved": true,
  "rulesValid": true,
  "minPct": 30.67,
  "maxPct": 33.47,
  "boundsValid": true,
  "boundsClear30": true,
  "sensitivity": {
    "critical": [["base","a",2]],
    "holds": true,
    "minCutSize": 1,
    "minimalCuts": [[["base","a",2]]],
    "redundant": [],
    "resilient": false
  },
  "covenantProved": false,
  "counterexample": {"?r":238,"?c":162},
  "facts": [["base","a",2]],
  "assumptions": [["blocked","a"]]
}

time

Deterministic proleptic Gregorian UTC calendar and timestamp functions, with zero dependence on the host's local time zone. Instants are exact integer UTC milliseconds since 1970-01-01T00:00:00.000Z.

CallGives
["time/parse", text]Exact integer UTC epoch milliseconds for an ISO-8601 date ("2026-03-03") or timestamp with explicit zone ("2026-03-03T11:40:00-05:00", "2026-03-03 16:40 UTC"), or null when invalid
["time/fromParts", year, month, day, hour?, minute?, second?, offsetMinutes?]Exact integer UTC epoch milliseconds from Gregorian calendar parts, failing on impossible dates
["time/format", epochMs]
["time/format", epochMs, precision]
ISO-8601 UTC string at "date", "minute", "second" (default), or "ms"
["time/parts", epochMs]Record {"year", "month", "day", "hour", "minute", "second", "ms", "dayOfWeek"} in UTC (dayOfWeek 0=Sunday..6=Saturday)
["time/diff", endMs, startMs]
["time/diff", endMs, startMs, unit]
Exact elapsed duration endMs - startMs in "ms" (default), "seconds", "minutes", "hours", or "days"
["time/add", epochMs, amount, unit]Shifts epochMs by an exact amount in "ms", "seconds", "minutes", "hours", or "days"
["begin",
  ["define", "detected", ["time/parse", "2026-03-03T14:05:00Z"]],
  ["define", "mitigated", ["time/parse", "2026-03-03T11:40:00-05:00"]],
  {"sameAsFromParts": ["=", "mitigated", ["time/fromParts", 2026, 3, 3, 11, 40, 0, -300]],
   "elapsedMinutes": ["time/diff", "mitigated", "detected", "minutes"],
   "nextDay": ["time/format", ["time/add", "mitigated", 1, "days"], "minute"],
   "parts": ["time/parts", "mitigated"]}]
result
{
  "sameAsFromParts": true,
  "elapsedMinutes": 155,
  "nextDay": "2026-03-04T16:40Z",
  "parts": {
    "year": 2026,
    "month": 3,
    "day": 3,
    "hour": 16,
    "minute": 40,
    "second": 0,
    "ms": 0,
    "dayOfWeek": 2
  }
}

Module symbols

Every module except console also binds module/symbol, such as number/symbol, to a JavaScript symbol that identifies the module.

Reference · information-oriented

Logic database guarantees

The rules every logic program follows, what Lion checks and when, and what it promises about changes and answers.

The logic database checks rules, goals, and changes as they arrive, so that every program has one well-defined answer, evaluation always finishes, and the data never ends up half changed.

Safety

  • Every variable in a rule's head must be bound by a goal in its body, unless the head lists it in exists. A variable that exists lists cannot also be bound by the body.
  • Every variable in a filter or in a computed value must first be bound by a relation goal, =, in, or schema/fits?, or typed by a schema that says what kind its values are, such as value/integer?, so that it is solved for. Every variable in an input of a graph algorithm must be bound, and an input must be data. An array is always a call, so a list pattern written as ["?a", "?b"] calls ?a and binds nothing: write it ["array/make", "?a", "?b"], as the message of a goal that cannot run says.
  • schema/fits? binds the value it checks only when nothing else can. A schema that lists the values it allows binds it to each, at most 100,000 of them. One that says what kind they are, such as value/integer?, makes the variable symbolic: the filters about it are solved for, and the ones the solver cannot decide wait for the values it lists. A variable no goal binds and no such schema types stays unbound, and the message says why.
  • A question, a goal under not, a goal used as a value, or a find, waits for the variables that the rule or query around it binds. Every other variable in it is its own, and the question must bind it itself. A find must bind every variable of its template.
  • The list in in must be bound before it runs.
  • Lion orders the goals of a body so each runs once its inputs are bound. Filters that are ready together run in the order written, so a guard written first protects the filter after it. Otherwise the order you write goals in only matters for goal-directed queries.

A rule, query, or invariant that breaks a safety rule fails when it is added or run, with a message that names the unbound variable.

Values

  • A value computed from a logic variable is what the same expression gives with the variable's value in its place. This holds for every function, for cond, match, eval, and records, for lambdas, and for the questions an expression asks: a goal used as a value and a find give in a rule what they give in plain code.
  • A filter must be true or false. The rows a rule derives and the answers a query gives must be data: JSON values and unknowns. Anything else fails with an error that shows the call or the value.
  • A function that fails while a rule or query runs it fails the rule or query. A function given a value it does not take names itself, the argument, and the value, as in plain code; any other failure names the call and the values it ran on.
  • Whether a value fits a schema is the same wherever it is asked: in plain code, under the schema's name, in a rule or query, in match, as an argument of a relation call, and as the schema of a relation's rows.
  • A goal that binds variables through a pattern gives what the same goal gives when another goal has bound those variables first, so the answers of a body do not depend on the order of its goals.

Questions and aggregation

  • Pure negative goals (not over positive relational goals) can go through recursion in plain Datalog strata: Lion computes their unique three-valued well-founded model (Van Gelder's alternating fixpoint), where positive atoms match definitely true rows, not matches definitely false rows, and cyclic facts remain undecided. Other questions—a goal used as a value, a find, why, assuming, a relation handed to a function, or negation inside a cycle with aggregation, existential invention, or equality rules—cannot go through recursion. A question that a rule only builds when it runs, as with eval, fails then instead.
  • An aggregate runs once its inputs are complete. Aggregation may go through recursion only with the lattice aggregates aggregate/min, aggregate/max, aggregate/shortest, and aggregate/union, and only when every relation in the recursive cycle aggregates.
  • Every rule for an aggregated relation must aggregate the same columns in the same way. Its facts, and the rows of its rules with plain heads, are candidates its aggregates combine, as a merge combines them.
  • A rule that invents cannot aggregate. Rules that invent wait until every rule that invents nothing has finished, then every one whose head does not hold invents, all at once, and the other rules run on what was invented, until nothing more is.

Together these make every program stratified: it has a single answer, whatever order rules and facts were added in, unknowns included.

Termination

  • Values flow from the columns a rule's body reads to the columns of its head. A rule may make a new value for a column, by computing it, in the head itself or through = or in, or by inventing it, as long as that value never flows back, through the rules, into making another new value. Values that come from facts are not new. So every new value comes from a finite chain of others, and evaluation stops.
  • A rule that breaks this fails when it is added. A computed value that flows back fails with ... computes a new value in its head while recursing, which may never finish., which suggests computing it in a non-recursive rule or with a lattice aggregate, and an invented one with ... invents a value for "?m" in its head while recursing, which may never finish.
  • Recursion through a lattice aggregate stops when no value improves. If values still improve after 10,000 rounds, as with a negative-weight cycle under aggregate/min, the query fails instead of running forever.
  • A graph algorithm cannot be part of a recursive cycle.

Here a recursive rule computes a label for each path. No rule reads the label to make another value, so the rule is accepted:

["begin",
  ["relation", "edge", ["from", "to"]],
  ["relation", "path", ["from", "to", "label"]],
  ["fact", ["edge", "a", "b"], ["edge", "b", "c"]],
  ["rule", ["path", "?x", "?y", ["string/concat", "?x", "→", "?y"]], ["edge", "?x", "?y"]],
  ["rule", ["path", "?x", "?z", ["string/concat", "?x", "→", "?z"]], ["path", "?x", "?y", "?_"], ["edge", "?y", "?z"]],
  ["query", ["path", "?from", "?to", "?label"], {"order": ["from", "to"]}]]
result
[
  {"from":"a","to":"b","label":"a→b"},
  {"from":"a","to":"c","label":"a→c"},
  {"from":"b","to":"c","label":"b→c"}
]

Every person has a mother, and every mother is a person. Each mother a rule invents would be a person who needs a mother of her own, so the second rule is refused, and the message names the rule that would invent:

["begin",
  ["relation", "person", ["name"]],
  ["relation", "mother", ["child", "mother"]],
  ["rule", ["exists", ["?m"], ["mother", "?p", "?m"]], ["person", "?p"]],
  ["rule", ["person", "?m"], ["mother", "?p", "?m"]]]
error
LogicError: Rule ["rule",["exists",["?m"],["mother","?p","?m"]],["person","?p"]] invents a value for "?m" in its head while recursing, which may never finish. Invent the value in a rule that does not recurse.

Keys

  • A keyed relation holds at most one row per key. A fact with a key that is present replaces the old row.
  • Rules can derive rows of a keyed relation, but two different derived rows with the same key make a query that reads them fail, naming both rows and a rule that gives one now. It names the same rows and the same rule whatever order the rules and facts came in, and whether the rows were derived from nothing or followed through changes. The rows are kept, so asking again fails at once, and the next change is followed through them. A relation that merges joins its merged columns instead, and the rest must agree.
  • The exception is an unknown that a rule of the keyed relation, or of a relation in a recursive cycle with it, invented. When two rows with the same key differ only where one holds such an unknown, the unknown takes the other row's value, or, when both hold one, the one that nests fewer unknowns, and of those the one that sorts first, and every row that holds it is replaced. So the value kept never depends on the order rules or facts were added in. An unknown that a fact holds is given, so a key never changes it.

Here twins share a mother, and an equality rule makes each child's invented mother the one registered for her. Making Ann and Bea twins would give Ann two mothers, Eve and Fay, which the key cannot make one, so the equality rule refuses the change. The message names Fay as derived, since she sorts later, by the rule that passes a twin's mother on:

["begin",
  ["relation", "person", ["name"]],
  ["relation", "twin", ["a", "b"]],
  ["relation", "registered", ["child", "mother"]],
  ["relation", "mother", ["child", "mother"], {"key": "child"}],
  ["rule", ["exists", ["?m"], ["mother", "?c", "?m"]], ["person", "?c"]],
  ["rule", ["mother", "?a", "?m"], ["twin", "?a", "?b"], ["mother", "?b", "?m"]],
  ["rule", ["=", "?m", "?r"], ["mother", "?c", "?m"], ["registered", "?c", "?r"]],
  ["fact", ["person", "ann"], ["person", "bea"], ["registered", "ann", "eve"], ["registered", "bea", "fay"]],
  ["fact", ["twin", "ann", "bea"]]]
error
LogicError: "mother" is keyed by ["child"], but ["rule",["mother","?a","?m"],["twin","?a","?b"],["mother","?b","?m"]] derived ["mother","ann","fay"] while ["mother","ann","eve"] holds.

Changes are all or nothing

A form that changes the database, fact, retract, or rule, either makes all of its changes or fails and makes none of them. Every fact is checked before any is added or removed, and every rule before it is added. When the database has invariants, the form is checked against them after making its changes, and undone if any breaks or cannot be checked, leaving the database exactly as it was, facts in the same order. Separate forms are separate changes.

A change to facts is checked against the invariants that read what it changed, and an invariant that expects no answers is asked about the new rows alone when its goal matches the rows of the relation that changed. That is only a faster way to the same verdict: a change is kept exactly when every invariant still holds.

Adding what is already held

Adding something the database already holds changes nothing: a fact that is present, a relation or schema declared the same way, or a rule or invariant that a snapshot would write the same way. Rules and invariants hold values as they were evaluated, so a name and the value bound to it are the same, whether the value is data or a function, while a variable "?x" and the string ["quote", "?x"] differ. Running a program twice against one database therefore leaves it as running it once did.

Equivalent ways to answer

  • Goal-directed and full evaluation give the same answers, possibly in a different order. A goal-directed query derives only the rows it asks about, so it does not fail on a row it never derives. A relation that rules invent rows of is derived in full, since what such a rule adds depends on every row. Either way, a relation is derived only when a goal reads it with an answer to extend, so neither fails on a relation that no answer reaches.
  • What the database has derived for earlier queries never changes an answer: a query gives what it would give on a database that has derived nothing yet.
  • A snapshot, evaluated into an empty database, gives the same answers as the database it was taken from, and taking a snapshot of that gives the same program.
  • The relation option "schema" and the invariant it stands for keep the same changes, with the same messages, and are saved as the same snapshot.
  • What rules derive is kept, and brought up to date when facts or rules change; what is kept is what evaluation from nothing would give.

Answer order

Without the "order" option, a query's answers come in the order they are found. That order is deterministic for a given program and version of Lion, but it is not part of the language: it can differ with what the database had derived before, and with the changes it has seen. Sort with "order" when order matters. A find always returns its list sorted, so a value a rule derives from one never depends on how it was found.

Reference · information-oriented

Errors

Every way a Lion program can fail, the error's tag, and what causes it.

A failed evaluation is a typed Effect failure. Each error has a _tag you can catch with Effect.catchTag. On this page and in the editor, failures show as Tag: message.

TagRaised when
SchemaErrorThe program is not a valid Lion expression, such as a record key __proto__, or eval is given something that is not JSON.
UnboundNameErrorA string of the form module/name is evaluated, nothing is bound to it, and it reads as a misspelled name: other names of its module are bound, or a bound name is a letter or two away, which the message suggests. The error holds the string as unbound and the suggestion, or null, as nearest. Inside quote the string is data.
InvalidFunctionCallErrorAn array's first element does not evaluate to a function, including a string no scope declares. A misspelled module/name is an UnboundNameError instead.
MalformedFormErrorAn array starts with a special form's name that no scope declares, but does not have the form's shape, such as ["define", "x"]. The message says what the form takes, with an example. The error holds the array as expression, the form's name as form, and what it takes as usage.
UndefinedYetErrorA name is read before the define, relation, or schema form that binds it has run. A body declares the names it defines from its start, so the string means that definition, which has no value yet. A body that defines the name of a form it uses, as ["define", "define", 1] does, fails with it too, and the message says so. The error holds the name as unassigned.
ArithmeticErrorArithmetic has no result, as division by zero has none, or a whole power would have more than 4,300 digits. Numbers are exact, so no sum or product overflows. A value is written as JSON text with a fraction no decimal writes, such as 1/3, which JSON cannot hold.
LogicErrorA logic form fails: an unsafe goal or rule, a recursion or question that breaks the rules, a broken invariant or query assertion, a key conflict, a bad option, and more. The message says what and where. A function called with the wrong number of arguments, or with an argument it does not take, fails with one too, as "number/add" takes a number as argument 1 but got "one".
WaitingErrorA value was needed before it is known. A host function gets this error from call when a Lion function's value is not known yet; the call the host function is part of then waits, so a program does not see it. A program sees it when a fact, retract, or why written inside a rule, query, or find is given a question: those forms act right away, so they cannot wait.
NotAnObjectErrorA function that reads keys received something that is not an object, or a method function received null.
KeyNotFoundErrorobject/get-path reached a key that is not there.
IndexOutOfBoundsErrorobject/get-path indexed past the end of a list.
NotAnArrayErrorobject/get-path used a numeric segment on something that is not a list.
PathTraversalErrorA path passed through a value that is not an object before its last key, or a key that is not there.
InvalidPathErrorA path argument is not a string.
NotAFunctionErrorobject/call-method or object/get-method named something that is not a method.
MethodNotFoundErrorThe end of a method path is not a method.
EmptyPathErrorA method path is empty.
NotAConstructorErrorobject/new was given something that is not a class.

Examples

["number/plus", 1, 2]
error
UnboundNameError: Nothing is bound to "number/plus". Other names begin with "number/", so it reads as a misspelled name. To mean the string itself, write ["quote", "number/plus"].
["plus", 1, 2]
error
InvalidFunctionCallError: ["plus",1,2] is not a valid call. The first element must be a special form or evaluate to a function.
["define", "x"]
error
MalformedFormError: ["define","x"] is not a well-formed define form: define takes a name and an expression, as in ["define", "answer", 42].
["begin", ["define", "total", ["number/add", "tax", 1]], ["define", "tax", 2]]
error
UndefinedYetError: "tax" is read before it is defined. A define binds its name from the start of the body it is in, and a relation or schema form from the start of the program, so the string means that definition, which has no value yet. Define it first, or write ["quote", "tax"] to mean the string.
["number/divide", 1, 0]
error
ArithmeticError: number/divide: 1 ÷ 0 has no finite result.
["number/divide", 1, 3]
error
ArithmeticError: 1/3 is a fraction no decimal writes, so JSON cannot hold it: round it with ["number/round", value, places], or write it as text with number/toString.
["begin",
  ["define", "pair", ["lambda", ["a", "b"], ["array/make", "a", "b"]]],
  ["pair", 1]]
error
LogicError: "pair" takes 2 arguments but got 1.
["number/add", "one", 2]
error
LogicError: "number/add" takes a number as argument 1 but got "one".
["begin",
  ["relation", "edge", ["from", "to"]],
  ["relation", "lonely", ["node"]],
  ["rule", ["lonely", "?n"], ["not", ["edge", "?n", "?_"]]]]
error
LogicError: Unsafe rule head ["lonely","?n"]: ?n never appears in a relation in the body. To say the head holds for some value nobody has given, list it in "exists": ["exists", ["?n"], head].
["object/get-path", ["quote", {"a": {"b": 1}}], "a.c"]
error
KeyNotFoundError: There is no key "c" in {"b":1}.

The functions a failure left

A failure that leaves the body of a function says so: its message ends with the functions it left, innermost first. A function has a name there when a define bound it, as in Racket. A function that made its call in tail position has nothing left of its own when the failure passes, as in Scheme, so it is not named; neither is a function no define bound. The failure keeps its kind.

["begin",
  ["define", "next", ["lambda", ["n"], ["number/add", "n", 1]]],
  ["define", "label", ["lambda", ["n"], ["string/concat", "item ", ["next", "n"]]]],
  ["label", "seven"]]
error
LogicError: "number/add" takes a number as argument 1 but got "seven". (in "next", called from "label")

Errors inside rules and queries

A function that fails while a rule or query runs it fails the rule or query. A function given a value it does not take says which function, which argument, and what it got, as it does in plain code. Any other failure is a LogicError that names the call and the values it ran on. An ArithmeticError stays as it is, since it already names both. A filter that is not true or false, and an answer that is not data, fail with a LogicError too.

["begin",
  ["relation", "reading", ["value"]],
  ["fact", ["reading", 4], ["reading", "n/a"]],
  ["query", ["and", ["reading", "?v"], ["number/greaterThan", "?v", 3]]]]
error
LogicError: "number/greaterThan" takes a number as argument 1 but got "n/a".

Errors from host functions

A host function that returns a failed Effect fails the program with that Effect's error. A host function that throws, or a defect inside the evaluator, fails the program as a defect rather than a typed error; Effect.runPromise rejects with it.

Reference · information-oriented

Command line

The lion command from @lionlang/cli: evaluating files, keeping a database file, serving the graph editor, and printing Lion as a Web Worker.

Install with bun add --dev @lionlang/cli. The package provides the lion command.

lion [<file>...]

lion [--database <path>] [--read-only] [--bind <name=json>]... [--bind-file <name=path>]... [--eval <json>] [<file>...]

Reads one or more Lion programs as JSON from files (evaluated sequentially against one database, each with a fresh top-level environment), --eval (-e), or standard input (when file is - or omitted while stdin is piped), evaluates them with the standard library and any --bind / --bind-file bindings, and prints the final result as JSON indented by two spaces.

Argument or flagMeaning
file...One or more paths to Lion programs in JSON (run in order against one database), or - to read from standard input. Optional when --eval is passed or stdin is piped.
--eval <json>, -e <json>Evaluate a Lion program written directly on the command line instead of reading files.
--bind <name=json>, -b <name=json>Bind a top-level name to a JSON value, preserving exact decimals and large integers. Repeatable; overrides --bind-file for the same name.
--bind-file <name=path>Bind a top-level name to the JSON value read from a file, preserving exact numbers. Repeatable.
--database <path>A JSON file that holds the logic database. It is loaded before the programs run; if it does not exist, the database starts empty. After all programs succeed, the database is saved back as a snapshot (one form and one fact per line) only if the file did not exist or the database changed. If any program fails, the file is not written.
--read-only, -rLoad --database without ever writing changes back to disk, even if the program asserts or retracts facts or rules.

lion inspect [<file>]

lion inspect [--derived] (<file> | --database <path>)

Loads a saved database read-only and prints a concise JSON summary of its ontology: every relation (columns, key, merge, base fact count, rule count, and optionally total derived row count with --derived), every named schema and its shape, every invariant, and summary totals.

Argument or flagMeaning
file / --database <path>Path to the saved Lion database file to inspect. Never modified.
--derived, -dAlso evaluate rules and include total row counts (rows) for each relation.

lion check [<file>]

lion check [--database <path>] [--bind <name=json>]... [--bind-file <name=path>]... [--eval <json>] [<file>]

Reads a program without running it and prints a JSON list of diagnostics and warnings, each with its JSON pointer in at: malformed forms, misspelled namespaced names, wrong-arity calls to known functions, relations, schemas, or lambdas, invalid relation/query/invariant options, unsafe rule heads or find templates, logic variables in ground facts, unreachable or non-exhaustive match cases, unreachable cond branches after else, duplicate lambda parameters, near-miss bare call heads, and Lion lints such as lists written as bare arrays inside rules or queries. Exits with status 1 when any error is found.

Argument or flagMeaning
filePath to a Lion program in JSON, or - to read from standard input. Optional when --eval is passed or stdin is piped.
--eval <json>, -e <json>Check a Lion program written directly on the command line.
--bind <name=json>, -b <name=json>Declare a top-level binding while checking the program. Repeatable.
--bind-file <name=path>Declare a top-level binding from a JSON file while checking the program. Repeatable.
--database <path>Load a saved database read-only before checking, so calls to its declared relations and schemas are recognized and checked for arity without modifying the file.

lion repl

lion repl [--host <address>] [--port <number>]

Serves the Fold Map graph editor bundled with the command, and prints its address. It runs until stopped.

FlagDefaultMeaning
--host127.0.0.1Address to listen on.
--port3000Port to listen on, from 1 to 65535.

lion serve

lion serve [--host <address>] [--port <number>] [--store <spec>] [--replica] [--sync-ms <ms>]
  [--multi-tenant] [--idle-ms <ms>] [--max-tenants <n>]
  [--group-commit-ms <ms>] [--compact-every <n>]
  [--peer <url>]... [--peer-sync-ms <ms>] [--auth-token <secret>]

Runs a stateful HTTP + SSE + Streamable MCP server over a sandboxed, journaled Lion database. Exposes GET /health, GET /v1/inspect, GET /v1/schema, GET /v1/calm, GET /v1/merkle, GET/POST /v1/delta, POST /v1/check, POST /v1/eval, POST /v1/commit, POST /v1/branches, POST /v1/sync, POST /v1/prolly/blocks, POST /v1/prolly/diff, POST /v1/sync/prolly, POST /v1/compact, POST /v1/clone, POST /v1/watch, GET /v1/ontology/fks, GET /v1/ontology/join-path, POST /v1/ontology/search, POST /v1/ontology/answerable, GET /v1/ontology/ossie, POST /v1/ontology/ossie/import, GET /v1/quorum/status, POST /v1/quorum/elect, POST /v1/quorum/replicate, POST /v1/quorum/vote, POST /v1/quorum/append, POST /v1/quorum/snapshot, POST /v1/quorum/compact, and POST /v1/mcp. With --multi-tenant, also exposes GET /v1/tenants, POST /v1/tenants/:id/hibernate, and /v1/tenants/:id/<route>.

FlagDefaultMeaning
--store <spec>in-memoryDurable object store: local directory, file:///path, sqlite:///path.db, sqlite://:memory:, or s3://bucket/prefix.
--replicafalseOpen --store as a read-only SWMR replica without fencing the writer.
--sync-ms1000Background WAL sync interval in ms when --replica is set (0 disables).
--multi-tenantfalseEnable prefix-isolated per-tenant actors under /v1/tenants/:id/... with automatic hibernation.
--idle-ms60000Idle timeout in ms before hibernating inactive tenants.
--max-tenants128Maximum active tenants kept in memory before LRU hibernation.
--group-commit-ms0Coalesce concurrent commits within this window into a single batched WAL write.
--compact-every0Automatically compact into a content-addressed Prolly checkpoint every N commits.
--peer <url>nonePeer Lion server URL for background O(diff) Prolly anti-entropy gossip (repeatable).
--peer-sync-ms5000Background anti-entropy gossip interval in ms when --peer is set.
--auth-token <secret>$LION_AUTH_TOKENRequire Authorization: Bearer <secret> on all routes except /health.
--spill-threshold <n>0Automatically spill any base relation reaching n facts into an out-of-core LsmSpine (0 disables).

lion mcp

lion mcp [--store <spec>] [--replica] [--read-only] [--max-steps <n>] [--max-facts <n>]

Runs a Model Context Protocol (MCP) JSON-RPC 2.0 server over stdio exposing lion_check, lion_eval, lion_commit, lion_inspect, lion_schema, lion_search, lion_answerable, lion_branch, lion_calm, lion_sync (extract, merge, prolly, pull), and lion_compact.

lion diff <left> <right>

lion diff [--derived] <left> <right>

Compares two saved Lion database snapshots and prints added and removed relations, rules, invariants, base facts, and (with --derived) derived rows.

lion schema

lion schema [--mode <full|eval|query|commit>] [--database <path>]

Emits Draft 2020-12 JSON Schema for valid Lion programs or for a specific saved database's relations and arities, suitable for structured LLM tool outputs.

lion ossie <export|import>

lion ossie export --database <path> --out <dir>
lion ossie import --dir <dir> [--database <path>]

Exports governed Lion relation metadata (description, synonyms, certified, references, keys, and inferred FKs) into an Apache Ossie 3-file YAML bundle (semantic_model.yaml, ontology.yaml, mapping.yaml), or imports an Ossie bundle back into runnable Lion relation declarations.

lion artifact

lion artifact <file> [--out <path.html>] [--title <text>] [--description <text>] [--theme dark|light] [--runtime-src <url>]

Packages any Lion JSON UI program into a standalone, shareable public HTML artifact that evaluates Datalog queries, counterfactual assuming branches, and formal proof/* certificates live in the browser. Omit --runtime-src to inline the full browser runtime for a 100% single-file offline HTML page, or pass --runtime-src to share a hosted runtime script across multiple pages.

lion worker

lion worker > lion-worker.js

Prints the command's own Lion as a Web Worker script, for a page that runs Lion in a browser. The worker holds one logic database. Each message posted to it has an id, and each answer it posts back has the same id, ok, the value as JSON text in json or the reason in error, and ms, how long it took.

MessageMeaning
{"type": "load", "snapshot": saved}Loads a database from a saved one, as --database loads its file, in place of the one the worker held.
{"type": "run", "program": program}Runs a program against the database, as lion <file> --database does. A program can change the database.

These are the answers the worker gives to a database of edges and the paths they make, and two programs run against it, without ms:

{"id":1,"type":"load","snapshot":["begin",
  ["relation","edge",["from","to"]],["relation","path",["from","to"]],
  ["fact",["edge","a","b"],["edge","b","c"]],
  ["rule",["path","?x","?y"],["edge","?x","?y"]],
  ["rule",["path","?x","?z"],["path","?x","?y"],["edge","?y","?z"]]]}
  answers {"id":1,"ok":true,"json":"null"}
{"id":2,"type":"run","program":["find","?to",["path","a","?to"]]}
  answers {"id":2,"ok":true,"json":"[\"b\",\"c\"]"}
{"id":3,"type":"run","program":["path","a"]}
  answers {"id":3,"ok":false,"error":"\"path\" takes 2 arguments (from, to) but got 1."}

A page that carries the script runs the Lion of the command that printed it, so running the page's programs with that command checks the page.

Global flags

FlagMeaning
--help, -hShow help for the command or subcommand.
--version, -vShow the version.
--wizardBuild the command interactively.
--completions <shell>Print a completion script for bash, zsh, fish, powershell, sh, or pwsh.
--log-level <level>Minimum log level: all, trace, debug, info, warn, error, fatal, or none.

Exit status

0 when the program succeeds. 1 when the file cannot be read or parsed, the program fails, or the database cannot be loaded or saved; the error is printed.

Reference · information-oriented

TypeScript API

The exports of @lionlang/core and @lionlang/typesafe-ai that host applications use.

Every module of @lionlang/core is importable by path, such as @lionlang/core/evaluation/evaluate. These are the exports meant for host applications. Evaluation results are Effects; see Run Lion from TypeScript.

@lionlang/core/evaluation/evaluate

run(expression, environment, options?)

Decodes expression as a Lion program and evaluates it with environment, a record of bindings. Returns an Effect of the result, failing with a Lion error.

options.database: a LogicDatabase to use instead of an empty one. Its relations are bound by name, unless environment binds the same name.

watch(query, environment, database, onChange)

Watches a query of a database: query is Lion code, such as a find, run as run runs it against database. Returns an Effect of {answers, stop}: what the query gives now, and a function that stops the watching. After each change a fact, retract, rule, or invariant form makes that adds or takes away an answer, onChange is called with {answers, added, removed}. The database keeps what it derived up to date as facts change, so asking again costs what the change costs. A change an invariant refuses, and what assuming asks, tell nothing.

const database = new LogicDatabase();
await Effect.runPromise(run(setup, stdlib, { database }));
const { answers, stop } = await Effect.runPromise(
  watch(["find", "?to", ["path", "a", "?to"]], stdlib, database, ({ added, removed }) =>
    console.log("reachable now", added, "no longer", removed)
  )
);
await Effect.runPromise(run(["fact", ["edge", "c", "d"]], stdlib, { database }));
// reachable now [ "d" ] no longer []
stop();
evaluate(expression)

Evaluates an already decoded expression. Requires LionEnvironmentService and, for logic forms, LionDatabaseService. Most hosts use run.

@lionlang/core/modules

stdlib

The standard library as a record of bindings.

namespaceEntries(namespace, record)

Returns a copy of record with every key prefixed by namespace/.

@lionlang/core/logic/database

new LogicDatabase(options?)

A logic database to share across runs. It holds relations, schemas, facts, rules, and invariants.

options.goalDirected: when false, every query derives every row of the relations it reads instead of only what it can reach. Defaults to true.

@lionlang/core/logic/fit

fits(schema, value)

An Effect that gives whether a value fits a schema. A host function that takes a schema can check values with it. Like call, it needs what an evaluation provides.

problemsOf(schema, value)

An Effect that gives every place where the value does not fit, as schema/problems does.

misfit(schema, value)

An Effect that gives the sentence schema/assert fails with, or undefined when the value fits.

@lionlang/core/logic/model

MAX_LATTICE_ROUNDS

10,000: the rounds recursion through lattice aggregates may take before failing.

@lionlang/core/evaluation/special-forms/function

call(fn, ...args)

Calls a Lion function, such as a lambda a host function was given, and returns an Effect of its value. A goal the function returns is asked, so the value is true or false. If the value is not known yet, the Effect fails with WaitingError and the call the host function is part of waits. Use it in a host function that works with what its callback returns.

apply(fn, args)

Calls a function the way a Lion call does, and returns an Effect of what the call evaluates to, which can be a value that waits.

@lionlang/core/logic/snapshot

saveDatabase(database, options?)

Returns an Effect of the database as a snapshot program. Recursive and mutually recursive lambdas are closed into self-contained blocks; fails with LogicError only if a rule or invariant holds a function the environment does not name and cannot write.

options.isBound(name): names bound where the snapshot will be loaded; strings equal to them are quoted.

loadDatabase(program, environment)

Evaluates program into a new LogicDatabase and returns an Effect of it.

Scaling, persistence, and sync modules

@lionlang/core/logic/journal — openJournal, openReadReplica

WAL-backed JournaledDatabase with atomic transactions, optimistic concurrency (expectedRevision), WAL group commit (commitBatch), incremental Prolly checkpoints (compact), time-travel (checkout), CoW branching (fork / merge), revision-cached merkleRoot(), and single-writer multi-reader ReadReplica.

@lionlang/core/logic/prolly — buildProllyTree, applyProllyMutations, diffProllyTrees, syncProllyTrees, snapshotDatabaseToProlly, loadDatabaseFromProlly, CachedBlockStore

History-independent, SHA-256 content-addressed Prolly trees with localized prefix reuse, O(log N + K) range scans (scanProllyRange), O(diff) Merkle range-sync with hash verification, and bounded LRU block caching.

@lionlang/core/logic/object-store — openObjectStoreJournal, ObjectStoreJournalStore, ObjectStoreBlockStore, DurableObjectObjectStore, sweepUnreferencedBlocks

SlateDB-inspired object-store journal using numbered CAS manifests, writerEpoch zombie-writer fencing, snapshot pinning, mark-and-sweep GC of obsolete checkpoints and unreachable Prolly blocks, zero-copy prefix cloning (cloneToPrefix), shared content-addressed Prolly blocks, and a Cloudflare Durable Objects adapter.

@lionlang/core/logic/calm — analyzeCalm, extractMonotonicDelta, mergeMonotonicDelta

Static CALM monotonicity analysis partitioning coordination-free confluent relations (including lattice-merged keys) from non-monotonic points of order, plus order-independent monotonic delta exchange.

@lionlang/core/logic/spine — LsmSpine, spillRelation, evictSpilledRelations, saveSpineToObjectStore, loadSpineFromObjectStore

Out-of-core paged LSM Z-set relation spine backed by immutable Prolly SST runs, bounded LRU block cache, persistent manifests, lazy paged secondary column indexes, and transparent Datalog integration (direct O(log N + K) indexed query and find lookups without full hydration, plus demand hydration and mutation mirroring).

@lionlang/cli/client — LionClient, LionClientError

Zero-dependency typed HTTP + SSE client SDK for lion serve with lossless wire encoding for exact rationals, automatic OCC retry (commitWithRetry), multi-tenant scoping (.tenant(id)), streaming SSE watch() async iterators, CALM/Prolly sync, and hibernation controls.

@lionlang/core/logic/algorithms

defineAlgorithm({ name, inputs, columns, run })

Returns a function to bind under name. Called in Lion with its inputs and one term per column, it builds a goal over the rows run computes.

  • inputs: a list of { kind: "relation" | "value", name }. A relation input is given as a relation's name or value; a value input as JSON data, or as a logic variable that another goal binds.
  • columns: the output column names.
  • run(inputs): receives each relation input as its list of tuples and each value input as itself. Returns a list of rows, each with one value per column, or a string that explains why it cannot. It runs once for each combination of input values a goal asks about.

@lionlang/core/logic/terms

logicFunction(fn)

Marks a function that takes logic variables as they are, and returns it. Every other function waits when it is called with a logic variable, so mark a function only when it builds a goal from the variables it is given, as a relation does.

new LogicForm(name, parts)

A logic form, held the way it is written: new LogicForm("=", [left, right]) is the goal ["=", left, right] makes, for a logic function to return. The names are "not", "and", "or", "=", "in", "find", and "schema/fits?". A relation call is an Atom, of the same module.

builtBy(fn, by, args)

Records that calling by with args built fn, and returns fn. The function is then written as that call, in messages and snapshots, as the functions that func/partial and the schema module make are.

readsOnlyArguments(bindings)

Marks the functions among the values of a record as reading nothing but their arguments, as every function of the standard library does. Lion cannot see what any other host function reads, so an invariant that calls one is asked in full after every change to facts. Marking a function lets such an invariant be asked only about what a change can have broken.

render(value)

Converts logic values, such as goals and variables, back into the Lion JSON that produces them.

compareValues(a, b)

The value order Lion sorts by: negative, zero, or positive.

@lionlang/core/analysis/analyze

analyze(expression, environment?)

Returns a tree describing each part of a program without evaluating it: its kind, its special form, the role of each child, and what each string means there, read by the scopes a run with environment reads it by. A string's meaning is a name or a binding, each with the binding it means or makes (a parameter, a define, a relation, a schema, or the environment's, with the pointers of the strings that bind it), a logic-variable, data, unbound where only a name can stand and nothing binds one, as at the head of a call, a form's name, or the keyword else. A part that fails when it runs, a malformed form or an unbound name, has a diagnostic: the message of the error the run fails with. The head of a call has none, since it is looked up where the call runs, and code eval ran may have bound it by then. The graph editor is built on it.

const program = [
  "begin",
  ["define", "total", 0],
  [["lambda", ["n"], ["array/make", "n", "total", "?x", "done"]], 1],
];
for (const { pointer, value, meaning } of flattenAnalysis(
  analyze(program, stdlib)
)) {
  if (meaning?.kind === "name" || meaning?.kind === "binding") {
    console.log(pointer, value, meaning.kind, meaning.binding.kind);
  } else if (meaning) {
    console.log(pointer, value, meaning.kind);
  }
}
// /0 begin form
// /1/0 define form
// /1/1 total binding define
// /2/0/0 lambda form
// /2/0/1/0 n binding parameter
// /2/0/2/0 array/make name environment
// /2/0/2/1 n name parameter
// /2/0/2/2 total name define
// /2/0/2/3 ?x logic-variable
// /2/0/2/4 done data
flattenAnalysis(node)

The nodes of an analysis tree, in order.

isSpecialFormName(value)

Whether value names a special or logic form.

@lionlang/core/errors/evaluation

InvalidFunctionCallError, LogicError, and WaitingError, the tagged error classes described in Errors.

Services

LionEnvironmentService (@lionlang/core/services/evaluation) and LionDatabaseService (@lionlang/core/services/database) carry the environment and database through evaluation. run provides both. LionAskerService (@lionlang/core/services/asker) says who answers questions at the moment: evaluation sets it while a rule is being written and while one runs.

@lionlang/typesafe-ai

makeTypeSafeBindings(config?, namespace?)

Returns bindings to spread into an environment: noul, choice, score, system-one, and models, under namespace/, "typesafe" by default. config is the TypeSafe client configuration. See Ask AI models with TypeSafe.

makeTypeSafeModule(config?)

The same functions without a namespace.

Reference · information-oriented

Release examples by version

Runnable examples covering every shipped version of @lionlang/core and @lionlang/cli from 0.1.0 through 0.25.0, statically verified by the docs build.

Every shipped version of @lionlang/core and @lionlang/cli is paired below with a live, runnable example exercising what that release introduced. The docs build and repository policy statically verify that no release version ships without a runnable guide example here.

@lionlang/core 0.25.0, @lionlang/cli 0.24.0 & @lionlang/ui 0.2.0 — SMT forall, PDR, proof/optimize & Public UI Artifacts

Adds quantified forall E-matching (forall-inst certificates) in proof/smt, CTI-guided PDR-lite invariant strengthening (strengthen: true) in proof/invariant, kernel-verified linear & mixed-integer optimization (proof/optimize) with tamper-bound Farkas/Chvátal-Gomory duality verification, lion artifact standalone public HTML export, 36 pure JSON UI primitives in @lionlang/ui 0.2.0 with live SMT models & expandable DPLL(T) lemma cards in ui/proof, and 14 live public proof & Graph-as-Code artifacts.

["begin",
  ["define", "q",
    ["proof/smt", ["quote",
      ["and",
        ["forall", ["x"], ["=", ["inv", ["inv", "x"]], "x"]],
        ["=", ["inv", "a"], "b"],
        ["!=", ["inv", "b"], "a"]]]]],
  ["define", "pdr",
    ["proof/invariant", {
      "vars": {"x": "value/integer?", "y": "value/integer?"},
      "init": ["lambda", ["s"], ["and", ["=", ["object/get", "s", "x"], 0], ["=", ["object/get", "s", "y"], 0]]],
      "next": ["lambda", ["s", "s2"],
        ["and",
          ["=", ["object/get", "s2", "x"], ["number/add", ["object/get", "s", "x"], 1]],
          ["=", ["object/get", "s2", "y"], ["number/add", ["object/get", "s", "y"], ["object/get", "s", "x"]]]]],
      "invariant": ["lambda", ["s"], ["number/greaterThanOrEqualTo", ["object/get", "s", "y"], 0]],
      "strengthen": true
    }]],
  ["define", "opt",
    ["proof/optimize", "min",
      ["number/add", ["number/multiply", 420, "?s"], ["number/multiply", 980, "?m"]],
      ["and",
        ["schema/fits?", "?s", "value/integer?"],
        ["schema/fits?", "?m", "value/integer?"],
        ["number/greaterThanOrEqualTo", "?s", 0],
        ["number/greaterThanOrEqualTo", "?m", 0],
        ["number/greaterThanOrEqualTo", ["number/add", "?s", "?m"], 3],
        ["number/greaterThanOrEqualTo",
          ["number/add", ["number/multiply", 120, "?s"], ["number/multiply", 320, "?m"]],
          700]]]],
  {"forallValid": ["proof/valid?", ["object/get", "q", "proof"]],
   "pdrLemmas": ["object/get", "pdr", "strengthened"],
   "pdrValid": ["proof/valid?", ["object/get", "pdr", "proof"]],
   "optimalCost": ["object/get", "opt", "optimal"],
   "optValid": ["proof/valid?", "opt"]}]
result
{
  "forallValid": true,
  "pdrLemmas": ["x >= 0"],
  "pdrValid": true,
  "optimalCost": 2380,
  "optValid": true
}

@lionlang/core 0.24.0 & @lionlang/cli 0.23.0 — Native DPLL(T) SMT, Arrays, k-Induction & Proof Inspector

Ships native lazy DPLL(T) SMT (proof/smt) combining CDCL SAT, LIA/LRA, polynomial sum-of-squares (sos), EUF congruence closure with bidirectional Nelson-Oppen equality sharing, and McCarthy's Theory of Arrays & Records (select/store, object/get/object/set, kernel-verified array-axiom certificates); automated k-induction in proof/invariant; declarative Lion Datalog join-fanout lint with zero false positives on quoted proofs; the interactive Proof & SMT Inspector in @lionlang/repl; and strict commit-time typecheck, policy, complexity-ceiling, and runnable-docs gates.

["begin",
  ["define", "arr",
    ["proof/smt", ["quote",
      ["and",
        ["=", "b", ["store", "a", "i", 10]],
        ["<=", "i", "j"],
        ["<=", "j", "i"],
        ["<", ["select", "b", "j"], 10]]]]],
  ["define", "sos",
    ["proof/smt", ["quote", ["<", ["+", ["*", "x", "x"], ["*", "y", "y"], 1], 0]]]],
  ["define", "kind",
    ["proof/invariant", {
      "vars": {"a": "value/integer?", "b": "value/integer?"},
      "init": ["lambda", ["s"], ["and", ["=", ["object/get", "s", "a"], 0], ["=", ["object/get", "s", "b"], 0]]],
      "next": ["lambda", ["s", "s2"], ["and", ["=", ["object/get", "s2", "a"], 1], ["=", ["object/get", "s2", "b"], ["object/get", "s", "a"]]]],
      "invariant": ["lambda", ["s"], ["number/greaterThanOrEqualTo", ["object/get", "s", "b"], 0]],
      "k": 3
    }]],
  {"arrValid": ["proof/valid?", ["object/get", "arr", "proof"]],
   "sosValid": ["proof/valid?", ["object/get", "sos", "proof"]],
   "k": ["object/get", "kind", "k"],
   "kValid": ["proof/valid?", ["object/get", "kind", "proof"]]}]
result
{"arrValid":true,"sosValid":true,"k":2,"kValid":true}

@lionlang/core 0.23.0 & @lionlang/cli 0.22.0 — Symbolic provers, governed ontologies, Ossie & spine pushdown

Adds proof/invariant, proof/bmc, proof/simp, proof/sat, proof/liveness, proof/refines, governed relation ontology metadata (description, synonyms, certified, references), declarative join-fanout lint, Apache Ossie export/import, and out-of-core RelationSpine semi-join pushdown.

["begin",
  ["relation", "service", ["id", "tier"], {"key": ["id"], "certified": true, "description": "Production services", "synonyms": ["app"]}],
  ["fact", ["service", "api", "gold"]],
  ["define", "inv",
    ["proof/invariant", {
      "vars": {"x": "value/integer?"},
      "init": ["lambda", ["s"], ["=", ["object/get", "s", "x"], 0]],
      "invariant": ["lambda", ["s"], ["number/greaterThanOrEqualTo", ["object/get", "s", "x"], 0]],
      "next": ["lambda", ["s", "s2"], ["=", ["object/get", "s2", "x"], ["number/add", ["object/get", "s", "x"], 1]]],
      "property": ["lambda", ["s"], ["number/greaterThanOrEqualTo", ["object/get", "s", "x"], 0]]
    }]],
  ["define", "sat", ["proof/sat", ["quote", ["and", "p", ["not", "p"]]]]],
  {"invValid": ["proof/valid?", ["object/get", "inv", "proof"]], "unsatValid": ["proof/valid?", ["object/get", "sat", "proof"]], "services": ["find", "?id", ["service", "?id", "gold"]]}]
result
{"invValid":true,"unsatValid":true,"services":["api"]}

@lionlang/core 0.22.0 & @lionlang/cli 0.21.0 — EUF congruence, lemma chaining, and two-state invariants

Adds Lean 4-style EUF congruence closure, proof/prove with using lemmas, strong remainder induction, and TLA+ two-state action invariants via was.

["begin",
  ["relation", "epoch", ["k", "n"], {"key": ["k"]}],
  ["invariant", ["and", ["was", ["epoch", "?k", "?old"]], ["epoch", "?k", "?new"], ["number/lessThan", "?new", "?old"]], {"assert": "none"}],
  ["fact", ["epoch", "wal", 1]],
  ["fact", ["epoch", "wal", 2]],
  ["define", "lem", ["proof/prove", ["not", ["exists", ["?x"], ["and", ["schema/fits?", "?x", "value/integer?"], ["number/greaterThan", "?x", 0], ["number/lessThan", ["number/add", "?x", 1], 2]]]]]],
  {"epoch": ["find", "?n", ["epoch", "wal", "?n"]], "lemmaValid": ["proof/valid?", "lem"]}]
result
{"epoch":[2],"lemmaValid":true}

@lionlang/core 0.21.0 & @lionlang/cli 0.20.0 — Quorum WAL, CALM sync, Prolly trees & LsmSpine

Introduces monotonic lattice merges for CALM coordination-free sync, Prolly-tree checkpoints, and content-addressed storage primitives.

["begin",
  ["relation", "high_water", ["node", "seq"], {"key": ["node"], "merge": {"seq": "aggregate/max"}}],
  ["fact", ["high_water", "n1", 3], ["high_water", "n1", 7], ["high_water", "n1", 5]],
  ["query", ["high_water", "n1", "?seq"]]]
result
[{"seq":7}]

@lionlang/core 0.20.0 & @lionlang/cli 0.19.0 — Proof kernel, induction, and MCP server

Ships proof/valid?, structural and numeric induction proofs, and the stateful HTTP + MCP runtime.

["begin",
  ["define", "p", ["proof/prove", ["not", ["exists", ["?n"], ["and", ["schema/fits?", "?n", "value/integer?"], ["number/greaterThan", "?n", 5], ["number/lessThan", "?n", 4]]]]]],
  {"proved": ["object/get", "p", "proved"], "valid": ["proof/valid?", "p"]}]
result
{"proved":true,"valid":true}

@lionlang/core 0.16.0–0.19.0 & @lionlang/cli 0.15.0–0.18.0 — Exact rationals, units, solver bounds, and autofix

Brings exact rational arithmetic, dimensional quantities (quantity/*), symbolic solver bounds (proof/bounds), and static RFC 6902 autofix.

["begin",
  ["define", "third", ["number/divide", 1, 3]],
  ["define", "dist", ["quantity/add", ["quote", {"value": 2000, "unit": {"m": 1}}], ["quote", {"value": 500, "unit": {"m": 1}}]]],
  {"exactOne": ["number/equals?", ["number/multiply", "third", 3], 1], "meters": ["object/get", "dist", "value"]}]
result
{"exactOne":true,"meters":2500}

@lionlang/core 0.11.0–0.15.0 & @lionlang/cli 0.10.0–0.14.0 — Explainable provenance, assuming, and existentials

Introduces why provenance trees, counterfactual assuming, existential invention (exists), and goal-directed evaluation.

["begin",
  ["relation", "edge", ["from", "to"]],
  ["relation", "reach", ["from", "to"]],
  ["rule", ["reach", "?a", "?b"], ["edge", "?a", "?b"]],
  ["rule", ["reach", "?a", "?c"], ["edge", "?a", "?b"], ["reach", "?b", "?c"]],
  ["fact", ["edge", "a", "b"]],
  {"whyValid": ["proof/valid?", ["why", ["reach", "a", "b"]]],
   "ifAdded": ["assuming", ["fact", ["edge", "b", "c"]], ["find", "?x", ["reach", "a", "?x"]]]}]
result
{"whyValid":true,"ifAdded":["b","c"]}

@lionlang/core 0.1.0–0.10.0 & @lionlang/cli 0.1.0–0.9.0 — Core JSON Lisp, schemas, match, and Datalog foundations

Establishes the JSON-based Lisp evaluator, lexical closures, pattern matching, schema validation, recursive relations, aggregates, and the lion CLI.

["begin",
  ["relation", "sale", ["dept", "amt"]],
  ["fact", ["sale", "books", 12], ["sale", "books", 18], ["sale", "games", 25]],
  ["relation", "dept_total", ["dept", "sum"]],
  ["rule", ["dept_total", "?d", ["aggregate/sum", "?a"]], ["sale", "?d", "?a"]],
  ["query", ["dept_total", "?dept", "?sum"], {"order": "?dept"}]]
result
[{"dept":"books","sum":30},{"dept":"games","sum":25}]

Explanation · understanding-oriented

Why programs are JSON

What Lion gains by making every program a JSON value, what it costs, and how the evaluation rules make it work.

Most languages have a syntax of their own, and a parser that turns text into a tree the evaluator walks. Lion skips the syntax. A Lion program is already the tree, written as JSON, and the evaluator walks it directly. This page explains why that is worth doing, and what it costs.

Code that other systems can handle

JSON is the one data format almost every system already speaks. Databases store it, HTTP carries it, queues pass it along, and every language can read and write it without a new library. When programs are JSON, all of that infrastructure works on programs too. A rule can live in a database row and be edited by an admin screen. A workflow can arrive in a request body. A diff of a program is a diff of JSON.

It also matters for programs that write programs. A language model, a form builder, or another service can produce a Lion program by producing JSON, and a JSON schema can describe what it may produce. There is no grammar to get wrong and no string escaping to forget.

Code is data, so data can become code

Lisp's old idea is that code and data share one shape, so a program can build and inspect programs with the same tools it uses on any list. Lion inherits this, which is why it is called a Lisp. A program is a list; quote holds one without running it, list functions take it apart and put it together, and eval runs the result. The how-to guide on code as data shows this in practice, and the graph editor relies on it: it edits the JSON tree and nothing else.

How JSON becomes code

Every JSON value has to mean something when evaluated, and Lion's rules are chosen so that the common case needs no ceremony:

  • Numbers, booleans, and null mean themselves, so plain data is a valid program.
  • Records evaluate their values and keep their keys, so a record is both a data structure and a way to return several results at once.
  • Arrays are calls, because calls are the heart of a Lisp, and an array is the only JSON shape with an obvious first element.
  • Strings are the one compromise. JSON has no separate type for names, so a string is a name when something is bound to it and text otherwise.

The full rules are in Evaluation rules.

What it costs

The string compromise is the main cost. A string in your data that happens to match a bound name, such as "number/add", evaluates to that function, and a list in your data is a call. quote is the way out, and the reason snapshots quote such strings when they save a database. Namespacing every library name with a / makes accidental matches rare.

JSON is also more verbose than a syntax designed for people, and it has no comments. Lion leans on tools for this: the graph editor shows the tree with each form labeled and each string read as a name, a logic variable, or data, and records can carry descriptions alongside code. For programs that machines write and people review, the trade is usually worth it.

Why not just use JavaScript?

A host language like JavaScript can do everything Lion can, but its programs are text that must be parsed, and running untrusted JavaScript means trusting it with everything the host can reach. A Lion program can only call what its environment binds. The host decides exactly which functions a program may use, so a program from a database, a user, or a model is as safe as the environment it runs in.

Explanation · understanding-oriented

Names, scope, and environments

How Lion decides which strings are names, why a body declares what it defines from its start, and what lasts from one run to the next.

Every string in a Lion program might be a name. This page explains which strings are names, where they come from, how a lookup finds them, and how long they last.

Environments are chains

An environment is a record of bindings with an optional parent. Looking up a name checks the current environment, then its parent, and so on to the top. A run starts with one top-level environment holding whatever the host gave it, usually the standard library.

Calling a lambda makes a new environment for its parameters whose parent is the environment where the lambda was created, not where it is called. That is lexical scope: a lambda remembers the names around it.

["begin",
  ["define", "counterFrom", ["lambda", ["start"],
    ["lambda", ["step"], ["number/add", "start", "step"]]]],
  ["define", "fromTen", ["counterFrom", 10]],
  ["define", "start", 1000],
  ["fromTen", 5]]
result
15

The global start is 1000, but the inner lambda sees the start it was created with, 10.

A string is a name where a scope declares it

JSON has one kind of string, so Lion decides which strings are names by where they are written, before the program runs. A string that a scope around it declares is a name; any other is data. A scope declares its bindings from its start: the names the host gave the run and the database's relations, the names the program defines anywhere at its top level and the relations and schemas it declares, and, for a lambda, its parameters and the names its body defines. What a string means therefore never depends on the order things run in: a binding made later, by eval for instance, never turns data that code already holds into a name. That holds in the parts of a find, a rule, or any other logic form as in plain code: they are read by the scopes they are written in, whenever the form runs. The first element of an array is the one place a string is always a name, since it names what the array does: one no scope declares is looked up where the call runs, so a relation that eval declared can be asked about after it.

["begin",
  ["relation", "seen", ["x"]],
  ["fact", ["seen", 1]],
  ["eval", ["quote", ["define", "later", 5]]],
  {"plain": "later",
   "find": ["find", "?v", ["=", "?v", "later"]],
   "in eval": ["eval", ["quote", "later"]]}]
result
{"plain":"later","find":["later"],"in eval":5}

Because a body declares what it defines from its start, functions can name each other in any order, which mutual recursion needs:

["begin",
  ["define", "greet", ["lambda", [], ["string/concat", "hello, ", "name"]]],
  ["define", "name", "Ada"],
  ["greet"]]
result
"hello, Ada"

Calling greet before name is defined fails with UndefinedYetError, rather than greeting the string "name".

Since the scopes settle it before anything runs, a tool can read it too. The graph editor shows under every string what it is there: a name, with what binds it (a parameter, a local or top-level define, a relation, a schema, or the environment), a logic variable, or data. Selecting a name marks its binding and every other string that means it, and a string that only a name could be, such as a misspelled module/name, is marked as an error before the program runs. analyze gives hosts the same reading.

define binds in its body; set! changes a binding

define binds in the body it stands in: inside a lambda, the lambda's call, so a helper value inside a function stays inside it, as in Scheme. To change a name around a lambda, such as the state an app's callbacks update, use set!:

["begin",
  ["define", "total", 0],
  ["define", "add", ["lambda", ["n"],
    ["begin",
      ["define", "doubled", ["number/multiply", "n", 2]],
      ["set!", "total", ["number/add", "total", "doubled"]]]]],
  ["add", 1], ["add", 2],
  {"total": "total", "doubled": "doubled"}]
result
{"total":6,"doubled":"doubled"}

doubled is the string outside add, since nothing outside declares it.

Parameters shadow globals, and forms

A parameter with the same name as a global hides the global inside the lambda's body. Because standard library names contain a /, choosing parameter names without one keeps them from shadowing a library function by accident. A parameter or a define may also take a special form's name, such as fact or in: where it is in scope, an array that starts with it is a call, and everywhere else the form.

Strings that name nothing

A string that no scope declares is itself, which is what lets a program write "open" for a status without any quoting. The cost is that a misspelled name would quietly become a string: ["number/ad", 1, 2] would be a call to a string, and "value/intger?" as a schema would be a string that only the same string fits.

So Lion looks at one more thing. A string of the form module/name that reads as a misspelled name is an error. It reads that way when other names of its module are bound, or when a bound name is a letter or two away, which the error then suggests. Any other string with a slash in it, such as "n/a" or "text/plain", is data as before.

["array/map", ["array/make", 1, "two"], "value/numbr?"]
error
UnboundNameError: Nothing is bound to "value/numbr?". Did you mean "value/number?"? To mean the string itself, write ["quote", "value/numbr?"].

A host that adds functions under its own module gets the same check for them: once "shop/stock" is bound, "shop/stok" is an error. Inside quote, a string is always data.

What lasts between runs

Names last for one run. Each run, whether a call to run, one file on the command line, or one example on this page, starts with a fresh environment, so nothing a program defines leaks into the next.

The logic database is different. It is not part of the environment; it is a separate store that a host can pass to several runs, and that the command line keeps in a file. Relations and schemas declared in a shared database are bound by name in every run that uses it, unless the host binds the same name. This split is deliberate: definitions are code, and code is re-run, while facts are state, and state persists.

Functions are Effects

A Lion function returns an Effect, a description of work, rather than a plain value. Evaluation is itself an Effect, so a function can do anything an Effect can, such as wait for a network call or fail with a typed error, and the evaluator composes it with everything else. Host functions may return plain values or Effects; Lion handles both. This is why func/callback exists: it turns a Lion function into an ordinary JavaScript function for APIs that expect one.

Explanation · understanding-oriented

How Lion answers logic questions

Why Lion's logic layer is Datalog rather than Prolog, how it computes answers bottom-up, and where its restrictions come from.

Lion's logic layer lets a program state facts and rules and ask questions, instead of spelling out how to find answers. This page explains the model behind it, and why its rules are what they are.

Goals are values

In most logic languages, rules and queries are a separate syntax. In Lion, calling a relation, such as ["parent", "?p", "eli"], just returns a goal value. Goals can be stored, passed to functions, and combined with and, or, and not, like any other value. A query, rule, or invariant solves them, and so does any expression that needs their answer. This keeps the logic layer inside the language: a lambda can build goals, answers come back as ordinary data, and a relation can be tested like any other condition.

Datalog, not Prolog

Prolog answers a question by searching backward from it, trying rules in order. That is powerful, but a query can run forever, and the answer can depend on the order rules were written in.

Lion follows Datalog instead. Datalog computes forward: it starts from the facts, applies every rule to derive new facts, and repeats until nothing new appears. Because the facts and the values in them are finite, and rules only combine values that already exist, this always stops, and the result does not depend on rule order. The price is expressiveness. Rules cannot make new values without limit, which is why Lion rejects a rule whose new value flows back, through the rules, into making another.

Semi-naive evaluation

Re-applying every rule to every fact in each round would redo the same work again and again. Lion's evaluation is semi-naive: each round only considers matches that use at least one fact that is new since the last round, and starts each join from those new facts. A query along a 3,000-step chain takes milliseconds rather than seconds this way.

Joins through a hub

A rule body is matched one relation goal at a time, and each goal looks its rows up by the values the goals before it bound. That is slow where most rows share one node, a hub. To count the triangles below, the second goal would read every edge out of a hub, about a thousand, for each edge into it, though the third goal then keeps only the few that lead back to where the first edge started.

So a goal can read its rows through a later relation goal that holds every variable it binds, when that goal has fewer rows for the answer: here, the edges into the node the first goal started from. Lion picks for each answer whichever of them has fewer rows, the cover of a worst-case optimal join such as Free Join, so a join through a hub reads the rows the other goals allow instead of every path through it. It changes what an answer costs, never which answers come or their order. Only relation goals may stand between the two: a filter between them still runs on every answer of the goals before it.

["begin",
  ["relation", "edge", ["from", "to"]],
  ["rule", ["edge", "?n", ["number/add", "?n", 1]], ["in", "?n", ["array/range", 2, 1000]]],
  ["rule", ["edge", "?n", "?hub"], ["in", "?n", ["array/range", 2, 1001]], ["in", "?hub", ["quote", [0, 1]]]],
  ["rule", ["edge", "?hub", "?n"], ["in", "?n", ["array/range", 2, 1001]], ["in", "?hub", ["quote", [0, 1]]]],
  {"edges": ["array/length", ["query", ["edge", "?a", "?b"]]],
   "triangles": ["aggregate/count", ["find", 1, ["and", ["edge", "?a", "?b"], ["edge", "?b", "?c"], ["edge", "?c", "?a"]]]]}]
result
{"edges":4994,"triangles":5988}

Stratification

A question needs a complete picture. "Customers with no orders" is only right once every order is known, and so is a total, a list of what a goal matches, or the plain fact that it matches anything. Lion therefore groups relations into strata, ordered by what depends on what, and derives a relation fully before any rule that asks about it or aggregates it. It does so the first time something reads the relation, and keeps the rows until a fact or rule changes. A rule that asks about a relation that depends on its own head has no correct stratum, so such a rule is rejected when added.

Lattice aggregates are the exception. min, max, shortest, and union only move one way as values arrive: a minimum only gets smaller. A partial result is never wrong, only not yet final, so these may aggregate through recursion. That is how a rule can compute shortest distances, and why a negative-weight cycle, where a distance would shrink forever, is stopped after 10,000 rounds.

Saying that something exists

Plain Datalog cannot say "every person has a mother" without naming her. Datalog± is the research name for Datalog with rules whose heads say that something exists, and a Lion rule whose head is exists is one. When its head does not hold, the rule invents a value for it. The research calls such a value a labeled null. Lion calls it an unknown, and writes it the way Hilbert's epsilon names "some x such that": ["some", "?m", ["mother", "ben", "?m"]] is some ?m such that ben's mother is ?m. Written this way, an unknown is ordinary data that means the same in every run, so a fact can mention it, a snapshot can save it, and running a program again invents the same one.

Running such rules is called the chase. Lion's is the restricted chase: a rule invents only for an answer whose head does not hold already, so a person with a known mother gets no unknown one. It runs Datalog-first: rules that invent wait until every rule that invents nothing has finished, so a mother that the rules can find is found before one is invented. And it runs in parallel: every rule that invents does so at once, on the same rows, so the result does not depend on the order rules were added in.

The chase can run forever. If every mother is a person and every person has a mother, each mother invented needs a mother of her own. Lion refuses such a program with a check called weak acyclicity. Values flow from the columns a rule's body reads to the columns of its head, and a program may make new values, by computing or inventing them, as long as no new value flows back into making another. The same check covers computed values, and accepts every program the older rule, that no recursive rule could compute a value in its head, accepted.

Whatever needs a value waits

A rule body mixes relation goals with filters such as ["number/greaterThan", "?amount", 50]. When Lion evaluates that call, ?amount has no value yet. So the call does not run: it becomes a value that stands for the call, and the engine runs it once for each answer that binds ?amount. The engine plans the body so each filter runs as soon as its variables are bound, which is why goals may be written in any order, and why a filter whose variables are never bound is an error rather than a silent miss.

The same one rule covers everything else that needs a value. Any function waits, whether it comes from the standard library or the host. A cond waits when its condition is not known, a match when its value is not, a begin when an expression before its last is not, and a record when one of its values is not. Each of them is written back out, in a snapshot or an explanation, as the form it was. And each computes exactly what it would compute with the value in place of the variable, so there is nothing new to learn about how an expression behaves inside a rule.

Only the things that build logic do not wait: relations, aggregates, and graph algorithms take a variable as it is and make a goal of it. A lambda's body runs right away for the same reason, so a lambda can build goals, while whatever inside it needs a value waits.

Whatever needs an answer asks

The waiting rule lets ordinary expressions live inside rules. Its mirror image lets rules live inside ordinary expressions. A goal with a relation in it is a question, and whatever needs its value asks it: a cond condition, a function argument, not, or find, which returns what the goal matches as a list. In plain code the question is asked as soon as something needs its value, and a program whose value is a goal gives the goal as written. Inside a rule it waits like everything else, and is asked once for each answer, with that answer's values in place.

The two rules meet without a seam. A question sees the variables its surroundings have bound, and owns the rest, so the same find means the same thing at the top of a program and deep inside a rule. That is also what makes it safe to move code into a lambda: a lambda that asks gives the same answers wherever it is called.

Explanations come free

Because evaluation derives each fact from specific earlier facts, Lion can say which rule produced a fact, and for which answer of the rule's body. why finds that answer when it is asked, the same one whatever order the facts came in, and gives it as a tree of the facts and tests the answer rested on.

When rules are not enough

Some questions are awkward or slow as rules, such as PageRank or Dijkstra's shortest paths. Rather than force them into rules, Lion lets algorithms be goals. A graph algorithm runs once its input relation is complete and contributes rows like a relation, so its answers can feed rules, negation, and aggregates. See Answer graph questions.

Explanation · understanding-oriented

Goal-directed evaluation

How Lion avoids deriving everything a program implies when a query only needs a little, and why the shape of a recursive rule matters.

Bottom-up evaluation derives every fact a program implies. Usually a query needs far less: asking for the paths from one node does not need the paths from every other node. This page explains how Lion narrows the work, and what that means for how you write rules.

Passing the question down

When a query gives a rule-defined relation a known argument, as "a" in ["path", "a", "?to"], Lion rewrites the rules before evaluating them, using a technique called magic sets. Each relation gets a copy specialized to which of its arguments are known, and extra rules pass those known values down through the rule bodies. Evaluation then only derives facts the query can reach. A query along a 3,000-node chain that would derive about 4.5 million paths in full returns its three answers in milliseconds.

An argument is known when it is a value, a variable the query has already bound with a relation, =, or in, or a value computed from such variables, as in ["path", ["number/add", "?s", 1], "?to"]. Inside a rule, only values and variables bound from facts count, so the rewritten rules never ask about values without end.

The rewrite changes how much is computed, never what the answers are. Lion still evaluates bottom-up; it just starts from the question's own values.

Why the shape of a rule matters

The rewrite passes known values from left to right through a rule's body. Compare two ways of writing paths from a known start:

  • Recursion first: ["path", "?x", "?z"], ["path", "?x", "?y"], ["edge", "?y", "?z"]. The known start ?x passes straight into the recursive call, so every step asks about the same start.
  • Edge first: ["path", "?x", "?z"], ["edge", "?x", "?y"], ["path", "?y", "?z"]. The recursive call asks about ?y, each node along the way, so the question spreads to every reachable node, which can cost as much as computing everything.

Both give the same answers. With a known start, write the recursion first; with a known end, put it last. Follow relationships of any length shows both.

Where a known value helps

A rule uses a known argument best when it can look rows up by it: when the argument stands whole in one of the rule's relation goals, as ?x does in ["edge", "?x", "?y"]. Then the rewritten rule reads only the rows for the values asked about. When the rule can only test the argument, because it sits inside a record pattern or a schema such as ["schema/open", {"topic": "?t"}], or in an in, the rule runs as written and keeps the rows asked about, so it never does more than the rule itself would.

What is computed in full, and shared

Some relations cannot be narrowed safely. A relation that is aggregated, computed by a graph algorithm, asked about, under not, in a find, or as a value, or that rules invent rows of, needs its complete contents to be right, so Lion derives it, and everything it depends on, in full. So does a goal that knows none of its arguments: a copy for it would hold every row anyway. Explanations from why also use full evaluation, so they describe the program as written.

What Lion derives in full it derives once, in the database, and keeps. Every later query reads it there, and a query that knows an argument of a relation the database already holds in full looks the rows up instead of deriving a copy. So a page that asks many different questions of one model derives each relation about once, as full evaluation would, and each question pays only for what it alone asks.

A relation is derived the first time a goal reads it, so a query never pays for relations it does not reach. Here the query asks only for listed teams, so the rule for big ones never gets past its first goal, big is never derived, and the amount that is not a number never matters, though ["big", "?u"] knows none of its arguments:

["begin",
  ["relation", "spend", ["team", "amount"]],
  ["relation", "team", ["name"]],
  ["relation", "big", ["team"]],
  ["relation", "flag", ["kind", "team"]],
  ["fact", ["spend", "web", 500], ["spend", "ops", "lots"]],
  ["fact", ["team", "web"], ["team", "ops"]],
  ["rule", ["big", "?t"], ["spend", "?t", "?a"], ["number/greaterThan", "?a", 100]],
  ["rule", ["flag", "big", "?t"], ["big", "?u"], ["team", "?t"]],
  ["rule", ["flag", "listed", "?t"], ["team", "?t"]],
  ["query", ["flag", "listed", "?t"], {"order": "t"}]]
result
[{"t":"ops"},{"t":"web"}]

Deriving flag in full, as ["flag", "?kind", "?t"] would, runs every rule and fails on "lots". The same holds in full evaluation: with ["rule", ["report", "?t"], ["audit", "?t"], ["broken", "?t"]] and no audit rows, broken is never derived.

When facts change

What Lion has derived it keeps when facts change, and brings up to date with the change. Every derived row has a weight: the number of its candidates, each a fact or an answer of a rule's body that gives the row, and the row holds while its weight is above zero. A change takes away the candidates that used a row a relation lost and adds the ones that use a row a relation gained, so it costs what it reaches, not what the database holds. An answer uses a row that a relation goal matched, wherever the goal stands in the rule: in its body, under not, where the row is why the answer is not one, in a find, in a goal used as a value, or in its head. An aggregate keeps the values of its candidates counted: a count, and a sum or a mean of whole numbers, change by one candidate, and every other aggregate combines the values that are left.

Rows that give each other cannot hold each other up. A candidate has a level, one above the highest level of the rows of its own group that its answer used, and a row is held from the least level of its candidates. Whether a row holds has many solutions when rows give each other, and the level it is held from has one, so a change is settled level by level, lowest first: a row whose first candidate is gone holds only where a candidate that rests on lower levels still gives it. Deriving from nothing is the same work, for a change that adds every fact.

Here the first query derives every team's total and which teams have no spending. The new fact reaches one group of total and one row of idle, and the retract reaches one of each again:

["begin",
  ["relation", "team", ["name"]],
  ["relation", "spend", ["team", "amount"]],
  ["relation", "total", ["team", "amount"]],
  ["relation", "idle", ["team"]],
  ["fact", ["team", "web"], ["team", "ops"], ["team", "lab"]],
  ["fact", ["spend", "web", 500], ["spend", "web", 20], ["spend", "ops", 70]],
  ["rule", ["total", "?t", ["aggregate/sum", "?a"]], ["spend", "?t", "?a"]],
  ["rule", ["idle", "?t"], ["team", "?t"], ["not", ["spend", "?t", "?_"]]],
  ["define", "now", ["lambda", [],
    {"totals": ["query", ["total", "?team", "?amount"], {"order": "team"}],
     "idle": ["find", "?t", ["idle", "?t"]]}]],
  {"first": ["now"],
   "added": ["begin", ["fact", ["spend", "lab", 5]], ["now"]],
   "retracted": ["begin", ["retract", ["spend", "ops", 70]], ["now"]]}]
result
{
  "first": {
    "totals": [{"team":"ops","amount":70},{"team":"web","amount":520}],
    "idle": ["lab"]
  },
  "added": {
    "totals": [
      {"team":"lab","amount":5},
      {"team":"ops","amount":70},
      {"team":"web","amount":520}
    ],
    "idle": []
  },
  "retracted": {
    "totals": [{"team":"lab","amount":5},{"team":"web","amount":520}],
    "idle": ["ops"]
  }
}

The answers are what a database that had derived nothing would give; only the order answers are found in can differ, which is one more reason to sort with "order" when order matters. A rule that invents, a key, and an equality rule are followed the same way, whatever the rule's goals look like. The answers of a rule that invents are counted as rows are, and each is asked, at the end of the stage it is first held in, whether a row held by then gives its head. Two values that a key or an equality rule makes one are a pair with candidates of its own: a row that holds a value its class no longer writes ends at the level the pair is held from, and is kept beside the row it became, so taking away the fact that made two unknowns one gives back the rows that held them apart. A row that comes beside a row with its key is read from the level after, when the pair has made the two one, so no rule finds two rows with one key, not even a rule of the group that derives them. why finds the answer that gives a row when it is asked, from the level the row is held from, so a change keeps no explanations and works none out; where a key or an equality rule made values one, it derives the group's answers again once after a change. Two kinds of relation cannot be followed row by row: one whose rule holds a function from the host that does not say it reads only its arguments, and one whose rule reads a changed relation through a schema instead of a relation goal. Lion derives such a relation again and compares it with what it was, so the relations that read it are still followed. It does so when something has read the relation since the last change; otherwise nobody is waiting for it, and it is forgotten until something reads it.

A new rule is followed the same way: the relations whose rules changed are derived again and compared, and the others keep their rows. A change an invariant refuses is followed back, so what was derived before it is still there, also when following it found two rows with one key that the key cannot make one. Such rows are kept as they are, and a question that reads them fails at once with what a database that derived nothing would say. A query that knows an argument keeps what it derived and follows changes too.

Turning it off

A host can create a database with new LogicDatabase({ goalDirected: false }) to derive every row of the relations a query reads. This is useful for comparing results; Lion's own tests check that both ways agree.

Explanation · understanding-oriented

One set of rules for every feature

Why Lion's features share the same few rules, how that follows from the principle of least astonishment, and how Lion settles the places where JavaScript and JSON disagree.

Lion is small, and its value comes from features that combine: a query option inside an invariant, a graph algorithm under not, a snapshot run by the command line. Features only combine well if they agree on the basics. This page explains the rules they share, and the principle behind them.

The principle of least astonishment

A feature should do what someone who already knows Lion expects, both on its own and next to every other feature. In practice that means reusing what exists before inventing more, and when a feature needs a rule, following the rule a similar feature already has. A user who learns one rule then knows how every feature behaves.

Reuse before invention

Invariants are the clearest example. Lion already had a way to say "this question must have no answers": the query option "assert": "none". An invariant is that same assertion, kept by the database. It takes the same option, compiles its goal like a query, is answered by the same engine, and fails with the same words. There is no second vocabulary to learn, and anything a query can ask, an invariant can require.

Changes are all or nothing

Every form that changes the database, fact, retract, or rule, either completes or changes nothing. This one rule answers many questions at once. What happens to the facts before a bad one in a retract? Nothing, because the form fails as a whole. What does a broken invariant leave behind? Nothing, because the change is undone, down to the order facts come back in. What if checking an invariant itself fails? The same: the change is undone.

The unit of change is one form, not one run. That keeps the rule simple and lets several facts that only make sense together go in a single fact form, while each later form is checked against the result.

Adding what is held changes nothing

Facts are a set, so adding a fact twice changes nothing; declaring a relation twice the same way changes nothing. Rules and invariants follow the same rule: adding one the database already holds, one a snapshot would write the same way, changes nothing. Before this was true for rules, running a setup program twice against a saved database added each rule again, and aggregates silently counted every match twice. One rule for every kind of definition removed that whole class of surprise.

One rule for everything that waits

Inside a rule or query, a logic variable has no value yet. Lion has one answer to that everywhere: whatever needs the value waits until the variable is bound, and then computes what it would compute with the value in its place. That holds for a standard function and a host function, for cond, match, and eval, for a record, and for a lambda passed to array/map. No function has to be marked for it, and no form behaves differently inside a rule than outside.

The forms that test truth follow one rule too. and, or, and not accept only true, false, and goals, and so does a filter: a filter that gives a number is an error, not a guess at what the number means. and and or stop at the first argument that decides them, as booleans and as goals.

One rule for every question

A goal is a question, and Lion has one answer to "who may ask it": anything. A rule or query asks a goal for its matches. not asks whether it has none. A cond condition, a function argument, or a value of a record asks whether it has any. find asks for all of them, as a list. There is no separate way to "call the database" from an expression, and no place where a relation call is refused.

Wherever a question is asked, the same thing happens to its variables: the ones the surroundings have bound keep their values, and the rest belong to the question. In plain code nothing is bound, so the question is asked as it stands. In a rule, it is asked once for each answer of the rule. That one rule replaced three special ones. not no longer has its own restriction on variables. A relation works as a predicate without being marked as one. And an aggregate needs no second meaning to be used in a query or to count zero: it combines the list that find gives it.

One limit follows from asking: a rule cannot ask a value-returning question—such as a find, a goal used as a value, why, or assuming—about a relation that depends on the rule's own head, because the answer would not be settled when the rule needs it. Pure negative goals (not) in plain Datalog rules are the one exception: Lion gives them their unique three-valued well-founded model via alternating fixpoint.

One rule for what fits

Checking data is usually a second language beside the first: a schema library at the edge of a program, with its own types, its own combinators, and its own errors. Lion has no second language. A schema is anything a value can fit, and one rule says what fits: a function is a predicate, a record or list fits part by part, and any other value fits a value equal to it. match already chose its branches this way, so its patterns and schemas are the same thing. Data is then a schema for itself, since a value with no function in it fits exactly the values equal to it.

The other rules then do the rest. A schema check is a call, so it waits for logic variables, and a rule can use it as a goal with nothing added. A logic variable in a schema is the value it meets, so the schema that checks a record is the pattern that takes it apart, and a relation call is a schema for a row: each argument says what its column must be. A relation is a predicate, so a relation is a schema, and as the schema of a column it is a foreign key. The schema of a relation's rows is an invariant, written in the vocabulary invariants already have, so it is all or nothing, reported in the same words, and saved by a snapshot like any other.

Equivalent programs behave the same

A snapshot is a program that rebuilds the database, so loading one must give the same answers, and saving again must give the same program. Goal-directed and full evaluation must give the same answers. A name and the value bound to it are the same inside a rule, because rules hold values as evaluated; that goes for a function as much as for a number. An expression over a logic variable must give what it gives with the value in the variable's place, and that includes every question the expression asks. What a database has already derived must never change an answer. A schema fits the same values under its name, and a relation's schema keeps exactly what the invariant it stands for keeps. Each of these is tested as a property over generated programs, so a change that breaks one fails the test suite.

Where JavaScript and JSON disagree

Lion runs on JavaScript, but its values are JSON, and the two disagree in a few places. Each time, Lion follows JSON, and applies the choice everywhere it comes up:

  • Numbers are exact. JavaScript's numbers are doubles, which round: 0.1 + 0.2 is 0.30000000000000004, and 9007199254740991 + 2 is 9007199254740992. A JSON number is decimal digits, of any size and precision. So a Lion number is the exact value its digits write, and arithmetic is exact, as Scheme's exact numbers are: 0.1 + 0.2 is 0.3, an integer of any size is itself, and 1 ÷ 3 is the fraction one third. That is also why what the solver proves about numbers holds of plain code: both work with the same exact numbers. JSON cannot hold a fraction no decimal writes, so writing one as JSON fails with ArithmeticError, and a snapshot writes it as the division that makes it.
  • Numbers are finite. JavaScript has Infinity and NaN; JSON does not. So arithmetic with no result, such as dividing by zero, fails with ArithmeticError rather than producing a value that cannot be printed, stored as a fact, or saved in a snapshot. Exact numbers never overflow.
  • Nothing is null. JavaScript has both undefined and null; JSON only has null. So every "there is nothing here" answer is null: the mean of no values, a cond with no match. Where nothing is there to give, a function fails instead of giving a null that could be a value: object/get of a key a record does not have, unless it is given a value for that, and array/head of an empty list.
  • Records and lists are different kinds. To JavaScript's typeof, a list is an object; to JSON, it is not. So value/object? is true for records and not for lists, and value/array? is the test for lists.
  • Keys belong to objects; methods belong to any value. Reading a key needs an object, so object/get and paths pass only through objects. But a string has methods, as JavaScript's "lion".toUpperCase() shows, so every method function works on any value except null.

One difference remains by design: without the "order" query option, the order of a query's answers is deterministic for a given program and version of Lion, but not part of the language. Sort when order matters. A find returns a value that rules can store, so its list is always sorted.

Explanation · understanding-oriented

How Lion's proof kernel and solvers fit together

Why Lion separates untrusted search procedures (DPLL(T), LRAT SAT, IC3/PDR, Büchi LTL, symbolic refinement) from a small trusted proof kernel (proof/valid?) that replays self-certifying JSON proofs.

Formal verification tools usually force a choice: either trust a large, fast automated solver (like an SMT solver or explicit-state model checker) with no independently checkable output, or write detailed interactive proof scripts checked by a tiny type-theoretic kernel (like Lean 4).

Lion follows the de Bruijn criterion inside a JSON Lisp: every search procedure — linear Fourier-Motzkin / Pugh's Omega, CDCL SAT, DPLL(T), EUF congruence closure, IC3/PDR with Farkas interpolation, Generalized Büchi LTL, term rewriting, and symbolic refinement — is treated as untrusted. Its job is to search for either a concrete counterexample or a compact, self-contained JSON certificate. Only proof/valid? is trusted.

Why certificates are plain JSON

Because every Lion program and value is valid JSON, a proof certificate is an ordinary data value that can be stored in a database, transmitted over HTTP, signed with Ed25519 (ProofEnvelope), inspected interactively with ui/proof, and re-verified in a browser Web Worker without running the solver again.

  • Linear & mixed-integer arithmetic (proof/prove, proof/bounds, proof/optimize): Farkas linear combinations, Chvátal-Gomory integer rounding, and Omega dichotomy split trees checked with exact rational arithmetic.
  • Boolean & bit-vector SAT (proof/sat, proof/smt): 1-UIP CDCL with two-watched-literals, VSIDS, and Luby restarts emits RUP/LRAT-hinted certificates checked by linear-time reverse unit propagation.
  • Combined theories (proof/smt): Lazy DPLL(T) binds theory lemmas (LIA/LRA, polynomial sum-of-squares, EUF congruence with verified rewrite replay, McCarthy arrays with extensionality, bit-vectors, ADTs, and E-graph-modulo forall E-matching) to an explicit atom table and axiom list.
  • Temporal & state-machine proofs (proof/invariant, proof/bmc, proof/liveness, proof/refines, proof/trace): Inductive invariants, k-induction, IC3/PDR-strengthened invariants, symbolic ranking variants, symbolic/finite stuttering refinement, and Generalized Büchi LTL each emit structured certificates that bind their phases together and reject tampered claims.

Why symmetry is restricted to safety

TLC established a subtle soundness boundary: quotienting reachable states by a symmetry canonicalizer preserves safety invariants (every concrete bad state maps to a canonical bad state), but can collapse distinct states along an infinite cycle and hide a fair lasso counterexample. Lion enforces this rule directly: proof/liveness accepts symmetry for safety-only invariant checks and rejects combining symmetry with temporal liveness (p/q or formula).

De Bruijn Criterion in JSON

Untrusted solvers search (CDCL, DPLL(T), PDR, Büchi LTL, simp); only the small proof/valid? kernel is trusted to verify certificates.
LayerEngineCertificate KindKernel Check
Propositional & BV2WL + VSIDS + Luby CDCLrup (LRAT hints)Linear-time hinted RUP replay
Combined TheoriesLazy DPLL(T) + Nelson-Oppendpll-t + atoms/axiomsAtom-bound theory lemma + RUP verification
Algebraic RewritingConditional proof/simp & proof/calcrewrite / rewrite-eq / calcExact path/substitution + chain continuity replay
Unbounded Safetyproof/invariant + k-induction + IC3/PDRinductive-invariant / k-inductionClaim-bound initiation, per-action consecution, safety, actionProperty
Temporal & RefinementGeneralized Büchi LTL, ranking variant, symbolic refinesliveness / ltl / symbolic-liveness / refinement / traceIndependent SCC fair-cycle, simulation, or SMT replay