Entity / foldkit-entity
States of a row, and what every write does to them
An invariant says what every row holds. A row also passes through states a
reader names (a draft, a published product), and a write makes sense from some
and leads to others. Entity.refine names one, as a value: a predicate over
the row, declared once on the Entity (every descriptor of it lists it, as it
judges its invariants). It is not another descriptor: a store, a compiler or a
guard given Draft where it wants Product would read every product.
const Product = Entity.define(
'Product',
Schema.Struct({
id: Schema.String,
status: Schema.Literals(['draft', 'published', 'archived']),
stock: Schema.Number,
}),
)
const Draft = Entity.refine(Product, 'Draft', { status: 'draft' }) // a value per field
const Published = Entity.refine(Product, 'Published', { status: 'published' })
const InStock = Entity.refine(Product, 'InStock', ({ row }) => Expr.gt(row.stock, 0)) // any predicate
const drafts = Query.from(Draft) // every product in the state: its predicate in `where`
Expr.show(Draft.predicate) // 'Product.Draft'
Entity.inState(Draft, { status: 'draft' }) // Option.some(true); none for a row without `status`- The literal form is one
Expr.eqper key (Expr.isNullfor anull), each typed by what its field stores: a key that is no field, or a value the field cannot hold, does not compile. Itsis(row)is a type guard narrowing the fields it names (row.statusis'draft'insideif (Draft.is(row))); the predicate form's narrows nothing. A Selection is never narrowed by state: a held row is updated in place, and goes on being read after it left the state. buildis givenrowalone, so a state cannot read the past: "was ever published" is a field.- A state may reach another row (
Expr.path,Expr.exists). It is queried as any predicate is, but it is notlocal:inStateandiscannot judge it from one row, and it is no write'sfromorbecomes, since a writer judges the row it writes alone.
A write says which state it starts from and which it leaves:
const Publish = Write.update(
Entity.input(Product, Schema.Struct({ id: Schema.String, status: Schema.Literal('published') })),
{ id: 'id', from: Draft, becomes: Published },
)from: Draftjoins the state's predicate to the write'swhen, so a row in another state is refused as unmet, as anywhenrefuses, and the write is aConditionedWrite.becomes: Publishedclaims every row the write can start from is published once it lands. It is decided where the write is declared, by enumerating those rows: a claim the patch cannot keep throws there, naming a row it breaks. A claim enumeration cannot decide (a salebecomes: InStockmoves a number) is the write's postcondition,ensures: an invariant of that write alone, idbecomes:InStock, which each writer judges where the write commits and refuses asInvalid.Write.ensured(Sell.write)is that invariant, forRefusal.isInvalidBy;Laws.checkreports the arrowenforced.
Checking every write: Laws.check
Laws.check judges each write against each invariant of its Entity, and
reports the arrows the writes make between its states. It is pure, needs no
database, and reads declarations only:
const report = Laws.check({ writes: [Rename, Publish, Revert, Sell] })
Laws.show(report)For the writes example, whose domain has a reservedWithinStock state
invariant, a publishedStaysPublished transition invariant and an Archived
state that the snippet above does not, it prints lines such as these (abridged;
examples/writes/LAWS.md
keeps the whole report, so a write added changes a checked-in file):
Product
Draft -> Published Publish holds
Published -> Draft Revert refused by publishedStaysPublished
before status: "published"
input status: "draft"
after status: "draft"
Archived -> Draft Revert undeclared
Archived unreached
Rename x reservedWithinStock kept: writes no member it reads
Restock x reservedWithinStock refused: Reserved stock cannot exceed the stock
before reserved: 0, stock: 0
input quantity: -1
after reserved: 0, stock: -1
1 entity, 4 states, 5 writes, 2 rules: 11 pairs, 7 kept, 4 refused, 0 undecidedA refusal prints its witness under it: the row before (none for a create),
the input, and the row after, over the members the rule and the write read,
the smallest the check found. The last line is what the report stands on.
Here nothing bounds Restock's quantity, so a negative one breaks the rule;
Schema.Number.check(Schema.isGreaterThanOrEqualTo(0)) on the input keeps it.
One write against one invariant comes to one of three verdicts, by the first of these that decides it:
| Case | Verdict |
|---|---|
| State invariant; write changes none of its fields | Kept, by disjointness |
| Finite fields set directly by the write | Enumerated: Kept, or Refused with witness |
| Rule holds vacuously for non-enumerable fields | Kept, vacuous |
| Bounded numbers decide the inequality | Kept, bounds; or Refused with witness |
| Unbounded text, links, or > 4,096 combinations | Undecided, with reason and obligation |
A transition invariant is never kept by disjointness: after.count >
before.count is broken by every write that leaves count alone. Rows are not
filtered by the invariants before enumeration, since a row may be invalid
before a write; a row the write's when (and from) definitely refuses is
dropped, and one it cannot judge stays.
Numbers, by their bounds
A number member or input key the check cannot enumerate gets an interval:
its Schema's checks (isGreaterThanOrEqualTo, isBetween, Schema.Int…),
narrowed by the write's from and when where they compare it with a value,
and by the Entity's state invariants, assumed to hold of the row before the
write. That assumption is what makes the proof inductive: a write that keeps a
rule from every row the rules allow keeps it on every row the writes make,
starting from rows that held it. The write's effect is carried through the
intervals (a set, an increment, a compute through operators that declare
Law.monotonic for each argument), and the rule is judged over the result in
SQL's three values. Kept by bounds holds for every row and input within
those bounds.
It is deliberately non-relational: a when comparing two unknowns
(amount <= balance) narrows each only by the other's interval, so it keeps
nothing on its own, and the pair is Undecided: "it rests on comparing
balance with amount". A refusal is never inferred from intervals: the check
tries the values nearest 0 and at each interval's ends, and refuses only with
a row and input the reference judge refuses, within every Schema, meeting the
when, and keeping every state invariant they hold the members of. The
numbers are the judge's (JavaScript's, rounding monotone); a store that rounds
otherwise is outside what it proves.
An Undecided pair of a declared write carries an obligation: the write,
the rule, the state invariants assumed before it and the cases (values
of the finite members) left, all as declared, for a later pass, such as a
solver, to prove without reading the source again.
The findings (holds, enforced, undeclared, refused, unmeetable,
unreached, terminal) are reports, never faults: a write an invariant can
refuse is legitimate. enforced (* -> InStock Sell enforced) is a
becomes held by its postcondition where the write commits, and that
postcondition is a pair of the write alone (Sell x becomes:InStock).
unmeetable is a write whose from and when no row the state invariants
allow can meet. A refusal whose witness starts in states no write reaches
carries a hint saying so: an invariant ruling those states out would settle
the pair.
A transition that is no declared write (another package's command, an
import) is an entry with a Footprint: what its author says it writes, or
Footprint.unknown, which writes every member and is Undecided against
every invariant:
Laws.check({
writes: [
{ name: 'Touch', entity: Product, footprint: Footprint.declared({ writes: [Product.fields.name], by: 'the import' }) },
{ name: 'Import', entity: Product, footprint: Footprint.unknown },
],
})A declared footprint names fields by reference, so one of another Entity is a
type error where the entry names its Entity. It keeps a state invariant only
by disjointness, and decides no transition invariant. Write.footprint(write)
is a declared write's own.
Evidence, and the graph's facts
A pair the check keeps by reading the declarations carries a record in
evidence, issued by foldkit-entity/laws: Bounded for one the numbers'
bounds decided, Enumerated for the rest (by disjointness, by enumeration,
vacuous, a create against a transition invariant, a delete). A pair
kept on its author's word (declared), refused or undecided carries none:
for those, the evidence is a walk through the writer, a scenario, or
Evidence.runtimeOnly with its reason. These records are
foldkit-metadata's Evidence; the Evidence this package exports is an
operator law's (Tested, Proven, below).
import { Option } from 'effect'
import { lawFactsOf } from 'foldkit-entity'
import { Evidence } from 'foldkit-metadata'
const records = report.pairs.flatMap(pair => Option.toArray(pair.evidence))
records.map(Evidence.issuedBy) // some('foldkit-entity/laws') for each kept pair
Laws.transition(Rename) // 'write:Rename'
const { nodes, edges } = Laws.facts(report)
lawFactsOf([Rename]) // the same shape, read off the declarations, with no check runRecords and the graph name a transition write:<name> (Laws.transition)
and a law <Entity>.<id> (Laws.law(invariant)), so Laws.check throws for
two entries of one name. lawId and transitionId are the same two
functions by name, in a module of their own, for code that must not carry the
check.
Laws.facts(report) is the law half of foldkit-surface's graph as plain
data in that graph's own shape (GraphFacts), since this package does not
import Surface: a Law per invariant, a Transition per write in a pair or an
arrow, a State per local state, Reads and Writes over space: 'entity'
paths such as ['Product', 'stock'], From and To per arrow, and a Keeps
edge per transition and law whose every pair carries a record. A write's own
ensures is marked postcondition on its pair and is no law of the Entity,
so the facts leave it out; an Unknown footprint writes every member, so it
has a Writes edge to each member a law of its Entity reads. A transition
invariant (pair.readsBefore) also reads its whole row (['Product']), since
a write leaving every member it reads alone can still break it.
lawFactsOf(entries) gives the same shape from Laws.check's entries without
judging them, so not the same facts: a State for every state, local or not,
From and To from each write's declared from and becomes, a Writes
edge to every field for an Unknown footprint, and no Keeps. It is what Surface's Graph.of derives a contract's
laws.entities with (a Remote domain declares its writes there), so only a
page that asks for the graph carries it, and never the check.