Chapter 11

Bringing λProlog to (aux kanren micro): the design

What and why

Chapter 10 ended with a precise list of what an importing module cannot obtain from (aux kanren micro) today: a named place in the state for its own data, a call after every binding (to check the scope of eigenvariables eagerly and to wake postponed equations), and a say in reification (to print new constraints and to hide what must not escape). The three tricks of Section 10.9.2 show that augment and generic fit the shape of a μKanren goal; they do not make them sound under every goal of the engine, nor cheap.

This chapter turns that observation into a design. It proceeds in four steps.

  1. Requirements (Section 11.1). The nine acceptance items A1–A9 against which the proposal was built and tested, stated as properties of a run of °->list.
  2. The design space (Section 11.2). The four meanings of unification on λ-terms compared in Section 9.8, and why higher-order pattern unification with universe levels is the one retained.
  3. Three prototypes (Section 11.3). Three complete implementations of the same requirements, which differ in where the code sits with respect to (aux kanren micro): a layer that does not touch the engine, a small generic protocol in the engine, and a native engine. They were compared by three reviews (engineering, fidelity to the book, pedagogy); the protocol won.
  4. The extension protocol (Section 11.4). The edit to (aux kanren micro) in full, as merged into master by commit 26b4708: the state’s slot X, the registry, every hook with its contract and call site, the primitives exported for the hooks, the invariants a client must keep, and where it differs from the prototype’s micro.diff.

The chapter closes with what the edit costs a first-order program (Section 11.4.10) and with the history of the review rounds that hardened the proposal (Section 11.5). The λ layer that sits on the protocol, (aux kanren lambda), with its unifier, its ∀° and ⊃° and its treatment of micro’s stores, is the subject of Chapter 12; the book’s examples run on it are in Chapter 13; the merge is in Chapter 14. In the repository the module and its suites are src/aux.kanren.lambda.scm and src/test/microkanren-lambda*.scm, merged by the commits of Section 14.4. The prototype they were ported from stays, frozen at commit f84cf9c, under doc/hol-kanren/prototype/ (the module, micro.diff, show.diff, the design notes DESIGN.md, the tests, the examples, the benchmarks and the scripts that build and run them).

Every Scheme snippet of this chapter with an answer was run on the merged tree (master at c0ff08c, micro and (aux kanren lambda)) unless it says otherwise, and its output is pasted verbatim. Snippets of the form (show "label" query) are quoted from the prototype’s examples.scm, where show prints the label as a comment and then the answers; their outputs are quoted from examples.out, which that script, run on the merged tree, prints byte for byte.

11.1Requirements

The proposal was written against nine acceptance items, A1 to A9. Each one is a property of the answers that °->list returns for a class of goals, illustrated by the book’s own examples with the book’s own answers. This section states each item in a form precise enough to be tested, then gives its intuition and one worked example. The general statements are tested, by hand-written cases (83 cases with 320 assertions in the prototype, 93 with 421 in the merged suite), not proved.

11.1.1Setting and notation

Goals and terms. The goal language is that of (aux kanren micro) (=°, ≠°, absent°, symbol°, number°, fresh°, and°, or°, cond°, relations) extended with three forms: (∀° (x) G), the universal goal pi x\ G; (⊃° (D ...) G), the implication D => G; and relations declared with define-dynamic-relation, the only ones that take hypotheses. The term language is micro’s (Scheme data and logic variables) extended with abstractions (ƛ (x) t), applications (@ t u ...) and eigenvariables. We write Ans(G)\mathrm{Ans}(G) for the list returned by (°->list #f G), and say that GG fails when Ans(G)\mathrm{Ans}(G) is empty.

Reference semantics. The specification is the goal-directed search of the book for hereditary Harrop formulas, that is, the six rules and, or, instan, generic, augment and backchain (Rules A.6; [MN p. 77], [MN p. 82], [MN p. 124]; see Section 3.2 and Appendix A). Uniform proofs are complete for intuitionistic provability of these formulas (Theorem 3.12), so implementing these rules faithfully is the semantics. Where λProlog says nothing (disequality, absento, types), the reading adopted extends micro’s own semantics over λProlog’s term model (item A8).

Definition 11.1 (Universe levels). A state carries a depth d∈ℕd\in\mathbb{N}, the number of ∀° goals whose body is running. Every logic variable XX has a level ℓ(X)\ell(X), the depth at its creation unless later lowered. An eigenvariable cc created by a ∀° at depth dd has ℓ(c)=d+1\ell(c)=d+1. The names that the unifier itself opens when it goes under a binder have level ∞\infty.

These levels are Nadathur, Jayaraman and Kwon’s tags minus one: their query starts at tag 1 (Rules A.33), ours at depth 0.

The level is the linear trace of Miller’s mixed prefix: a variable of level dd stands for an existential quantifier that follows the first dd universal quantifiers of its branch. The intended reading is Nadathur, Jayaraman and Kwon’s Gopalan Nadathur, Bharat Jayaraman, and Keehang Kwon. Scoping constructs in logic programming: implementation problems and their solution. Journal of Logic Programming, 25(2):119–161, 1995 (Definition 9.15): a term may be substituted for XX only if every constant in it has a level ≤ℓ(X)\le \ell(X).

Example 11.2. In (fresh° (q) (∀° (x) (fresh° (y) G))), q has level 0, the eigenvariable x level 1, and y level 1. So y may be bound to a term containing x, while q may not. This is ∃q ∀x ∃y. G\exists q\,\forall x\,\exists y.\,G read off the creation depths.

Definition 11.3 (Order independence). A conjunction is order independent when permuting its conjuncts changes at most the order of its answers, not the set of answers (taken as data, with their residual constraints).

Order independence is not an item of its own. It runs through all of them, because it is what Nadathur, Jayaraman and Kwon prove for their tagged interpreter: the choice of the goal to reduce next is irrelevant (their Prop. 4.1, Section 9.7). A miniKanren conjunction is fair to no conjunct, so any order-dependence is visible to the user. Most defects found by the reviews of Section 11.5 were violations of it, “in one goal order of three”.

11.1.2The nine items

Definition 11.4 (A1: the scope of ∀). (a) generic. In a state of depth dd, (∀° (x) G) runs G[c/x]G[c/x] at depth d+1d+1, with cc a new eigenvariable of level d+1d+1, and gives every answer state of GG back the depth dd.

(b) Scope invariant. In every state reached by the search, every binding X:=tX:=t of the substitution satisfies the three binding conditions of Definition 9.15 (stated also in Section 3.4.3 and Definition A.34): (1) XX does not occur in tt; (2) every eigenvariable occurring in tt has a level ≤ℓ(X)\le \ell(X); (3) every unbound variable YY of tt has ℓ(Y)≤ℓ(X)\ell(Y)\le\ell(X) (lowering; for a flexible subterm Y a¯Y\,\bar a, the arguments not visible at ℓ(X)\ell(X) are pruned).

(c) Universality of the invariant. (b) holds for every binding, whatever goal made it: the goals of the new module, micro’s own =°, every relation built on it (cons°, the user’s relations), and the unifier’s internal bindings.

Intuitively, (a) is the book’s generic rule [MN p. 82] (Definition 3.9) and (b) is the reason why it is sound: no eigenvariable can reach a variable created before its ∀°, directly or through an alias, so a proof never assumes that a fresh name equals an older term. Restoring the depth on each answer matters: a variable created after the ∀° has exited must not see cc, which a creation timestamp alone would not ensure.

The invariant (b) is stated on single bindings, but it controls whole values. Suppose X:=tX:=t and YY occurs unbound in tt; by (3), ℓ(Y)≤ℓ(X)\ell(Y)\le\ell(X), so if YY is bound later to some t′t', condition (2) for Y:=t′Y:=t' admits only eigenvariables of level ≤ℓ(Y)≤ℓ(X)\le\ell(Y)\le\ell(X). By induction on the chain of bindings, the fully walked value of XX never holds an eigenvariable of level >ℓ(X)>\ell(X): checking each binding once, when it is made, is enough. Condition (3) is what makes the induction go through; without lowering, an alias created before the eigenvariable could receive it later.

Item (c) is what separates a sound design from a layered one, as Section 11.3.1 shows. The book’s two classical queries [MN p. 85] and two escapes through aliases:

(show "∃Y∀x. Y = x  and  ∀x∃Y. Y = x"
      (list (°->list #f (fresh° (q) (∀° (x) (=° q x))))
            (°->list #f (fresh° (q) (∀° (x) (fresh° (y) (=° y x))) (=° q 'ok)))))

(show "escape through an alias (q = (y), y = x), and through micro's cons°: both fail"
      (list (°->list #f (fresh° (q) (∀° (x) (fresh° (y) (=° q (list y)) (=° y x)))))
            (°->list #f (fresh° (q) (∀° (x) (cons° x '() q))))))
;; ∃Y∀x. Y = x  and  ∀x∃Y. Y = x
(() ((λ () 'ok)))

;; escape through an alias (q = (y), y = x), and through micro's cons°: both fail
(() ())

In the third query the binding y := x is legal (y has level 1), but q := (y) was made earlier with y unbound; condition (3) lowered y to level 0 at that moment (by binding it to a fresh variable of level 0), so the later y := x violates (2). The fourth query never mentions the new module’s unifier: cons° is micro’s, and its =° is checked all the same. The suite adds Nadathur, Jayaraman and Kwon’s own example (Section 3.4.3, and the tutorial after Definition 9.15), where lowering reaches a variable created by backchaining on an assumed clause: ∃x∀y(q y⊃p x)\exists x\forall y(q\,y\supset p\,x) with the clause ∀z(q z⊃p (d z))\forall z(q\,z\supset p\,(d\,z)) fails, as it must.

Definition 11.5 (A2: AUGMENT and BACKCHAIN). (a) augment. Σ;𝒫⟶D⊃G\Sigma;\mathcal{P}\longrightarrow D\supset G reduces to Σ;𝒫∪{D}⟶G\Sigma;\mathcal{P}\cup\{D\}\longrightarrow G: (⊃° (D ...) G) runs GG with the clauses DD added to a context Γ\Gamma kept in the state, and gives every answer state of GG back the old Γ\Gamma. Hypotheses are visible exactly during GG, and the branches of an or° do not see each other’s hypotheses.

(b) Clause order. Γ\Gamma is a list, extended at the front. A dynamic relation pp called on t¯\bar t is the disjunction of its clauses in Γ\Gamma, most recent first, followed by its static body [MN p. 78].

(c) Variables of a clause. The logic variables free in DD belong to the context: they are shared by every use of the clause and with the goal around it [MN p. 86–88]. The clause’s own universally quantified variables, (∀ (z) ...), are renamed at each use, at the current level (Nadathur, Jayaraman and Kwon’s “new tagged instance”).

(d) Static relations are closed. Assuming a clause for a relation not declared with define-dynamic-relation is an error, not a silent no-op.

Point (b) is a statement about order, which a miniKanren usually leaves to interleaving. The book fixes it with two queries against the program p 1 [MN p. 78]:

?- p 2 => p 3 => p X.
X = 3;
X = 2;
X = 1
?- (p 2 & p 3) => p X.
X = 2;
X = 3;
X = 1
(define-dynamic-relation (p° x) (=° x 1))
(show "clause order under augmentation (p.94)"
      (list (°->list/datum (fresh° (q) (⊃° ((p° 2)) (⊃° ((p° 3)) (p° q)))))
            (°->list/datum (fresh° (q) (⊃° ((p° 2) (p° 3)) (p° q))))))
;; clause order under augmentation (p.94)
((3 2 1) (2 3 1))

The label’s “p.94” is the PDF page, [MN p. 78]; see Section 1.5. Each clause answers without suspending, so the flat disjunction returns its disjuncts in order, and the order is the book’s. Point (c) is the subtle one: in pi z\ (q z => p (d z)) the variable z is the clause’s own, while a free Y in an assumed p Y is the goal’s. Section 3.8.1 explains why Γ\Gamma must live in the state rather than in a Scheme parameter.

Definition 11.6 (A3: ∀ and ⊃ together). The book’s type inference for untyped λ-terms (Section 6.5.4), whose abstraction case is typeof (abs M) (arr A B) :- pi x\ typeof x A => typeof (M x) B, computes principal types: for a closed term it answers the book’s type up to the names of type variables, and it fails on terms that have no simple type.

This item exercises all of A1, A2 and A4 in one clause: ∀° makes the bound variable a scoped constant, ⊃° assumes its type, (@ R x) β-reduces the object-level body, and the type variables A, B, created outside the ∀°, must never be bound to a type containing x. In the module’s syntax:

(define-dynamic-relation (typeof° m t)
  (cond°
    ((fresh° (M N B) (=° m `(app ,M ,N)) (typeof° M `(arr ,B ,t)) (typeof° N B)))
    ((fresh° (R A B) (=° m `(abs ,R)) (=° t `(arr ,A ,B))
       (∀° (x) (⊃° ((typeof° x A)) (typeof° (@ R x) B)))))))

Run on the combinators S and I and on λx. x x\lambda x.\,x\,x, written in the object syntax with ƛ for the meta-level binder:

(show "typeof S, I and λx.x x"
      (list (°->list/datum (fresh° (q) (typeof° `(abs ,(ƛ (x) `(abs ,(ƛ (y) `(abs ,(ƛ (z)
                                          `(app (app ,x ,z) (app ,y ,z)))))))) q)))
            (°->list/datum (fresh° (q) (typeof° `(abs ,(ƛ (x) x)) q)))
            (°->list/datum (fresh° (q) (typeof° `(abs ,(ƛ (x) `(app ,x ,x))) q)))))
;; typeof S, I and λx.x x
(((arr (arr α (arr β γ)) (arr (arr α β) (arr α γ)))) ((arr α α)) ())

The third query fails by the occurs check: the type of x would have to be an arrow type containing itself.

Definition 11.7 (A4: λ-tree syntax and β). (a) α. (ƛ (x) t) builds an abstraction whose bound variable is a Scheme variable; terms built alike are equal?, and unification is modulo α.

(b) β. (@ (ƛ (x) t) s) is t[s/x]t[s/x] at construction; an application whose head becomes an abstraction through a later binding is reduced on the fly, in unification and in every deep walk.

(c) η. Terms are kept η-short; η-expansion happens on demand when one side of an equation is an abstraction.

(d) Object-level substitution is meta-level β (Section 6.3): the book’s evaluators, copy and subst give the book’s results.

(show "α-equivalence: λa.a = λb.b, and the β-redex (λx.g x x) a"
      (list (°->list #f (fresh° (q) (=° (ƛ (a) a) (ƛ (b) b))))
            (°->list/datum (fresh° (q f) (=° f (ƛ (x) `(g ,x ,x))) (=° q (@ f 'a))))))
;; α-equivalence: λa.a = λb.b, and the β-redex (λx.g x x) a
(((λ (α) α)) ((g a a)))

The first unification succeeds and binds nothing, so q stays fresh. In the second, f is bound first and the application (@ f 'a) is β-reduced when the deep walk of the answer meets it. With call-by-name evaluation, the book’s (λxλw.w) Ω(\lambda x\lambda w.w)\,\Omega [MN p. 183] evaluates to abs w\w without ever evaluating Ω, because the substitution of the argument is a meta-level β that drops it (Chapter 13).

Definition 11.8 (A5: Lλ unification and delay). Call pattern for a variable FF an argument list a¯\bar a of F a¯F\,\bar a whose members head-normalise to distinct eigenvariables of level >ℓ(F)>\ell(F) (Definition 7.15, with levels in place of the prefix).

(a) Patterns. For an equation all of whose flexible subterms are patterns, unification terminates; it fails if and only if the equation has no unifier, and otherwise it binds a most general unifier (Theorem 7.22). On the problems 8.G–8.K it gives the book’s answers and mgus [MN p. 222–225]. (The book does not number these problems; the labels 8.A–8.M are those of Section 7.7, in their order of appearance, as the test suite uses them; 8.M is the problem of [MN p. 208].)

(b) Dynamic LλL_\lambda [MN p. 225–226]. An equation outside LλL_\lambda is neither failed nor enumerated: it is suspended, retried after every later binding, solved as soon as it becomes a pattern, and otherwise reported in the answer as a residual (assert (≐ u v)), closed over the eigenvariables whose scope it outlived.

The level condition is Miller’s “universally quantified inside the scope of FF”. To see it at work, compare ∃F ∀x. F x=x\exists F\,\forall x.\,F\,x=x with ∀x ∃F. F x=x\forall x\,\exists F.\,F\,x=x. In the first, ℓ(F)=0<1=ℓ(x)\ell(F)=0<1=\ell(x), so (@ F x) is a pattern, and the only unifier is F:=λx. xF:=\lambda x.\, x. In the second, FF is created under the ∀°, so ℓ(F)=1=ℓ(x)\ell(F)=1=\ell(x) and (@ F x) is not a pattern: FF may mention xx as a constant, and both λz. z\lambda z.\, z and λz. x\lambda z.\, x solve the equation, so no unifier is most general. The proposal solves the first; the second it suspends, accepting either solution when a later goal supplies it:

(pretty-print
 (list (°->list/datum (fresh° (q) (∀° (x) (=° (@ q x) x))))
       (°->list/datum (fresh° (q) (∀° (x) (fresh° (F) (=° (@ F x) x)
                                                    (=° F (ƛ (z) z)) (=° q 'id)))))
       (°->list/datum (fresh° (q) (∀° (x) (fresh° (F) (=° (@ F x) x)
                                                    (=° F (ƛ (z) x)) (=° q 'const)))))))
(pretty-print
 (°->pretty (fresh° (q) (∀° (x) (fresh° (F) (=° (@ F x) x) (=° q 'ok))))))
(((ƛ (x) x)) (id) (const))
((ok : (= (ƛ (x) (@ α x x)) (ƛ (x) x))))

The last residual is instructive. When the ∀° exits, FF (of level 1) is raised, F:=α xF:=\alpha\,x with ℓ(α)=0\ell(\alpha)=0, and the equation is closed over xx: ∀x ∃F. F x=x\forall x\,\exists F.\,F\,x=x has become ∃α ∀x. α x x=x\exists\alpha\,\forall x.\,\alpha\,x\,x=x, which is problem 8.M below.

Part (a) is Miller’s theorem Dale Miller. A logic programming language with lambda-abstraction, function variables, and simple unification. Journal of Logic and Computation, 1(4):497–536, 1991, whose algorithm (Definition 7.21) prunes and raises; part (b) is what Teyjus 2 does with the equations it cannot solve, after Dowek, Hardin, Kirchner and Pfenning Gilles Dowek, Thérèse Hardin, Claude Kirchner, and Frank Pfenning. Unification via explicit substitutions: the case of higher-order patterns. In M. Maher, editor, Joint International Conference and Symposium on Logic Programming (JICSLP), pages 259–273. MIT Press, 1996 (Section 7.9.1). The book’s main example, problem 8.H [MN p. 223–224] (Example 7.23), ∀w ∀x ∀y. f (U x y)=f (g (V y w))\forall w\,\forall x\,\forall y.\ f\,(U\,x\,y)=f\,(g\,(V\,y\,w)) with UU, VV quantified outside, is the λProlog query pi w\ pi x\ pi y\ f (U x y) = f (g (V y w)); it has the mgu U=λx. λy. g (V′ y)U=\lambda x.\, \lambda y.\, g\,(V'\,y), V=λy. λw. V′ yV=\lambda y.\, \lambda w.\, V'\,y (Example 7.23):

(show "Example 8.H, pruning: (U V)" (°->list/datum (fresh° (q u v) (=° q (list u v)) (∀° (w x y) (=° `(f ,(@ u x y)) `(f (g ,(@ v y w))))))))
;; Example 8.H, pruning: (U V)
(((ƛ (x y) (g (@ α y))) (ƛ (y w) (@ α y))))

The fresh α is the book’s V′V'. A non-pattern such as problem 8.M, pi x\ F x x = x, has two incomparable unifiers, so it waits; it is reported, and a later binding wakes it. Problem 8.A, F a=g a aF\,a=g\,a\,a with aa a constant, is not a pattern either (its argument is no eigenvariable):

(show "non-patterns: 8.M and 8.A, suspended; 8.M woken by F := λa.λb.b"
      (list (°->pretty (fresh° (q) (∀° (x) (=° (@ q x x) x))))
            (°->pretty (fresh° (q) (=° (@ q 'a) '(g a a))))
            (°->list/datum (fresh° (q) (∀° (x) (=° (@ q x x) x))
                                       (=° q (ƛ (a b) b))))))
;; non-patterns: 8.M and 8.A, suspended; 8.M woken by F := λa.λb.b
(((α : (= (ƛ (x) (@ α x x)) (ƛ (x) x))))
 ((α : (= (@ α a) (g a a))))
 ((ƛ (a b) b)))

(The first two answers, 8.M and 8.A, are printed by °->pretty of the show module, the third by °->list/datum; the residual of 8.M is closed over x, which has left its scope.)

Definition 11.9 (A6: λProlog’s semantics where Ma and Friedman differ). On the equations by which Ma and Friedman Weixi Ma and Daniel P. Friedman. A new higher-order unification algorithm for λ\lambdaKanren. In miniKanren and Relational Programming Workshop, 2021 motivate static closures (Section 9.2), the answer is λProlog’s: (1) λa. X=λb. b\lambda a.\, X=\lambda b.\, b and their conjunction containing it fail, since ∃X∀a. X=a\exists X\forall a.\,X=a is false (Example 7.25); the paper answers X=𝚍𝟶X=\mathtt{d0}; (2) λa. λa. X=λc. λd. c\lambda a.\, \lambda a.\, X=\lambda c.\, \lambda d.\, c fails, with no false “true = false”, because shadowing is lexical; (3) their Example 3, λa. λb. X=λc. λd. Y\lambda a.\, \lambda b.\, X=\lambda c.\, \lambda d.\, Y, gives X=YX=Y; (4) an assumption is tried before the program: with a dynamic eq°, their assume query gives (orange apple) where the paper prints (apple orange); (5) their E12, ∀A. A=F A\forall A.\,A=F\,A, gives F=λA. AF=\lambda A.\, A, as in the paper.

(show "λa.X = λb.b fails (the paper: X = d0); λa.λa.X = λc.λd.c fails; ∀A. A = F A gives F = λA.A"
      (list (°->list #f (fresh° (q) (=° (ƛ (a) q) (ƛ (b) b))))
            (°->list #f (fresh° (q) (=° (ƛ (a) (ƛ (a) q))
                                        (ƛ (c) (ƛ (d) c)))))
            (°->list/datum (fresh° (q) (∀° (a) (=° a (@ q a)))))))
;; λa.X = λb.b fails (the paper: X = d0); λa.λa.X = λc.λd.c fails; ∀A. A = F A gives F = λA.A
(() () ((ƛ (a) a)))

Section 9.3.1 discusses these equations; the point here is only that the proposal answers them the way λProlog’s quantifier reading dictates.

Definition 11.10 (A7: the book’s programs). The book’s programs over λ-tree syntax give the book’s answers, in the book’s order where the interleaving search allows it: de Bruijn translation in both directions [MN p. 193]; prenex normal forms, the unique one and the five of a non-unique case [MN p. 196–197]; mappred (Figs. 5.3–5.4); palindromes over functional difference lists, the book’s first nine answers [MN p. 142]; Fischer’s CPS transformation, exactly the book’s term [MN p. 257].

These programs are the integration tests: each needs several of A1–A5 at once, and each has an answer printed in the book to compare with. Chapter 13 walks through them.

Definition 11.11 (A8: micro’s stores on λ-terms). (a) ≠° decides modulo αβη and respects scope; its outcome does not depend on whether a binding comes before or after it. Under ∀° it reads an eigenvariable as generic’s new name by default (pi x\ not (q = x) succeeds), and as any term of its universe when the parameter μkanren-λ-reading is 'extensional (the reading of Moiseenko and of Jin et al. Evgenii Moiseenko. Constructive negation for miniKanren. In miniKanren and Relational Programming Workshop, 2019; and Ende Jin, Gregory Rosenblatt, Matthew Might, and Lisa Zhang. Universal quantification and implication in miniKanren. In miniKanren and Relational Programming Workshop, 2021).

(b) absent° looks for its datum in the parts of a λ-term, never in binder names, de Bruijn indices or the internals of an eigenvariable; on a flexible term it waits.

(c) symbol°, number° and the user’s types wait on a flexible term, and decide a rigid λ-term or an eigenvariable by the type’s predicate.

(d) No eigenvariable is ever printed free in an answer; residual constraints print as ≐ and (∀ (x) ...); binders print renamed apart; ground answers evaluate back to live λ-terms.

λProlog has no disequality, absento or types, so this item is not fidelity but coherence: micro’s stores must keep meaning what they mean once terms have binders. For instance:

(show "≠ modulo αβη, flex-flex with an existential, a flexible absento, a type on a flexible term"
      (list (°->pretty (fresh° (q) (≠° q (ƛ (x) x))))
            (°->pretty (fresh° (q f g) (=° q (list f g))
                         (≠° (ƛ (x y) (@ f x)) (ƛ (x y) (@ g y)))))
            (°->pretty (fresh° (q F) (=° q F) (absent° 'c (@ F 'c))))
            (°->list/datum (fresh° (q F) (=° q F) (absent° 'c (@ F 'c))
                             (=° F (ƛ (z) 'b))))
            (°->list/datum (fresh° (q F) (=° q (@ F 'a)) (symbol° q)
                             (=° F (ƛ (z) z))))))
;; ≠ modulo αβη, flex-flex with an existential, a flexible absento, a type on a flexible term
(((α : (≠ α (ƛ (x) x))))
 (((α β) : (∀ (_3) (≠ (α β) ((ƛ (x) _3) (ƛ (y) _3))))))
 ((α : (absento c (@ α c))))
 ((ƛ (z) b))
 (a))

Line by line. (1) q≠λx. xq\ne\lambda x.\, x is kept as a constraint, as micro keeps q≠5q\ne 5. (2) The trial unification of λx. λy. f x\lambda x.\, \lambda y.\, f\,x with λx. λy. g y\lambda x.\, \lambda y.\, g\,y prunes both ff and gg to a common constant function: the line says ¬∃H. f=λx. H∧g=λy. H\neg\exists H.\,f=\lambda x.\, H\wedge g=\lambda y.\, H, printed in the equivalent form ∀H. (f  g)≠(λx. H  λy. H)\forall H.\,(f\;g)\ne(\lambda x.\, H\;\lambda y.\, H). The variable HH (_3), which the trial created, is quantified inside the negation, which micro’s prefixes cannot express. (3) Whether c is absent from F 𝖼F\,\mathsf{c} depends on FF, so the constraint waits on the whole flexible term. (4) Once F:=λz. 𝖻F:=\lambda z.\, \mathsf{b}, the argument is dropped and the constraint holds. (5) (symbol° q) waits on F 𝖺F\,\mathsf{a} and holds once F:=λz. zF:=\lambda z.\, z makes it a. Chapter 12 explains each of these answers in detail.

Definition 11.12 (A9: conservativity). (a) micro’s six suites (microkanren, -aggregation, -untagged, -show, -arith, -date; 125 cases at f84cf9c, 187 on the merged tree) pass with unchanged expectations, answer order included, against the edited micro, both with and without (aux kanren lambda) loaded.

(b) A first-order program pays at most a few per cent for the edit (measured in Section 11.4.10).

Table 11.1 summarises the nine items and the evidence for each.

Table 11.1: The acceptance items and the hand-written cases that pin them (93 cases, 421 assertions in src/test/microkanren-lambda.scm; 6 more cases in microkanren-lambda-limits.scm pin the known limits).
itemrequirementbookcases / assertions
A1scope of ∀: generic, NJK’s binding conditions on every binding[MN p. 82, 85]9 / 22
A2⊃: augment, clause order, shared and renamed variables, closed static relations[MN p. 77–78, 86–88]8 / 21
A3∀ and ⊃ together: type inference[MN p. 191]3 / 8
A4λ-tree syntax: α, β, η; object substitution by meta β[MN p. 177–199]4 / 9
A5LλL_\lambda unification with mgus; dynamic LλL_\lambda (delay)[MN p. 220–226]10 / 40
A6λProlog’s answers where Ma–Friedman differ—5 / 13
A7the book’s programs, the book’s answers[MN p. 142, 193–197, 257]5 / 12
A8≠, absento, types and reification on λ-terms—11 / 65
A9micro’s suites unchanged; first-order cost—1 / 2, + 187 cases ×2
R, R2, R3regressions of the three review rounds (Section 11.5)27 / 128
R4, S, one Rcases added by the merge (Section 14.1.1)10 / 101

11.2The design space

Section 9.8 put four candidate meanings of =° on λ-terms side by side, without choosing (Table 9.2). In one paragraph each:

  • A. Pattern unification with de Bruijn terms and levels, after Miller, Nipkow, and Nadathur and Linnell Dale Miller. A logic programming language with lambda-abstraction, function variables, and simple unification. Journal of Logic and Computation, 1(4):497–536, 1991; Tobias Nipkow. Functional unification of higher-order patterns. In M. Vardi, editor, 8th Symposium on Logic in Computer Science, pages 64–74, New York, 1993. IEEE; and Gopalan Nadathur and Natalie Linnell. Practical higher-order pattern unification with on-the-fly raising. In ICLP 2005: 21st International Logic Programming Conference, volume 3668 of LNCS, pages 371–386, Sitges, Spain, 2006. Springer; what Teyjus 2 and ELPI Cvetan Dunchev, Ferruccio Guidi, Claudio Sacerdoti Coen, and Enrico Tassi. ELPI: fast, embeddable, λ\lambdaProlog interpreter. In Logic for Programming, Artificial Intelligence, and Reasoning (LPAR-20), volume 9450 of LNCS, pages 460–468. Springer, 2015 run. Decidable and unitary on LλL_\lambda; non-patterns are delayed.
  • B. Nominal unification (Urban–Pitts–Gabbay Christian Urban, Andrew M. Pitts, and Murdoch J. Gabbay. Nominal unification. Theoretical Computer Science, 323(1–3):473–497, 2004; αKanren William E. Byrd and Daniel P. Friedman. α\alphaKanren: A fresh name in nominal logic programming. In Proceedings of the 2007 Workshop on Scheme and Functional Programming, Université Laval Technical Report DIUL-RT-0701, pages 79–90, 2007). Decidable, unitary with a freshness context. A different logic: names as data, no function variables, no β; noms are distinct constants, not eigenvariables, so generic still needs a separate mechanism; αKanren has no disequality.
  • C. Static closures (Ma–Friedman Weixi Ma and Daniel P. Friedman. A new higher-order unification algorithm for λ\lambdaKanren. In miniKanren and Relational Programming Workshop, 2021). Grafting semantics: λa. X=λb. b\lambda a.\, X=\lambda b.\, b succeeds, unlike λProlog; a workshop preview with no published algorithm.
  • D. Huet’s pre-unification, enumerated by the stream (Huet Gérard Huet. A unification algorithm for typed λ\lambda-calculus. Theoretical Computer Science, 1:27–57, 1975; Teyjus 1). Exact for full higher-order unification, but semi-decidable, with possibly infinitely many pre-unifiers.

The proposal retains A, for three reasons.

  1. λProlog’s semantics. The requirements are the book’s. Option A is what the book’s own implementations run, and with delayed non-patterns its behaviour on the book’s examples is the book’s (A5). Option C gives different answers on A6’s equations by design; option B answers a different question.
  2. Decidability and most general unifiers. Miller’s theorem (Theorem 7.22) makes unification on patterns terminating and unitary. This matches the shape of micro’s =°, which maps a state to at most one state (✓° or ✗°). Option D needs branching inside unification, so it cannot be an =°; it can be added later as an explicit search over the suspended equations, which are its natural agenda (Chapter 14).
  3. Universe levels make generic cheap and exact. The tagged interpreter of Nadathur, Jayaraman and Kwon is sound and complete, and needs one integer per variable and one comparison per binding (Definition 9.15). The alternatives for ∀ alone are weaker or costlier: the explicit prefix of λKanren 2020 Weixi Ma, Kuang-Chen Lu, and Daniel P. Friedman. Higher-order logic programming with λ\lambdaKanren. In miniKanren and Relational Programming Workshop, 2020 is walked at each check and only grows (Section 9.4); the eigen-absento of Hemann, Byrd and Friedman Jason Hemann, William E. Byrd, and Daniel P. Friedman. The eigen operator of miniKanren-with-symbolic-constraints. Software, 2013. URL https://github.com/webyrd/miniKanren-with-symbolic-constraints costs O(∣B∣)O(|B|) per check and is first-order only (Section 9.6); the end-of-scope check of Section 10.9.3 prunes late and lets constraints outlive their scope.

Three secondary choices follow from A and are shared by every prototype below. Terms are locally nameless Conor McBride and James McKinna. Functional pearl: I am not a number — I am a free variable. In Proceedings of the ACM SIGPLAN Workshop on Haskell, 2004; and Arthur Charguéraud. The locally nameless representation. Journal of Automated Reasoning, 49(3):363–408, 2012 (de Bruijn indices inside bodies, eigenvariables for free names), so α costs nothing and terms built alike are equal?. Raising is done lazily through levels rather than eagerly as in the book’s §4.4.1 [MN p. 107]; the two differ in the shape of the mgu, not in its meaning (Example 7.31). And non-patterns are delayed rather than rejected: rejecting them, as ELPI does by default, would lose subst R N (R N) with R unknown, and the palindrome program.

What A leaves open is where the code lives with respect to (aux kanren micro), and that question was answered by building it three times.

11.3Three prototypes

Three complete prototypes were built against A1–A9. They share the representation (locally nameless abstractions, applications, eigenvariables with levels) and the algorithmic core (variable elimination with pruning and lowering, a store of suspended equations). They differ in architecture. Table 11.2 compares them at a glance; the subsections describe each one, its strengths, and the concrete defects the three reviews found.

d1, layeredd2, hooksd3, native
edit to micronone (byte-identical binary)+105/−25 lines: a field and seven hooksmicro grows from 713 to 1217 lines; a 931-line diff
λ statea record bound to the reserved variable 0a seventh field XX holds U, E, P; levels on the variable record
unifiera second one, =λ°, beside micro’smicro’s, plus an unify hookmicro’s, rewritten
runnerits own, λrunmicro’s °->listmicro’s °->list
suite29 cases, 137 assertions, hand-written42 cases, 102 assertions, hand-written14 cases, 116 assertions, a generated snapshot
ranklast for all three reviewsfirst for two reviewsfirst for the pedagogy review
Table 11.2: The three prototypes.

11.3.1d1: a layer with no edit to micro

Architecture. d1 takes Section 10.9.2 at its word: it imports micro unchanged and adds a pure library. Its whole context (current level, level boundaries and overrides, the clause database, delayed equations, pending constraints) is a record bound to the reserved variable 0, the “S-register” of Trick 2, overwritten by a persistent update/sbral in O(log⁡∣S∣)O(\log|S|), so each branch of an or° keeps its own context; the query variable is variable 1. Since micro’s binding site is closed, d1 brings its own unifier =λ°, its own constraints ≠λ° and absentλ°, and its own runner λrun. Levels need no slot in the variables: micro allocates indices monotonically, so a variable’s level at creation is a step function of its index, recorded as boundaries pushed by ∀°; lowering is recorded as overrides.

Strengths. Micro’s behaviour and speed are untouched by construction. d1’s absent° was the most precise on flexible terms, it offered the extensional reading of ≠ under ∀, it had an αKanren-style printer, a data runner comparable with equal?, and a table of every place where purity leaks, each pinned by a test. All these were grafted into the final proposal.

Defects. The leaks are the architecture’s, not the code’s. Micro’s =°, and every relation built on it, binds without d1 seeing the binding, so A1(c) fails:

; d1-layered, its own runner
(pretty-print (λrun (q -1) (∀° (x) (cons° x '() q))))
(pretty-print (λrun (q -1) (∀° (x) (=λ° q x))))
((x₂))
()

With d1’s own unifier the escape is caught; with micro’s cons° the eigenvariable x₂ leaks into the answer. The proposal answers () to the first query (A1, above). The reviews found four more defects: the module’s goals do not run under °->list (they need the register); conjunction is not commutative, because d1 read a list headed by a symbol as a rigid application in spine notation, conflating lists with λ-tree applications, and together with η this made the answers of some conjunctions depend on the order of the conjuncts; d1 duplicates a large part of micro; and =λ° costs 4.4 times micro’s =° on search. Its clause database was a linear list, on which the reviews measured slowdowns of 18 times. d1 was ranked last by all three reviews.

11.3.2d2: an extension protocol in micro

Architecture. d2 makes the smallest principled edit that opens the closed points of Table 10.2, and builds the whole λ layer as a client module on top of it. The state gets a seventh field X, which micro copies and never reads. A record of procedures, registered globally, has hooks for term?, unify, post, diseq, value, repr and forms; micro calls them at the matching points. The edit was +105/−25 lines (counted on its micro.diff), the module 708 lines.

Strengths. The reviews found no soundness defect in d2. It kept terms η-short as an invariant, so both λx. q x=q\lambda x.\, q\,x=q and F x=G x⇒F=GF\,x=G\,x\Rightarrow F=G hold; it had a “soft” occurs check that suspends F x=G (F x)F\,x=G\,(F\,x) instead of failing it (it holds with G:=λz. zG:=\lambda z.\, z); its suite was hand-written with book page references; its printer was the only one that renamed binders correctly; and the edit cost at most 2.8% on micro’s benchmarks.

Defects. The reviews found seven, listed in Table 11.3. None is a soundness defect; most are imprecisions of the stores on λ-terms and one is a cost.

defectfix in the proposal
D1a suspended disequality printed as (deny (and))the denied equation, (deny (≐ u v))
D2absent° over-strict on flexible termsthe parts hook: a flexible term is watched whole
D3trivially true residuals kept (F x x=F x xF\,x\,x=F\,x\,x)delay drops α-equal sides
D4Miller’s n7 left suspended and printed with _2discharge at ∀ exit; the terms hook names residual variables
D5registering the extension slowed ≠°-heavy first-order code by 45–50%migration only when a new binding holds a λ-term
D6goal suffix on term constructors, levels hidden in property lists, λ-terms not equal?ƛ, @; plain records thanks to parts, value, atom?; interned hints
D7symbol°/number° failed eagerly on flexible terms; ⊃° on a static relation silently ignoredthe tag hook; an error for non-dynamic relations
Table 11.3: The defects of d2 found by the reviews, and their fixes (design notes, §10.2).

One more defect turned up while grafting: F=λx. G (F x)F=\lambda x.\, G\,(F\,x), reached through η-short construction, failed micro’s occurs check before any hook could see it. That is why the final protocol has an occurs hook.

11.3.3d3: a native engine

Architecture. d3 integrates λ-terms into micro itself, in the style of ELPI and Teyjus. The variable record gets a level slot; μkanren-unify knows abstractions, eigenvariables and flexible applications; the binding site does the occurs check, the scope check and lowering in one walk; ∀° and ⊃° are core goals; the current universe, the delayed equations and the program are packed in one extra state field. Micro grew from 713 to 1217 lines.

Strengths. The pedagogy review ranked d3 first for three reasons: one vocabulary, readable answers in ƛ, @ and ≐, and answers usable as code. d3 also discharged residual constraints at ∀ exit by raising and closing them, and it was the fastest: type inference of the Church numeral 400 took 105 ms, against d2’s 441 ms.

Defects. The reviews found a crash in μkanren-verify-D+ on a disequality prefix whose trial unification delays, and an η-incompleteness that made ≠° unsound: after λx. F x≠λx. G x\lambda x.\, F\,x\ne\lambda x.\, G\,x, the binding G:=FG:=F was accepted.

(pretty-print (°->list #f (fresh° (q F G) (=° q (list F G)) (≠° (ƛ (x) (@ F x)) (ƛ (x) (@ G x))) (=° G F))))

Run against d3, then against the merged module:

((λ (α) (cons α (cons α '()))))
()

The answer of d3 is a pair (F,F)(F,F), which violates the disequality it was asked to keep. Besides, its suite was a snapshot generated from the actual answers rather than written from the book, and its diff carried trailing-whitespace churn.

11.3.4The verdict

The three reviews gave aggregate scores of 23 to d2, 21 to d3 and 15.5 to d1. Two reviews ranked d2 first, the pedagogy review ranked d3 first, and all three ranked d1 last. The choice of d2 as the base rests on four facts.

  • Size and scope of the edit. The final protocol of the prototype was +235/−41 lines of micro (713 to 907 lines; 214 of the added lines are not blank), comments included, all generic: nothing in micro mentions λ, levels or clauses. d3 special-cases every walker. Merged onto the micro of the records, it is +286/−65 lines in 26b4708 and +31/−9 in d501822 (1167 to 1410 lines), still with no mention of λ. The same protocol could carry another store, such as nominal terms or finite domains.
  • Soundness is equal. d3’s eager binding rule and the λ layer’s eager post check enforce the same binding conditions; every scope attack of the reviews fails correctly on both, and on the final version.
  • Correctness favours d2: d3 had a crash and an unsound ≠°, d2 neither.
  • Pedagogy. d3’s three advantages were grafted onto d2 (one vocabulary of ƛ, @, ≐; readable residuals; ground answers as live terms through the environment hook), so the pedagogical argument for the native design no longer holds.

The reviews also recommended about twenty grafts from d1 and d3. Each was either done or explicitly declined; Table 11.4 lists the main ones.

fromgraftstatus
d3discharge residual constraints at ∀ exit by raising and closingdone
d3≐ exported, residuals as (assert (≐ …)), merged binders (ƛ (x y) …)done
d3a first-order fast path for the scope checkdone (μkanren-plain?, top, the atom? hook)
d3ground answers as live termsdone (environment hook)
d3the 2–4× faster λ machinerypartly: Church 400 from 441 to 254 ms (210 ms merged); d3: 105 ms
d3var–var bindings oriented by leveldeclined: a hook on micro’s second-hottest path
d3levels on the variable recorddeclined: freshª would need the universe, so micro would become λ-aware
d1precise absent° on flexible termsdone
d1the extensional reading of ≠ under ∀, as an optiondone (μkanren-λ-reading)
d1a data runner, an αKanren-style viewdone (°->list/datum, °->pretty)
d1a limits table, each row pinned by a casedone
d1truly nameless λ-records, equal? modulo αpartly: interned hints; α-variants with different hints are not equal?
Table 11.4: Grafts recommended by the reviews (a selection from the design notes, §10.3).

The two declined grafts share a reason. Both would put knowledge of levels into micro’s core: the var–var clause of the unifier, its hottest path after pair–pair, and the variable constructor freshª, which would need the current universe kept in the extension’s data. The protocol’s discipline is that micro stays λ-agnostic; for the orientation, the lowering done by the scope check yields the same mgu up to renaming.

11.4The extension protocol

The protocol is the part of the proposal that edits (aux kanren micro). It is generic: it lets a client module own a class of records (its terms), keep per-branch data in the state, and be consulted at each point where micro would otherwise treat those records as plain slot vectors. The prototype carried it as micro.diff, a patch of +235/−41+235/{-}41 lines against the micro of f84cf9c. That micro then moved on (Section 14.4), the patch stopped applying, and the protocol entered master reworked, in commit 26b4708 “Open (aux kanren micro) to extensions”, with one more hook in d501822. This section gives it as merged. Excerpts are verbatim from src/aux.kanren.micro.scm at c0ff08c, and :N are its line numbers; some comment lines are left out. Section 11.4.9 lists where the merged protocol differs from micro.diff.

11.4.1The slot X

The state gets a field X, the extensions’ slot, the last of its nine (Definition 10.2). Micro never reads it, and every constructor of a state carries it along: the positional make-μkanren-state/C, μkanren-state-with/S of the binding site and of freshª, μkanren-state-with/stores and the indexing of a raw state (:128–150, :1148). The keyword copy μkanren-state-with accepts X:, and a copy that replaces X alone keeps the stores indexed (:159–171):

  (define (μkanren-state-with s #!key
                              (vars-count (μkanren-state-vars-count s))
                              (S μkanren-state-keep)
                              (D μkanren-state-keep)
                              (A μkanren-state-keep)
                              (T μkanren-state-keep)
                              (tags (μkanren-state-tags s))
                              (X (μkanren-state-X s)))
    (let* ((kept? (λ (v) (eq? v μkanren-state-keep)))
           (field (λ (v get) (if (kept? v) (get s) v))))
      (if (and (kept? S) (kept? D) (kept? A) (kept? T))
          (make-μkanren-state/C vars-count (μkanren-state-S s) (μkanren-state-M s) (μkanren-state-C s) (μkanren-state-P s)
                                (μkanren-state-Tc s) tags (μkanren-state-raw s) X)
          ...)))

The outside constructor keeps its six-argument signature, with X optional (:137–138), so the positional states of test/microkanren.scm still work. X is '() until an extension writes it, which the λ layer reads as “everything empty”; so °->§ keeps its fixed empty initial state. The λ layer stores in X one record with the current depth, the highest depth reached, the variables’ levels, the context Γ\Gamma, the suspended constraints E, the λ-disequalities N and an index W of the prefixes of D that reach each variable (Chapter 12). Since S is persistent and X is copied forward by every goal, the data is branch-local for free: each branch of an or° sees its own Γ\Gamma, as A2(a) requires. There is one slot for every extension: the λ layer takes all of it, so no other extension that keeps data in X can be loaded with it.

11.4.2Extensions and the registry

An extension is a record built by (:219–221)

  (define (make-μkanren-extension name #!key (term? #f) (atom? #f) (unify #f) (occurs #f) (post #f) (diseq #f) (tag #f) (watch #f)
                                             (parts #f) (value #f) (repr #f) (terms #f) (forms #f) (environment #f))

and μkanren-extension-register! adds it to a global list (:225–228). Registering again under the same name replaces the old extension, so reloading a module is harmless; nothing can be taken back. Dispatch is by term: the extension that owns a pair of terms is the first whose term? holds of either (:231–236).

  (define (μkanren-extension/term u v)
    (let loop ((E μkanren-extensions))
      (cond
        ((null? E) #f)
        ((let1 (term? (μkanren-extension-term? (car E))) (and term? (or (term? u) (term? v)))) (car E))
        (else (loop (cdr E))))))

With no extension registered a hook site costs a test of the empty registry, by pair? or null?, or a map over it (those of forms, terms, watch and environment), on paths that are not the hottest one (:209–210). The registry is global rather than per state because °->list starts from μkanren-state-empty: a per-state hook list would have to be carried by every initial state.

The exported surface is twelve names (:16–19): μkanren-state-X, make-μkanren-extension and μkanren-extension-register!; the unifier μkanren-unify and the chain μkanren-post-unify for the hooks; μkanren-state-forget, μkanren-state-remove-D and μkanren-state-no-D? (Section 11.4.4); and four readers of the indexed disequality store, μkanren-state-indexed?, μkanren-state-prefix, μkanren-state-prefix-ids and μkanren-state-drop-prefix. μkanren-extension?, μkanren-extension-name, the hook accessors and the dispatchers (μkanren-extension/term and its siblings) stay internal to micro, since no client uses them.

The λ layer registers itself once, at load time (aux.kanren.lambda.scm:1238–1245):

  (define μkanren-λ-extension
    (make-μkanren-extension 'λProlog
      term?: μkanren-λ-term? atom?: (λ (u) (or (μkanren-eigen? u) (μkanren-bvar? u))) unify: μkanren-λ-unify occurs: μkanren-λ-occurs post: μkanren-λ-post diseq: μkanren-λ-diseq
      watch: μkanren-λ-watch
      tag: μkanren-λ-tag parts: μkanren-λ-parts value: μkanren-λ-value repr: μkanren-λ-repr
      terms: μkanren-λ-terms forms: μkanren-λ-forms environment: μkanren-λ-environment))

  (μkanren-extension-register! μkanren-λ-extension)

The registration is for the whole process and for good: every query run after the import, a first-order one too, goes through the hooks.

11.4.3The hooks

Table 11.5 lists the fourteen hooks. Compared with d2’s seven, the protocol adds atom?, occurs, tag, parts, terms and environment, each answering a defect or a graft of the reviews (atom? the first-order fast path, environment live ground answers, the others the defects of Table 11.3 and the occurs failure found while grafting), and watch, added at the merge to keep the migration of D linear (Section 14.4). The last column says which closed point of Table 10.2 each hook opens. Then a paragraph per hook gives its contract and its call site; the contracts are stated in micro’s own comment of the record (:180–210).

hookarguments →\to result; contractcalled byopens
term?(u): uu is one of the extension’s recordsdispatch—
atom?(u): uu holds no variablemicro’s occurs check, which then does not look inside uuthe binding site
unify(u v s as) →\to (s* as*) | #f: a pair with one extension term, neither a working variable; parts unified with μkanren-unifyμkanren-unify/held: the structure–structure clause and the clause after pair–pairthe unification cond
occurs(α v s as) →\to (s* as*) | #f: micro’s occurs check failed on α:=v\alpha:=vμkanren-state-update, failure path onlythe binding site
post(s* as) →\to (s** as**) | #f: runs after the bindings of =°, before their constraints are handed on; may bind moreμkanren-post-unify, called by =°the post-=° chain
diseq(u v s absento) →\to #f | state | 'fail: may claim a disequality; absento when an absento posts it≠°, and every prefix that holds an extension’s term≠° (store D)
tag(u tag s) →\to state | #f: a type on its termμkanren-post-type: symbol°, number°, user types, and the types handed on by =°the A store
watch(d i s) →\to ss or ss with a new X: told of the prefix dd that D takes under the id iiμkanren-add-prefixthe D store
parts(u s [projecting]) →\to 'stuck | list: where absent° looks into its term; when projecting, the parts whose constraints an answer keepsabsent°, the absentos handed on, μkanren-project-Tthe T store; reification
value, repr(u walk s): the deep value; the expression that rebuilds itμkanren-state-find/value, /reprreification
terms(s) →\to terms: the terms of its residual constraintsμkanren-projectreification
forms(s s*) →\to forms: the forms its constraints add to an answerμkanren-projectreification
environment(): where °->list/ground evaluates answers°->listthe runner
Table 11.5: The hooks of an extension. u,vu,v: walked terms; ss: a state; as: the bindings made so far, as (α . t) pairs; →\to gives the result, | separates alternatives.

term? identifies the extension’s records. Every dispatch by term goes through it (unify, tag, parts, value, repr); the other hooks are consulted on every registered extension, so an extension without term? could still use them. For the λ layer, the four records are abstractions, applications, eigenvariables and de Bruijn indices.

unify is consulted when micro’s unifier meets a pair of walked terms, one of which is the extension’s and neither of which is a working variable. Two clauses of the unification cond hand such pairs over: the structure–structure clause (two records, or a record and a vector) and the clause after pair–pair (an extension term against a pair or an atom), :505–515:

        ((and (μkanren-structure? u*) (μkanren-structure? v*))
          (cond
            ((and (pair? μkanren-extensions) (μkanren-extension/term u* v*)) => (λ (e) ((μkanren-extension-unify e) u* v* s assocs)))
            (else (μkanren-unify/held (μkanren-structure->list u*) u-held (μkanren-structure->list v*) v-held s assocs))))
        ; the hottest path: a unification answers `(s* assocs*)` or #f, no need for a checked match.
        ((and (pair? u*) (pair? v*))  (let1 (r (μkanren-unify/held (car u*) u-held (car v*) v-held s assocs))
                                        (and r (μkanren-unify/held (cdr u*) u-held (cdr v*) v-held (car r) (cadr r)))))
        ; an extension's term against a pair or an atom.
        ((and (pair? μkanren-extensions) (μkanren-extension/term u* v*)) => (λ (e) ((μkanren-extension-unify e) u* v* s assocs)))
        (else #f))))

The variable clauses, above this excerpt, and the pair–pair clause are untouched. The hook may call μkanren-unify back on parts: the λ layer’s ξ rule opens both bodies with one new name and unifies them with micro’s own unifier. So a list nested in a λ-term is still unified by micro, and a λ-term nested in a list is still handed to the hook. μkanren-unify keeps the stores of its state as they are, and the hook must report every binding it makes (E2 below), since =° hands on the constraints of those only. Before the protocol, two records unified slot by slot, so an abstraction would have been compared by its hint and its raw body.

atom? tells micro’s occurs check that a record holds no variable, so the check need not look into its slots. For the λ layer, eigenvariables and indices are atoms. Without it micro rebuilt every eigenvariable as a slot list at each binding; adding it cut type inference of the Church numeral 400 from 311 to 254 ms in the prototype (an 18% gain on the λ workloads). In the walk of the binding site (:440–441):

                ; an extension's term that holds no variable is not looked into.
                ((μkanren-structure? w) (if (μkanren-extension/atom? w) M (O (μkanren-structure->list w) M)))

occurs gets the last word when micro’s occurs check fails on α:=v\alpha:=v and vv may hold extension terms. Inside a λ-term an occurrence may be only apparent: q=F qq = F\,q holds with F:=λz. zF:=\lambda z.\, z, and F=λx. G (F x)F=\lambda x.\, G\,(F\,x) with G:=λz. zG:=\lambda z.\, z. The binding site, closed in Table 10.2, is opened on its failure path only (:445–454):

    (let* ((M (μkanren-state-M s))
           (M* (if (and held (not (μkanren-M-admits? M (μkanren-var-index α)))) M (walk M))))
      (cond
        (M* (let* ((S* (μkanren-update/sbral α v (μkanren-state-S s)))
                   (s* (μkanren-state-with/S s (μkanren-state-vars-count s) S* M*))
                   (assocs* (cons `(,α . ,v) assocs)))
              `(,s* ,assocs*)))
        ; an occurrence inside an extension's term may be only apparent: the extension decides.
        ((pair? μkanren-extensions) (μkanren-extension/occurs α v s assocs))
        (else #f))))

The λ layer answers by β-normalising vv (if it is α\alpha itself the equation is trivial) and otherwise by variable elimination, which fails on a rigid occurrence and suspends one in the argument of a flexible term (Chapter 12).

post is the hook that carries the scope check. It runs after the bindings that one =° made and before their constraints are handed on or the stores indexed; it receives those bindings, may bind more (lowering, pruning, waking suspended equations), and returns the extended bindings, so that micro hands on the constraints of every variable they bind. The post-=° chain, closed and wired for D/A/T in micro alone, becomes an exported procedure (:261–269):

  (define (μkanren-post-unify s* assocs)
    (let loop ((E μkanren-extensions) (s* s*) (assocs assocs))
      (cond
        ((null? E) (if (μkanren-state-raw s*) (μkanren-state-index s*) (μkanren-repost s* assocs)))
        ((μkanren-extension-post (car E)) => (λ (post)
                                                (match/first (post s* assocs)
                                                  (#f #f)
                                                  ((,s** ,assocs*) (loop (cdr E) s** assocs*)))))
        (else (loop (cdr E) s* assocs)))))

and =° calls it (:1174–1183):

  (define ((=° u v) s)
    (define post°
      (λ1-match/first
        ((,s* ,assocs)  (cond
                          ((μkanren-state-equal? s s*) (✓° s*))
                          ((μkanren-post-unify s* assocs) => ✓°)
                          (else (✗° s*))))))
    (cond
      ((μkanren-unify u v s '()) => post°)
      (else (✗° s))))

Read post° clause by clause. If unification returned the very state it was given (μkanren-state-equal? is the eq? test of Proposition 10.3), nothing was bound, so no hook runs and no constraint is handed on; this is why invariant E1 of Section 11.4.6 matters. Otherwise the bindings assocs go through every extension’s post, in registration order, each one receiving the state and bindings the previous one answered; then μkanren-repost hands on the constraints of the variables bound (Section 10.5.4). A #f anywhere fails the =°.

This is how A1(c) is met without opening the binding site: every binding reaches the store through some =°, micro’s included, and every =° ends in μkanren-post-unify. The binding is checked a moment after it is made, but before any other goal can see it. Running post before the constraints are handed on, not after, matters for two reasons: its own bindings must be handed on too (E3), and the λ layer moves a disequality prefix that has come to hold a λ-term out of D before micro posts it again with its plain trial (E4).

Pitfall (A goal that unifies on its own must end in μkanren-post-unify). The guarantee “every binding is checked” holds because every goal of micro that commits a binding to the search state is an =°; micro’s other calls of the unifier are trials whose states are thrown away (in ≠°, in absent°, in subsumption) or reification. A goal of an extension that calls μkanren-unify and returns its state bypasses post exactly as Trick 1’s bind/raw bypasses the stores (Section 10.9.2): an eigenvariable could reach an older variable unchecked, and the constraints of the variables bound would not be handed on. Such a goal must pass the state and the exact new bindings to μkanren-post-unify, which is why it is exported; the λ layer does so at ∀° exit (Section 11.4.4).

diseq lets an extension claim a disequality (:1185–1192):

  (define ((≠° u v) s0)
    (let1 (s (μkanren-state-index s0))
      (cond
        ((not s) (✗° s0))
        ; an extension may take the disequality over, when its terms are involved.
        ((and (pair? μkanren-extensions) (μkanren-extension/diseq u v s)) => (λ (r) (if (eq? r 'fail) (✗° s) (✓° r))))
        ((μkanren-unify u v s '()) => (λ1-match/first ((,s* ,d) (if (μkanren-state-equal? s s*) (✗° s) (✓° (μkanren-add-prefix d s))))))
        (else (✓° s)))))

#f leaves u≠vu\ne v to the store D, a state keeps it in the extension’s store, 'fail says that uu and vv are already equal. A separate hook is needed because a D prefix is a list of bindings: the mgu of a pattern trial can contain variables the trial itself created, which are existential inside the negation (the ∃ of item A8), and a prefix cannot express that. ≠° is not the only source of prefixes on master: an absento with a variable datum posts disequalities with the nodes of its term, a type turns the absentos of its variable into prefixes, and the indexing of a raw state posts its prefixes again. Each of these goes through μkanren-extension/prefix (:285–293), which hands a prefix whose terms hold an extension’s term to the diseq hook, as the disequality of its two sides, with the flag absento when an absento posts it, so that the extension reads it as it reads absence. The prefixes that =° posts again when it binds one of their variables do not: they are the post hook’s to move first. Together these keep E4: D holds no extension term.

tag decides a type goal (symbol°, number°, a type made by define-μkanren-tag) on an extension term. Without it such a goal failed on every record that is not of the type, so (symbol° (@ F 'a)) failed even though F:=λz. zF:=\lambda z.\, z would make it a symbol; now the λ layer makes it wait. Every type goes through μkanren-post-type, the type goals and the types that =° hands on alike (:985–991):

  (define (μkanren-post-type u tag s)
    (let1 (u* (μkanren-state-find u s))
      (cond
        ((μkanren-var-working? u*) (μkanren-post-A u* tag s))
        ((μkanren-extension/hook u* μkanren-extension-tag) => (λ (tag-hook) (tag-hook u* tag s)))
        ((μkanren-tag-pred? tag u*) s)
        (else #f))))

watch is told of every prefix that D takes, with its id (:936). Micro’s records list a prefix under its left sides and under its right sides that are variables; the variables below a compound right side, which a later binding may bind to an extension’s term, are listed nowhere. The λ layer’s hook puts them in its own index W, so that its post hook can find the prefixes that a binding reaches by looking at the bound variables only, never at all of D. It was added in d501822, which made that migration linear (Section 14.4).

parts says where absent° looks into an extension term: a list of parts, or 'stuck when the term cannot be looked into yet, in which case absent° watches it whole, like a variable. Micro walks record slots, so without the hook (absent° 0 q) would reject λx.x because of the index 0 in its body, as it did in d1. With projecting true, the same hook tells the projection of T on an answer which parts’ constraints the answer keeps, instead of splitting a λ-term into its raw slots (:840–850):

  (define (μkanren-absent-parts u s)
    (cond
      ((μkanren-extension/hook u μkanren-extension-parts) => (λ (parts) (parts u s)))
      (else (μkanren-compound->list u))))

Its call sites are absent° and the absentos that =° hands on, through μkanren-absento+ and μkanren-absento/term+ (both read 'stuck as “watch”), and μkanren-project-T, through the twin μkanren-project-parts.

value and repr give the deep value of an extension term and the Scheme expression that rebuilds it; walk is passed so that the hook can recurse on the parts. They are called by μkanren-state-find/value and /repr, so β-normalisation applies wherever micro deep-walks: answers, the stores in answers, project° and aggregation (:531–534):

            ((and (record-instance? w*) (not (μkanren-var? w*)))
              (cond
                ((and (pair? μkanren-extensions) (μkanren-extension/term w* w*)) => (λ (e) ((μkanren-extension-value e) w* A s)))
                (else (apply make-record-instance (map A (μkanren-structure->list w*))))))

terms and forms give the extension a say in the answer. terms returns the terms of its residual constraints whose variables the answer should name: micro reifies them after the answer, so a residual prints α, β instead of _2. forms returns the forms its constraints add to the answer’s body, after micro’s own (:762–766, :779–780):

    (let* ((w* (μkanren-state-find/value w s))
           (extra (μkanren-extension/terms s)))
      ; the variables of the extensions' residual constraints are named too, after those of the answer.
      (match1/first ((,s* ,c ,vars-reversed ,assocs) (μkanren-state-reify (if (null? extra) w* (cons w* extra)) s))
               (X**   (μkanren-extension/forms s s*))
               (body  (μkanren-form w** D** A** T** X** s*)))

environment names the environment in which °->list/ground evaluates answers: that of the last extension that names one, else micro’s own (:306–309, :1402). The λ layer gives its own module environment, where ƛ, @ and ≐ are bound, so a ground answer evaluates back to a live λ-term that can be applied again (the pedagogy graft from d3).

                         (let ((E (eval `(lambda ,(cadr expr) ,(last expr)) (μkanren-extension/environment)))

11.4.4The primitives

Besides the registry, the protocol exports what a hook needs and micro alone did not export.

(μkanren-state-forget α s) unbinds α\alpha (:395–402):

  (define (μkanren-state-forget α s)
    (let1 (S (μkanren-state-S s))
      (μkanren-state-with/S s (μkanren-state-vars-count s) (update/sbral (μkanren-var-index/sbral S α) *μkanren-unbound* S)
                            (μkanren-M-admit (μkanren-state-M s) (μkanren-var-index α)))))

A post hook uses it to take back a binding that =° has just made, turning it into a constraint of its own, and leaves that binding out of the bindings it answers. Since post runs before the constraints are handed on, the stores never see the binding. The λ layer needs this when the scope check of X:=tX:=t cannot be decided yet, because tt contains a non-pattern that only a later binding can resolve: the binding becomes the suspended equation X≐tX\doteq t, as Teyjus would delay it. For instance ∃q ∃G ∃H ∀y. q=G (H y)\exists q\,\exists G\,\exists H\,\forall y.\ q = G\,(H\,y) leaves q unbound with a residual; a later G:=λa. 𝗄G:=\lambda a.\, \mathsf{k} solves it with q=𝗄q=\mathsf{k} (Chapter 12). The last argument is the one point where the merged forget is not the prototype’s. Another binding of the same unification may have written α\alpha into S while α\alpha was bound, and since commit d5b6f34 M decides whether the binding site walks a value at all. A forget that left M as it was would let a later binding of α\alpha to such a value skip its occurs check and build a cyclic substitution; so forget makes M admit α\alpha. The repro (forget-M.scm, kept with the gate logs) gave one cyclic answer with the prototype’s forget and none with this one, and test/extension/forget pins it (Section 14.4).

μkanren-unify (:480–483) is the unifier the hooks call; its answer keeps the stores as they are, so it must go through μkanren-post-unify, shown above, unless it is a trial whose answer is thrown away. μkanren-post-unify is exported for goals of an extension that unify on their own and must then run the same chain as =°. The λ layer calls it at ∀ exit, where the raising of the variables of a residual constraint makes new bindings that must wake the suspended equations and be handed on.

(μkanren-state-remove-D drop? s) (:404–410) removes from D the prefixes an extension takes over, and μkanren-state-no-D? (:367–369) tells cheaply that D never held a prefix, so that a query without disequalities pays nothing for them in the λ layer’s post hook. The readers of :371–379, exported with the watch hook, let the hook look at the prefixes a binding reaches by id: whether the stores are indexed, the prefix of an id, the ids that the record of a variable lists, and a copy without one prefix.

11.4.5The absento of a variable datum

The third review of the prototype found a defect of micro itself, independent of λ-terms. Micro decided an atom against an absento datum with equal? only, although a datum that holds a variable may still become that atom. With the micro of f53bdcb it printed the answers below (recorded then, not run again; those of the merged tree follow the next paragraph):

(pretty-print (°->list #f (fresh° (q D) (absent° D q) (=° q 'a) (=° D 'a))))
(pretty-print (°->list #f (fresh° (q D) (=° q 'a) (=° D 'a) (absent° D q))))
(pretty-print (°->list #f (fresh° (q D) (absent° D q) (=° q 'a))))
((λ () 'a))
((λ () 'a))
((λ () 'a))

The first two answers claim that a is absent from a. micro.diff fixed it by deciding such an atom by μkanren-tag-unify and watching it while pending. master fixed it on its own, before the merge, in commit 9cecddf: an absento whose datum holds variables is posted as faster-miniKanren posts it (Section 10.5). So the merged protocol carries no change to absent°. On the merged tree:

()
()
((λ () 'a))

The third answer stays, correctly: D is not in the answer and can be chosen different from a. 9cecddf brought a new route into D, though: the disequalities that such an absento posts bypass ≠°, so in a port that hooked only ≠° they could put a λ-term in D, which the reification of the answer then could not read. The merged protocol routes them through μkanren-extension/prefix, with the flag absento (Section 11.4.3).

11.4.6The invariants a client keeps

Micro’s records keep the invariants I1–I6 of Section 10.5. A client of the protocol keeps six more, E1–E6, written next to them (:108–121).

Definition 11.13 (Protocol invariants). (E1) eq?-entailment. A hook that changes nothing returns the very state object it was given: ≠° and the trials of D decide entailment by eq?.

(E2) Extended bindings. The assocs that a unify, occurs or post hook answers list every binding it made, pruning and lowering included, since =° hands on the constraints of those only; a binding taken back by μkanren-state-forget is left out.

(E3) Post first. The post hooks run before =° hands the constraints on or indexes the stores, so that the bindings they add are handed on too.

(E4) D holds no extension term. A prefix whose terms hold an extension’s term goes to the diseq hook; a binding that brings such a term into a prefix already in D is the post hook’s to find, before the constraints are handed on, with the records and the watch hook.

(E5) X alone keeps the index. A copy that replaces X alone keeps the stores indexed.

(E6) X everywhere. Every constructor of a state carries X along, which the engine never reads.

E1 is Proposition 10.3 carried over to the hooks. Micro reads “unification gave back ss” as “the terms are already equal”: ≠° then fails, =° hands nothing on, and the re-posting of a D prefix declares it violated. A hook that rebuilt an unchanged state would make (≠° (ƛ (a) a) (ƛ (b) b)) look satisfiable (the λ analogue of (≠° 1 1) in the pitfall after Proposition 10.3). For the λ layer this has a concrete consequence: the names that the ξ rule opens under binders live outside the state, so a ξ step that binds nothing returns ss itself. So the λ disequality below is recognised as an equality that already holds, and fails, exactly as micro’s (≠° 1 1) does:

(pretty-print (°->list #f (fresh° (q) (≠° (ƛ (a) a) (ƛ (b) b)))))
(pretty-print (°->list #f (fresh° (q) (≠° 1 1))))
()
()

E2 is what keeps the stores honest. μkanren-repost hands on only the constraints of the variables that appear among the new bindings; a binding made by a hook and not reported would leave a violated disequality in D. This is Trick 1’s lesson (Section 10.9.2): a state produced by unification must go through the chain with its exact bindings. E3 and E4 are the two reasons why post runs first, given above. E5 is what lets an extension write X at every step without making micro verify its stores again, and E6 is what a new constructor of micro must remember: the port onto the records found seven places to thread X through, and μkanren-state-with ignores a key it does not know, so a port that missed X: lost levels, Γ\Gamma, E and N without an error.

Pitfall (A hook that forgets a binding must also drop it from the bindings). E2 has a converse. When post takes a binding back with μkanren-state-forget, it must remove it from the bindings it answers; otherwise micro would hand on, from a variable that S no longer binds, the constraints of its record. The λ layer’s μkanren-enforce does both, through μkanren-drop.

11.4.7From closed points to hooks

Table 11.6 reads the protocol against Table 10.2: for each closed point of (aux kanren micro), what the protocol opens and what it leaves closed on purpose.

closed point (Table 10.2)opened bystill closed
the field list of the state, its constructorsthe field X, carried by every constructor (E6)the records of the variables
the unification condunify in the structure–structure clause and after pair–pairthe variable clauses, pair–pair
the binding site μkanren-state-updateatom? inside the occurs check; occurs on the failure path; the scope check moved to postvar–var orientation (older to newer); the sparing by M
the post-=° chainpost, threaded; μkanren-post-unify, μkanren-unify, μkanren-state-forget exported—
the storesdiseq and μkanren-extension/prefix for D, watch and the prefix readers, tag, partsthe records, I1–I6
reification (D/A/T only)value, repr, terms, forms; parts in projection modepurification and subsumption of micro’s stores
°->§: fixed empty initial statenot needed: X = '() means empty; environment for ground answersfixed query index 0
Table 11.6: Closed points of (aux kanren micro) and the hooks that open them.

The three needs listed at the end of Chapter 10 correspond to three rows: “a named place in the state” is X, “a call after every binding” is post, and “a say in reification” is value, repr, terms and forms. The rest of the protocol exists because micro’s stores and occurs check, written for first-order data, look into records slot by slot.

11.4.8The show module’s own extensions

(aux kanren micro show) reads answers back without eval, as data, constraints and a cells diagram (Section 10.7). The prototype taught it the forms of λ with show.diff, which hard-coded ƛ, @, ≐, ∃ and ∀ in show. The merge replaced that diff by a registry of show’s own (commit e97f7ef, aux.kanren.micro.show.scm:40–71), built like micro’s: a μkanren-show-extension has three hooks, each a procedure or #f, and registering again under the same name replaces it.

  • datum (r D) reads a rebuilding expression of its own, given the reader D for the parts;
  • constraint (c C R) reads a form of its own, given the readers for forms and expressions, and is asked before micro’s forms are, since λ’s denials look like micro’s;
  • cell (v) tells the cells view that a datum is one of its terms, as a label, its binders and labelled edges to its parts.

The λ layer registers μkanren-λ-show-extension when it is loaded (aux.kanren.lambda.scm:1250–1273), so it imports the show module. With no extension registered a reading costs a test of the empty registry, and the views are as before.

Tutorial (One =° on a λ-term, through micro and the hooks). To watch the protocol at work we re-register the λ extension under its own name with some hooks wrapped by a printer. Registering under the same name replaces it (Section 11.4.2). Micro exports no accessor of the hooks, so the script reads the slots of the registered record directly, with record-instance-slot of (chicken memory representation) (imported with srfi-1, besides (aux base), (aux stream), (aux kanren micro) and (aux kanren lambda)); this is for tracing only. The script runs with csi -s, which prints nothing but what the script prints.

(define fields '(name term? atom? unify occurs post diseq tag watch parts
                 value repr terms forms environment))
(define (orig h)
  (record-instance-slot μkanren-λ-extension (list-index (λ (f) (eq? f h)) fields)))
(define (D t) (if (μkanren-λ-term? t) (μkanren-datum t) t))
(define (B as) (map (λ (p) (list (car p) ':= (D (cdr p)))) as))
(define (say . xs) (display "  ") (for-each display xs) (newline))
(define traced
  (make-μkanren-extension 'λProlog     ; same name: replaces the λ extension
    term?: (orig 'term?)
    atom?: (λ (u) (let1 (r ((orig 'atom?) u))
                    (say "atom?  " (D u) " => " r) r))
    unify: (λ (u v s as)
             (say "unify  " (D u) " =? " (D v))
             (let1 (r ((orig 'unify) u v s as))
               (say "unify  => " (and r (B (cadr r)))) r))
    occurs: (orig 'occurs)
    post: (λ (s as)
            (say "post   " (B as) " at depth " (μkanren-λ-depth s))
            (let1 (r ((orig 'post) s as))
              (say "post   => " (and r (B (cadr r)))) r))
    diseq: (orig 'diseq) tag: (orig 'tag) watch: (orig 'watch) parts: (orig 'parts)
    value: (orig 'value) repr: (orig 'repr)
    terms: (λ (s) (let1 (r ((orig 'terms) s)) (say "terms  => " r) r))
    forms: (λ (s s*) (let1 (r ((orig 'forms) s s*)) (say "forms  => " r) r))
    environment: (orig 'environment)))
(μkanren-extension-register! traced)
(pretty-print (°->list/datum (fresh° (q) (∀° (x) (=° (@ q x) `(g ,x ,x))))))
(pretty-print (°->list #f (fresh° (q) (∀° (x) (=° q x)))))
  unify  (@ _0 (eigen x)) =? (g (eigen x) (eigen x))
  atom?  (ƛ (x) (g x x)) => #f
  atom?  (bvar 0) => #t
  atom?  (bvar 0) => #t
  unify  => ((_0 := (ƛ (x) (g x x))))
  post   ((_0 := (ƛ (x) (g x x)))) at depth 1
  post   => ((_0 := (ƛ (x) (g x x))))
  terms  => ()
  forms  => ()
((ƛ (x) (g x x)))
  atom?  (eigen x) => #t
  post   ((_0 := (eigen x))) at depth 1
  post   => #f
()

The first query, pi x\ F x = g x x, step by step.

  1. ∀° raises the depth to 1 and makes the eigenvariable x of level 1; q is _0, of level 0.
  2. Micro’s =° calls μkanren-unify. Both sides are walked: the left one is an application record, the right one a pair. No variable clause applies, the left side is a structure but the right one is not, and the pair–pair clause does not apply: the clause after it finds the owning extension and calls unify.
  3. The hook head-normalises both sides. The left one is flexible, _0 applied to the pattern (x): one eigenvariable, whose level 1 exceeds the level 0 of q. So this is flex–rigid. Variable elimination replaces x by the bound variable of the new abstraction, and the hook calls micro back to bind _0 := (ƛ (x) (g x x)).
  4. That binding goes through micro’s binding site and its occurs check. The value is new, not a part of S, so the check walks it: it looks into the abstraction (atom? is false) and stops at each (bvar 0) (atom? is true). No occurrence of _0: the binding is made, and the hook returns it.
  5. Back in =°, the state has changed, so μkanren-post-unify runs the post hook on the new binding. Levels exist, and _0 is below the highest level reached, so the scope check runs: the bound term holds no eigenvariable of level >0>0 (x has become an index), and no variable to lower. The binding passes; E is empty, so nothing is woken, and D never held a prefix, so nothing migrates. Then micro hands on the constraints of _0, which has no record.
  6. The ∀° body has answered; ∀° gives the state back depth 0 and discharges the constraints mentioning x (there are none).
  7. Reification asks the extension for the terms of its residual constraints (none) and for its forms (none); the value and repr hooks, not traced here, print the abstraction.

The second query, sigma Y\ pi x\ Y = x, never calls unify: q is a variable, so micro’s variable clause binds it directly. The occurs check meets the eigenvariable, an atom, and does not look into it. Micro makes the binding _0 := x; but the post hook sees that x has level 1 and _0 level 0, which violates condition (2) of A1, and answers #f. =° fails before any other goal could see the binding. This is A1(c) at work: the binding was made by micro’s own clause, and the extension still had the last word.

11.4.9What changed between micro.diff and the merge

The design is the prototype’s; the code had to follow a micro that changed under it. Twenty commits of src/aux.kanren.micro.scm separate f84cf9c from 5f406fd, and micro.diff failed 12 of its 19 hunks on the latter. The protocol was ported by hand onto the new sources, and these are the points where the merged one differs:

  • the state has nine fields, not seven, and X is threaded through every constructor of the records’ state (E6), not two positional ones; a copy that replaces X alone keeps the stores indexed (E5);
  • the hooks use the internal μkanren-unify, now exported, since the exported μkanren-state-unify answers raw states that the next goal indexes again: measured on master, with nn = 10, 100 and 1000 variables carrying a ≠°, an absent° and a symbol° each, =° after a copy that leaves the stores raw costs 0.07, 1.4 and 101 ms, and after μkanren-state-unify 0.08, 1.8 and 148 ms, against 4–5 µs on an indexed state;
  • post runs before μkanren-repost, the handing on of constraints that replaced the verification of D/A/T (E3);
  • the diseq hook takes an absento argument, and every prefix that holds an extension’s term goes to it through μkanren-extension/prefix (E4; Section 11.4.5);
  • the tag hook sits in μkanren-post-type, the one place every type goes through;
  • μkanren-state-forget makes M admit the variable it unbinds (Section 11.4.4);
  • watch and the prefix readers are new, for a migration of D per binding;
  • the change to absent° is gone, since master made it first;
  • μkanren-extension?, μkanren-extension-name and μkanren-answer-environment are no longer exported, and E1–E6 are written into micro next to I1–I6.

11.4.10Cost

Section 14.3 gives the cost of the protocol on first-order search, measured by the whole test of the merged tree with binaries compiled by csc -O2 -d1: master before the merge (5f406fd) against the merged tree (c0ff08c), without and with (aux kanren lambda) loaded but unused. With no extension the protocol costs 0.0% to 2.2% on the benchmark rows of 25 ms or more, but for three rows of about 30 ms of bench-big.scm that run 1 ms (3.3%) slower. That is the price of the slot X, allocated with every state, and of the tests of the empty registry. With the λ extension loaded, the searches without stores cost 0.3% to 1.5%, and the disequality-heavy perm6 and perm7 12%: the remainder is the post hook’s look at the bindings that reach a prefix of D. One cost is not removed and is documented: once any ∀° has run, levels exist, and every later binding below the top level gets the scope check, which costs first-order search about 2.2 times (Section 14.3.4).

11.5Review history

After the choice of d2 and the grafts, the proposal went through three adversarial review rounds. Each round attacked the proposal itself with hand-written probes and with randomly generated goals, run with their conjunctions in both orders. Every report was first reproduced, then fixed, a code fix with a regression case (in round 3 each new case was checked to fail on the proposal before the fix).

roundreportsregression casestypical defects
11312 (44 assertions)disequality prefixes holding an eigenvariable left in D (a free (eigen x) printed, a crash); pruning inside an argument that a non-pattern may drop; occurs check not modulo β; raw record slots in projected absento; a binder hint capturing cons in ground answers
286 (31 assertions)raising at ∀ exit not closing every constraint; η-redexes created by later bindings; occurs failure on non-rigid arguments; the extensional reading absorbed by T; first-order cost after a ∀°
3129 (53 assertions)non-patterns with functional arguments; disequalities over unreachable arguments; absento of an eigenvariable under a type; user types on λ-terms; η-short occurs check; a datum reducing to an atom; two types on one flexible term; first-order cost with D or A non-empty; λ-terms in the show module’s cells view
Table 11.7: The three adversarial review rounds (design notes, §10.4–10.6).

All 33 reports were real. In round 1 the twelve code defects were fixed, each pinned by a case, and one documentation error was corrected. In round 2 two reports were one defect; six were fixed with regression cases, and the seventh, the cost of first-order search after a ∀°, was measured and documented rather than changed, since the cheap fix would give up the guarantee that host code cannot smuggle an eigenvariable into an older variable. In round 3 three pairs of reports were one defect each; all nine defects were fixed with a regression case each. Round 3 also produced the generic change to absent° of Section 11.4.5, which master later made on its own. The defects themselves belong to the λ layer and are discussed where it is described (Chapter 12).

The merge brought a fourth round of a different kind. Each of its commits was reviewed before the next one was written, against a gate of differential runs, mutants and benchmarks, and a re-validation of the prototype on the new micro came first. That work found three defects the three rounds could not have seen, since they came from the changes of micro: the cycle that the prototype’s μkanren-state-forget builds under M, the λ-terms that the new absento could put in D, and the leaks of eigenvariables through the bodies of aggregations, which master had already fixed. It also found that the migration of D was quadratic, and that the show module crashed on some λ disequalities. Section 14.4 tells that story.

11.6Summary

  • The requirements are nine acceptance items: the scope of ∀ under Nadathur, Jayaraman and Kwon’s binding conditions, for every binding (A1); augment with the book’s clause order and variable sharing (A2); type inference as the test of ∀ and ⊃ together (A3); λ-tree syntax with α, β and η (A4); LλL_\lambda unification with mgus and delayed non-patterns (A5); λProlog’s answers where Ma and Friedman differ (A6); the book’s programs (A7); micro’s stores on λ-terms (A8); micro’s suites unchanged (A9). Order independence runs through all of them. They are pinned by 83 cases and 320 assertions, 93 and 421 in the merged suite.
  • Of the four meanings of =° on λ-terms, pattern unification with universe levels is retained: it is λProlog’s, it is decidable and unitary (one state per =°), and levels give generic for one integer per variable and one comparison per binding.
  • Three prototypes were built: a layer with no edit (d1), a hooks protocol (d2), a native engine (d3). d1 cannot check bindings made by micro’s =°, so eigenvariables leak through cons°; d3 had a crash and an η bug that made ≠° unsound; d2 had seven non-soundness defects. The reviews scored them 15.5, 23 and 21; d2 became the base, and d3’s pedagogical strengths and d1’s precision were grafted onto it.
  • The protocol, merged by commit 26b4708, adds a slot X that micro carries through every constructor and never reads, a global registry of extensions dispatched by term?, and fourteen hooks: atom? and occurs in the binding site, unify in the unification cond, post in the chain after =°, diseq, tag, watch and parts in the stores, value, repr, terms and forms in reification, environment in the runner. The show module has a registry of its own, with three hooks.
  • The scope check lives in post: every binding passes through some =°, and every =° ends in μkanren-post-unify, which runs the hooks before the constraints of the bound variables are handed on. An extension goal that unifies on its own must end in μkanren-post-unify too. μkanren-state-forget lets post turn a binding into a suspended equation, and makes M admit the variable it unbinds.
  • A client keeps E1–E6: it returns the very state when it changes nothing, reports every binding it makes, runs before the constraints are handed on, keeps its terms out of D, and carries X.
  • The prototype’s edit was +235/−41 lines; merged onto the micro of the records it is +286/−65 and +31/−9, λ-agnostic, and costs 0–2.2% on first-order search with no extension loaded (1 ms more on three rows of about 30 ms); micro’s 187 cases pass unchanged with and without the λ layer. Three adversarial rounds sent 13, 8 and 12 reports, all real; every defect but one documented cost was fixed with a regression case.