Chapter 14
Limitations, costs and the merge
What and why#
Chapter 11, Chapter 12 and Chapter 13 presented the proposal from the inside. The first gave the
extension protocol added to (aux kanren micro), the second the module (aux kanren lambda) built on it, and
the third the book’s programs running beside their λProlog originals. This chapter looks at the proposal
from the outside, as a reviewer does before and after a merge. It asks five questions.
- How do we know it works? What the test suites check, how a case is written, and what a green run does and does not establish (Section 14.1).
- Where does it differ from λProlog? Nine documented limitations and deviations, each pinned by a test case, most with a small run (Section 14.2).
- What does it cost? The measured overhead on first-order search, after a
∀°, and on λ workloads, and where that time goes (Section 14.3). - How did it enter the repository? The five commits of the merge, what changed against the prototype, the defects the merge found and fixed, and what is still open (Section 14.4), then six later work items (Section 14.5).
- What must the author decide? The questions that only the maintainer of
auxcan answer (Section 14.6).
The module is merged. It lives in src/aux.kanren.lambda.scm, its suites in
src/test/microkanren-lambda*.scm, and the protocol in src/aux.kanren.micro.scm; the
prototype stays in doc/hol-kanren/prototype/, frozen at commit f84cf9c and superseded,
because this document cites it. Every Scheme snippet below was run on the merged tree, master at
c0ff08c, and its output is pasted verbatim. The snippets import (aux base),
(aux stream), (aux kanren micro), (aux kanren micro show) and (aux kanren lambda). The figures of the
“whole test” come from a run of every suite, differential, mutant and benchmark on that tree,
against master before the merge (5f406fd); its logs are kept outside the repository.Page numbers “p.N” in the comments of the prototype and of the module are PDF pages (see Section 1.5).
14.1How the module is tested#
14.1.1Three layers of tests#
The tests come in three layers, each with its own job.
- Acceptance (A1–A9). The acceptance criteria that the three prototypes shared, these cases say what the module must
do: the scope of
∀, hypothetical clauses, type inference, object-level substitution, unification, the differences from Ma and FriedmanWeixi Ma and Daniel P. Friedman. A new higher-order unification algorithm for Kanren. In miniKanren and Relational Programming Workshop, 2021, the larger programs of the book, and micro’s stores on λ-terms. A9 says that micro alone has not changed. - Regression (R, R2, R3, R4, S). The proposal went through three adversarial review rounds, which sent
thirteen, eight and twelve reports. Every report was reproduced before it was fixed, and every code fix
came with a regression case; each case of the third round fails on the code before its fix. Several reports turned out to describe the
same defect, and two were documentation errors or a cost, not code defects. So the rounds left 12, 6
and 9 cases. The merge added three groups: R4 (six cases with hand-checked answers on the defects the
re-validation found), S (three cases of the show module’s reading of λ-terms), and one more case in R,
R/D-migration-reach, for the migration of D per binding. - Limits. A separate suite,
microkanren-lambda-limits.scm, pins what the module does not do, or does differently from λProlog. Its opening doc string reads “Known limits of (aux kanren lambda), each pinned so that a change of behaviour is noticed.” When one of these cases fails, a limitation has changed, perhaps for the better, and the documentation must change with it.
Next to them, micro has a suite of its own for the protocol, test/microkanren-extension.scm
(6 cases), which runs in its own process because the registry is global and cannot be taken back: it
registers small extensions and checks the order of the hooks, the slot X and the
watch hook.
| group | subject | cases | assertions |
|---|---|---|---|
| A1 | ∀ scope: escapes, aliases, levels reaching clauses | 9 | 22 |
| A2 | ⊃ hypothetical clauses: scope, order, sharing; courses, jars, reverse | 8 | 21 |
| A3 | ∀ and ⊃ together: type inference, forwards and backwards | 3 | 8 |
| A4 | object-level substitution: cbn, β, copy, subst, existential generalisation | 4 | 9 |
| A5 | : flex–rigid, flex–flex, pruning, 8.G–8.M, non-patterns, η | 10 | 40 |
| A6 | Ma & Friedman 2021, case by case | 5 | 13 |
| A7 | de Bruijn, prenex, mappred, palindromes, Fischer’s CPS | 5 | 12 |
| A8 | micro’s stores on λ-terms: ≠°, absent°, types, printing, grouping | 11 | 65 |
| A9 | a first-order case inside the suite | 1 | 2 |
| R | the first review round, and the migration of D per binding | 13 | 56 |
| R2 | the second review round | 6 | 31 |
| R3 | the third review round | 9 | 53 |
| R4 | the merge: cycles under ∀°, handover and discharge, aggregation, printed forms | 6 | 65 |
| S | the merge: the show module on λ-terms | 3 | 24 |
microkanren-lambda.scm | 93 | 421 | |
microkanren-lambda-limits.scm | 6 | 13 |
14.1.2How a case is written#
A case is a list of assertions (⊦= expected actual) from (aux unittest). Every expected
answer was written by hand, from the book or from the logic, and none was captured from a run. This
matters: one prototype had a generated snapshot as its suite, which would have frozen its bugs as
expected answers. Here is the A1 case that tests escapes through an alias:
((test/A1/alias _)
; the escape through a younger variable is caught whatever the order of the bindings and their kind.
(⊦= '() (°->list #f (fresh° (q) (∀° (x) (fresh° (y) (=° q (list y)) (=° y x))))))
(⊦= '() (°->list #f (fresh° (q) (∀° (x) (fresh° (y) (=° y x) (=° q (list y)))))))
(⊦= '() (°->list #f (fresh° (q) (∀° (x) (fresh° (y z) (=° q (list y)) (=° y z) (=° z x))))))
(⊦= '() (°->list #f (fresh° (q) (∀° (x) (fresh° (y) (=° y q) (=° y x))))))
(⊦= '() (°->list #f (fresh° (q) (∀° (x) (=° (vector q) (vector x)))))))Three habits of the suite show here. First, the same property is asserted under several goal
orders. Conjunction must be commutative, and many defects found by the reviews broke exactly that: an
answer lost in one order of the goals and found in another. Since the merge, R4 asserts some properties
in every order of the goals, with a macro in-every-order that runs all the permutations.
Second, the runner states what is compared.
(°->list #f g) gives micro’s answer as rebuilding code, constraints included, while
°->list/datum gives plain data comparable with equal? against an answer quoted from the book.
An error is compared through its message. Third, comments cite the book’s page or the review report that
the case pins.
Tutorial (What the levels do in the second assertion). Both assertions encode , which has no proof: it would
need , and is quantified outside . Section 13.3 follows the first order, where
Check lowers when is made and then rejects . Here and
(Definition 11.1), and (=° y x) comes first. ,
the highest level reached (Definition 12.4), and a variable of level sees every
eigenvariable that exists, so is not checked (a fast path, Section 12.3.6). Then
(=° q (list y)) binds ; the check (Definition 12.8) walks to and finds
. No answer. The two orders fail at different bindings, for the same reason. The
other three assertions vary the route: a chain of two variables, a var–var binding in the other
direction, a vector instead of a list.
14.1.3micro’s own suites, run twice#
Acceptance item A9 lives mostly outside the module’s suite, which holds only one first-order case under
that name. A9 is micro’s six suites, 187 cases on the merged tree, run twice: the core suite and those of
aggregation, untagged terms, show, arithmetic and dates. The first run is make test-microkanren and its siblings, as before the merge. The second loads the module first, with
csi -R aux.kanren.lambda, so that the extension is registered while first-order code runs;
the target test-microkanren-with-lambda of src/Makefile does it, and make test
runs it after the module’s suites:
cd test && for t in microkanren microkanren-aggregation microkanren-untagged microkanren-show microkanren-arith microkanren-date; do ${CSI} -R aux.kanren.lambda -s $$t.scm || exit 1; doneThe prototype kept a second copy of the six suites that differed only in its import line; the merge
replaced the copy by this flag, so the suites cannot drift apart. The expectations are not touched, answer
order included. The suite of union-find tests (aux kanren unionfind), a separate engine that does
not import micro, so it is not run with the module loaded.
14.1.4The run#
The module is part of the egg and of src/Makefile, which builds and tests it with the rest
(make test), or alone:
cd src
make test-microkanren test-microkanren-lambda test-microkanren-with-lambdaOn the merged tree, built into a private repository with csc, nothing installed, the three
targets print, verbatim:
cd test && csi -s microkanren.scm
((ran 38) (failed 0))
cd test && csi -s microkanren-extension.scm
((ran 6) (failed 0))
cd test && csi -s microkanren-lambda.scm
((ran 93) (failed 0))
cd test && csi -s microkanren-lambda-limits.scm
((ran 6) (failed 0))
cd test && for t in microkanren microkanren-aggregation microkanren-untagged microkanren-show microkanren-arith microkanren-date; do csi -R aux.kanren.lambda -s $t.scm || exit 1; done
((ran 38) (failed 0))
((ran 16) (failed 0))
((ran 44) (failed 0))
((ran 16) (failed 0))
((ran 52) (failed 0))
((ran 21) (failed 0))That is cases of the module, the 6 of the protocol, and micro’s cases
run twice, cases in all, with 0 failures. The prototype’s run, at f84cf9c, had 89 cases of
the module and micro’s 125 run twice.
The whole test ran every suite of src/test, 77 entries (every line of the test target,
the six suites run again with the module among them, four more targets, and five files that no target
lists), on the merged tree and on master before the merge, built the same way. 73 entries pass on the merged tree.
63 suites give the same last line on both trees; microkanren runs 38 cases against 37, one being
C1’s new case; nine entries are new (the extension suite, the two λ suites, the six runs with the module
loaded) and pass. The four failures are the same on both trees and do not touch micro: a memory check of
the simdjson suite (test/simdjson/frees-the-tree), which also stops a plain make test at
its first line, and three files that no target lists, which exit with an error on both trees. 54 of the 56
modules build; the two that do not, aux.hwy and aux.judy, lack their C libraries here and
are commented out of the egg.
Pitfall (What a green run does not say). The suites are example-based. They show that the module gives the book’s answers on the book’s examples,
and that every defect found by review stays fixed. They do not prove soundness. The guarantees on pattern
problems come from the theorems the algorithm follows: Miller’s termination and most-general-unifier
resultsDale Miller. A logic programming language with lambda-abstraction, function variables, and simple unification. Journal of Logic and Computation, 1(4):497–536, 1991, the soundness and completeness of universe taggingGopalan 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,
and its levels formulationGopalan 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. The tests check that the code follows those
algorithms on the cases tried. Mutants measure how much they check: of five mutants of the soundness
review, which the prototype’s suites missed two of, the merged suites catch all five; one of them,
μkanren-state-forget leaving M as it was, makes the λ suite hang rather than fail, and micro’s
own suite reports it as a wrong answer (Section 14.4.4). And a passing limits suite is no good
news in itself: it means the limitations are still there.
14.2Limitations and deviations from λProlog#
λProlog is a typed language with its own implementation of the hohh search. (aux kanren lambda)
is an untyped library over a miniKanren with interleaving search and constraint stores that λProlog
does not have. Some departures follow from that: they are the price of the host. Others are choices that
could be revisited. Table 14.2 lists all nine, with the case that pins each. The
subsections take them in order.
| limitation | pinned by | |
|---|---|---|
| 1 | only dynamic relations take hypotheses; no predicate quantification | A2/static-relations |
| 2 | untyped: η only at abstractions, @ distinct from lists, β may diverge | limits/untyped |
| 3 | non-patterns suspended, never enumerated: floundering reported, not detected | limits/no-huet |
| 4 | answer order is micro’s interleaving | A7/prenex, A3/backwards |
| 5 | ≠°, absent° and types are extensions, with a chosen reading of ∀ | A8/diseq-extensional, R2/extensional-absent-order |
| 6 | host escapes: levels police logic variables, not Scheme values | limits/host-escape |
| 7 | binder names are hints; some projected constraints keep a working variable | A6/alpha, limits/absent-projection |
| 8 | costs: no indexing of E and N; the scope check after any ∀° | the benchmarks (Section 14.3) |
| 9 | the answer variable must be created outside every ∀° | R2/answer-inside-forall |
14.2.1Only dynamic relations take hypotheses#
In λProlog every predicate is dynamic: D => G may add clauses for any predicate, including one
that has static clauses in the program. Here only a relation defined with define-dynamic-relation
consults the context Γ, and assuming a clause for any other relation is an error. A ⊃° that
silently ignored such a clause would be worse, and all three prototypes did that.
(define-relation (r° x) (=° x 1))
(define-dynamic-relation (d° x) (=° x 1))
(error-message (λ () (°->list #f (fresh° (q) (⊃° ((r° 2)) (r° q))))))
(°->list/datum (fresh° (q) (⊃° ((d° 2)) (d° q))))"not a dynamic relation, see define-dynamic-relation"
(2 1)The dynamic relation answers 2 before 1, because hypotheses come first, most recent first, then the static body ([MN p. 78], Section 3.2).
Two consequences follow, both because clauses are Scheme closures and not formulas. A program cannot
build a clause as a term and then assume it. And there is no quantification over predicates, so the
book’s reverse, which hides its auxiliary rev under pi rev\ ... [MN p. 125–126]
(Definition 5.7), cannot be transcribed as it stands. The suite runs instead the fohh reverse of
Figure 3.4 [MN p. 87], which assumes the clauses of its auxiliary predicate but does not hide its name: here
rev° is a dynamic relation declared at top level, with no static clauses (A2/reverse). Roadmap item (e) addresses
predicate quantification (Section 14.5.5).
14.2.2Untyped terms#
λProlog’s terms are simply typed, and its unifier works on βη-long normal forms. The module has no types. It keeps terms η-short and η-expands one side only when the other is an abstraction, which is Miller’s treatment of the untyped caseDale Miller. A logic programming language with lambda-abstraction, function variables, and simple unification. Journal of Logic and Computation, 1(4):497–536, 1991. Three facts follow.
(°->list #f (fresh° (q) (=° (@ 'g 'a) '(g a))))
(μkanren-datum (ƛ (x) (@ 'g x)))()
g- λ-tree application
(@ 'g 'a)is not the list'(g a): the first is a term of the meta-language, the second Scheme data of the object language. Keeping them apart is what keeps conjunction commutative. One prototype conflated them and lost that property. - is built η-short as .
- Full β through
@on instantiated heads is not guaranteed to terminate on untyped meta-terms. With types, β-reduction would terminate.
There is also no check that a solution exists in a possibly empty type (Section 4.6). Roadmap item (f) addresses types (Section 14.5.6).
14.2.3Non-patterns are suspended, never enumerated#
Outside the module does what Teyjus does: it suspends the equation in the store E, retries it after every binding in case it has become a pattern, and reports it in the answer if it is still suspended (Section 7.9). It does not run Huet’s procedure (Section 7.4). Two runs show what this means:
(°->list #f (fresh° (q F) (=° q F) (=° (@ F 'a) 'b) (=° (@ F 'a) 'c)))
(°->list #f (fresh° (q F) (=° q F) (=° (@ F 'a) '(g a a))))((λ (α) (assert (≐ (@ α 'a) 'b)) (assert (≐ (@ α 'a) 'c)) α))
((λ (α) (assert (≐ (@ α 'a) (cons 'g (cons 'a (cons 'a '()))))) α))The second problem is the book’s Example 8.A (Example 7.5), , written with list data for the right-hand side. It has four unifiers and no most general one [MN p. 213]. The module does not choose: it answers that is any α satisfying the residual. That answer is correct but conditional.
The first problem shows the cost of not choosing. and have no common solution, since . Huet’s procedure would find that out, but the module only suspends both equations and returns an answer whose residuals are jointly unsatisfiable. This is floundering reported but not detected: the answer says what was left undecided, and it is up to the reader, or a later binding, to find out that it is empty. Roadmap item (d) would add an optional Huet search over E (Section 14.5.4).
14.2.4Answer order is micro’s interleaving#
λProlog searches depth-first, left to right; micro interleaves the branches of a disjunction. Where the
book lists answers, the two orders often agree: augmentation order [MN p. 78], the existential
generalisations [MN p. 203], the palindromes [MN p. 142], reverse, the course database (whose extra,
duplicate proofs come in the interleaving’s order), and the CPS term
[MN p. 257]. They differ on prenex, whose five answers [MN p. 196–197] come out as the book’s first,
third, second, fourth and fifth:
((all (ƛ (x) (all (ƛ (x1) (and (q x x) (q x x1))))))
(all (ƛ (x) (all (ƛ (x1) (and (q x1 x1) (q x x1))))))
(all (ƛ (x) (all (ƛ (x1) (all (ƛ (x2) (and (q x x) (q x1 x2))))))))
(all (ƛ (x) (all (ƛ (x1) (all (ƛ (x2) (and (q x1 x1) (q x x2))))))))
(all (ƛ (x) (all (ƛ (x1) (all (ƛ (x2) (and (q x2 x2) (q x x1)))))))))The difference also helps. Where depth-first search loops, interleaving finds answers that λProlog misses.
Asked for terms of type , typeof run backwards loops under depth-first search. Here it
enumerates terms:
((abs (ƛ (x) x))
(abs (ƛ (x) (app (abs (ƛ (x1) x1)) x)))
(abs (ƛ (x) (app (abs (ƛ (x1) x)) x))))The suite compares answer sets, through a sorted copy, wherever interleaving rather than logic decides the order. Where it compares a sequence against the book, the book’s order is the claim being tested.
14.2.5Disequality, absence and types under ∀#
λProlog has no disequality, no absento and no type constraints. micro has all three, so the
module had to decide what they mean when an eigenvariable is involved. For ≠° there are two
defensible readings of .
Definition 14.1 (two readings of an eigenvariable under ≠). Under the generic reading, an eigenvariable is the new constant introduced by generic (Rules A.6), distinct from every term the older variables can denote. Under the extensional reading, an eigenvariable stands for an arbitrary term of its universeEvgenii 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.
The generic reading is the default: it matches λProlog, where pi x\ not (q = x) succeeds, and it
behaves like αKanren’s nomsWilliam E. Byrd and Daniel P. Friedman. Kanren: 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. The extensional reading is chosen by the parameter
μkanren-λ-reading:
(°->list #f (fresh° (q) (∀° (x) (≠° q x))))
(parameterize ((μkanren-λ-reading 'extensional)) (°->list #f (fresh° (q) (∀° (x) (≠° q x)))))
(parameterize ((μkanren-λ-reading 'extensional))
(list (°->list #f (fresh° (q) (∀° (x) (fresh° (y) (≠° y x) (=° y 'a))) (=° q 'ok)))
(°->list #f (fresh° (q) (∀° (x) (fresh° (y) (≠° y x) (=° y `(f ,x)))) (=° q 'ok)))))
(°->list #f (fresh° (q) (∀° (x) (fresh° (y) (≠° y x) (=° y 'a))) (=° q 'ok)))((λ (α) α))
()
(() ((λ () 'ok)))
((λ () 'ok))Read them as statements about all .
- Generic, : is older than and can never denote it, so the disequality holds for good and vanishes from the answer.
- Extensional, : ranges over every term, ’s value included, so the disequality cannot hold for all and the goal fails.
- Extensional, : the instance refutes it. With it holds, since no term equals the list (occurs check).
- Generic, : is not the new name , so it holds.
Both readings were implemented so that the order of a binding and a disequality does not change the
answer. A8/diseq-extensional pins both orders of and , and
R2/extensional-absent-order pins four goal orders of , which fails in every order.
The reading has edges, and the proposal documents them. absent° and the types always use the generic
reading. A disequality keeps the reading in force when it is posted, with one exception. A first-order
disequality sits in micro’s store D, which records no reading. If it later migrates to the
module’s store N, because one of its sides came to hold a λ-term or an eigenvariable, it takes the reading
in force at the migration. The two readings then differ only if a program changes
μkanren-λ-reading between the two goals. Under the extensional reading, once a ∀° has run,
a first-order disequality goes to N at once, with its reading.
14.2.6Host escapes#
Levels police logic variables. A Scheme value that host code carries out of a scope is not a logic variable, and the levels know nothing about the route it took. The limits suite pins both halves of the story:
(define stash #f)
(°->list #f (fresh° (q) (∀° (x) (project° ((v x)) (begin (set! stash v) ✓°)))
(λ (s) ((=° q stash) s))))
(°->list #f (fresh° (q) (∀° (x) (project° ((v x)) (begin (set! stash v) ✓°)))
(∀° (y) (fresh° (z) (=° z stash) (=° q 'leaked)))))()
((λ () 'leaked))Tutorial (Why the first escape is caught and the second is not). In both goals the first ∀° raises the depth to 1 and creates with . project°
stores the eigenvariable record in a Scheme variable, and the scope exits, so the depth is back to 0.
- First goal: was created at depth 0. Binding is checked, and is a scope failure. The smuggled name cannot reach an older variable.
- Second goal: a second
∀°raises the depth to 1 again, and is created inside it with . Binding passes the check, since . A level is a depth, not the identity of a scope, so two sibling scopes at the same depth look alike.
Inside the logic no such program can be written: a variable created in a later scope never sees the
earlier eigenvariable, because it is out of its lexical scope. The escape needs project° and
set!. The point of the first case is that even this route cannot violate the quantifier prefix of
the older variables. That guarantee has a price, discussed in Section 14.3.4.
14.2.7Binder names are hints; projected constraints#
A λ-record stores an interned hint, the name the user wrote, for printing. Terms built alike are
therefore equal?, and they group in groupby°. α-variants written with different names are
not equal?, although they are α-equivalent, which ≐ and μkanren-α=? decide:
(list (equal? (ƛ (x) `(f ,x)) (ƛ (x) `(f ,x)))
(equal? (ƛ (x) `(f ,x)) (ƛ (y) `(f ,y)))
(≐ (ƛ (x) `(f ,x)) (ƛ (y) `(f ,y))))(#t #f #t)A hint that equal? ignored could not be stored in the record. The proposal chose to print answers
with the user’s binder names, and gave up equal? modulo α for that (Section 14.6).
The second half of this item is about answers. An absento on a flexible term whose head is in the answer is kept whole, and an argument out of the answer prints as a working variable:
(°->list #f (fresh° (q) (fresh° (Y) (absent° 'c (@ q Y)))))
(°->list #f (fresh° (q) (fresh° (F) (absent° 'c (@ F q)))))((λ (α) (assert (absent? 'c (@ α _1))) α))
((λ (α) α))The first answer says: there is some _1 such that does not occur in . It cannot
be weakened to an absento on alone: contains , yet with
the application reduces to . In the second answer the head is out of the answer
and may be a constant function, so the constraint is dropped. A disequality with such an argument,
(deny (equal? β (@ α _3))), is likewise kept in the answer (R3/diseq-unreachable-argument),
and so is an absento whose datum may still reduce to an atom of the answer; since 9cecddf micro
keeps an absento with a variable datum as disequalities of the datum with the parts of the term, so it prints
as the denial (begin (deny (≐ (@ α 'b) 'a))) (R3/absento-datum-reduces), where the prototype
printed (absent? (@ α 'b) 'a).
14.2.8Costs#
The engine pays for four things that λProlog implementations avoid. Every binding retries all the
suspended equations of E and the disequalities of N when they are not empty, with no index by variable
(the wake-up loop of Section 12.3.7). While D holds prefixes, every binding of a variable that one of
them reaches walks the bound value, to see whether a λ-term has come in (Section 12.5).
The scope check walks bound terms below the top level from the first ∀° on, for the rest of the
search, even after that ∀° has exited. And deeply nested binders scale quadratically.
Section 14.3 gives the figures.
14.2.9The answer variable outside every ∀°#
°->list reifies variable 0, the first one created. If it is created inside a ∀° and its
value holds that scope’s eigenvariable, no answer can be written without the eigenvariable. λProlog
reports no binding for a variable quantified inside pi x\ . The module raises an error instead of
printing an eigenvariable free:
(error-message (λ () (°->list #f (∀° (x) (fresh° (q) (=° q x))))))
(°->list #f (∀° (x) (fresh° (q) (=° q 'a))))
(°->list #f (fresh° (q) (∀° (x) (=° q 'a))))"the answer holds the eigenvariable of a ∀° it was created in: create the variable it reifies outside every ∀°"
((λ () 'a))
((λ () 'a))An answer that does not hold the eigenvariable is reported as usual, wherever its variable was created. The idiomatic form is the third one: create the query variable first.
14.3Performance#
All figures are in milliseconds, from the whole test of the merged tree. Each benchmark was compiled with
csc -O2 -d1 against the repository it runs on, and its variants alternated over five rounds, their
order rotated each round. Three variants are compared: master is master before the merge
(5f406fd), merged is c0ff08c with no extension loaded, and merged+λ is
c0ff08c with (aux kanren lambda) loaded, so its hooks are registered. The tables give the
median of the five rounds and, in the last column, the median of the ratios paired within a round. Other
users’ jobs ran on the machine during the test (load average 2 to 19), and single medians move in
clusters about 4–5% apart, so the paired ratios are the figures to read. Two controls bound the noise: a
row with no kanren (Fibonacci of 27 and a reversal of elements) stays at paired ratios of 1.00 to
1.02, and master’s binary run a second time against itself gives 0.98 to 1.02 on the rows of 25 ms or
more. The prototype’s figures, measured for the proposal on the micro of f84cf9c, are quoted where
they are compared.
14.3.1The protocol on first-order search#
With no extension loaded, the protocol costs 0.0% to 2.2% on every benchmark row of 25 ms or more of
the three first-order benchmark programs (bench.scm, bench-big.scm,
bench-step2.scm), with the exception of three rows of bench-big.scm of 29–30 ms, whose
paired ratios of 1.033 and 1.034 are 1 ms, one tick of the millisecond timer. That agrees with the
figure measured for its commit, 0.7% to 2.2%. It is the price of the slot
X, allocated with every state, and of the tests of the empty registry at the hook sites; none of
them sits on the variable clauses or the pair–pair clause of the unifier. (Table 14.3’s
medians of 358 against 340 ms are two clusters of the noise: paired, the rounds give 1.020.)
| benchmark (ms) | master | merged | paired |
|---|---|---|---|
append° backwards, 2000 answers, full | 5457 | 5543 | 1.009 |
| the same, search only | 340 | 358 | 1.020 |
open append°, 1000 answers, search | 1311 | 1369 | 1.009 |
perm6 with 15 pairwise ≠°, 720 answers | 165 | 162 | 1.013 |
perm7 with 21 pairwise ≠°, search | 1191 | 1198 | 1.015 |
14.3.2With the λ extension loaded#
(aux kanren lambda) loaded and unused. t is a variable
that append° does not use.| benchmark (ms) | master | merged+λ | paired |
|---|---|---|---|
append° backwards, search | 340 | 345 | 1.015 |
open append°, search | 1311 | 1314 | 1.003 |
append° backwards, full | 5457 | 5511 | 1.009 |
+ symbol° t | 353 | 356 | 1.014 |
+ absent° t | 354 | 352 | 0.994 |
+ ≠° t 1 | 353 | 379 | 1.074 |
perm6, 15 ≠° | 165 | 179 | 1.127 |
perm7, 21 ≠°, search | 1191 | 1323 | 1.124 |
≠° on 50 idle variables, then append° backwards on 500 | 30 | 37 | 1.267 |
| all-distinct, 100 variables bound one by one | 77 | 88 | 1.143 |
≠° store of 3000, then bind | 48 | 69 | 1.468 |
≠° and symbol° on 100 variables | 8 | 13 | 1.625 |
≠°, symbol°, absent° mixed on 100 variables, bound one by one | 8 | 19 | 2.375 |
Loaded but unused, the extension costs little where no disequality is kept: 0.3% to 1.5% on the
searches without stores, up to 8% with symbol° or absent°. Where disequalities are kept it
costs 4% to 47% on the rows of 25 ms or more, and more on short rows that bind many constrained
variables, up to 2.4 times on the 8 ms of the mixed row. The time goes to the post hook. After
every binding it looks for the prefixes of D that the binding reaches, through micro’s records and its own
index W, and walks the bound value of each such variable once, to see whether a λ-term has come into a
prefix (Section 12.5); then it retries the λ-disequalities of N, if any. The rows of
bench-step2.scm, larger stores bound one by one, cost 4% to 17%.
The prototype paid more here, because its hook walked every prefix of D whenever the new bindings were
too long to tell at a glance that they hold no λ-term. First-order search makes such bindings at every
step, to the tails of a list, so a store of disequalities cost walks. On the micro of
5f406fd, whose stores had become much faster than the prototype’s, that one look became the whole
cost: the gate of the commit that added the module measured the row “≠° store of 3000,
then bind” at 5332 ms with λ loaded against 62 ms without, 86 times, and the migration was about 4.9 s of
it. Commit d501822 made the look per binding; its gate measured 86 ms against 62, and the whole
test measures 69 against 48 ms.
14.3.3The migration of D, made linear#
5f406fd, which kept its migration,
against the merged tree, for three sizes . One run per round, medians of five rounds.| benchmark (ms) | port+λ | merged+λ |
|---|---|---|
a store of ≠°, = 500, 1000, 2000 | 131 / 565 / 2351 | 10 / 20 / 40 |
| the variable of prefixes bound to a λ-term, = 1000, 2000, 4000 | 565 / 2379 / 9857 | 27 / 54 / 110 |
| the same, bound to a long list | 582 / 2411 / 9897 | 24 / 49 / 100 |
| , then built pair by pair, = 1000, 2000, 4000 | 4 / 8 / 16 | 7 / 14 / 27 |
| ten such prefixes | 4 / 8 / 16 | 9 / 19 / 38 |
The table shows the shape of the change. The first three rows were quadratic and are
linear: at the largest size the merged tree is 59 to 99 times faster. The last two rows are the price.
A recursion that builds the open tail of a prefix one pair at a time makes, at every step, a binding that W
lists, so the hook walks its value and extends W; the port did nothing there, since its bindings were short
enough to be told apart at a glance. Both stay linear, at 1.7 and 2.4 times the port. Without λ loaded the
same programs run on the merged tree within 1 ms of master.
14.3.4After a ∀°#
The second review round measured first-order search that runs after some ∀° has run and exited.
In Table 14.6, pre is (∀° (z) ✓°), which binds nothing and exits at
once, and typeof° is one type inference of run before the search.
∀° has run, with λ loaded, on the merged tree. The
prototype measured 663 / 1104 / 1092 and 1296 / 2940 ms.| benchmark (ms) | no ∀° before | pre before | typeof° before |
|---|---|---|---|
append° backwards, 2000 answers, search | 362 | 815 (+125%) | 823 (+127%) |
open append°, 1000 answers, search | 1381 | 3060 (+122%) | — |
The absolute cost is what it was in the prototype, about 450 ms on append° backwards; it doubles
the search now because the search itself got twice as fast.
Tutorial (Where the time goes after a ∀°). Take one step of append° backwards on the list of 2000 numbers. It binds a variable to a
pair whose tail is a ground suffix of , which is already a part of a value of S.
- No
∀°has run. The level table is empty, no scope check runs, and micro’s occurs check is spared too: the bound value is held, and M tells that the variable cannot occur in it (Section 10.4). The binding walks nothing. prehas run. The depth went to 1 and back to 0, so the highest level reached is . The search’s variables are at level 0, below . Each binding of such a variable gets the scope check, whose allocation-freeμkanren-plain?walks the bound tail through the substitution. That walk is the whole difference: micro spares its own walk of the same tail, and the scope check has no such sparing.
Why not skip the check when the depth is back to 0 and nothing of a higher level is reachable? For logic variables that would be safe: an exited scope reaches a depth-0 binding only through constraints, which are checked when they wake. But an eigenvariable smuggled out by host code would then reach an older variable unchecked, which is the first case of Section 14.2.6. The cheap fix gives up that guarantee, so it was not made. The proper fix is to spare the scope check where micro spares its occurs check (Section 14.5.1). When the prototype measured this, micro’s occurs check still walked the tail too, and the plan was one walk for both checks.
14.3.5λ workloads#
Table 14.7 compares the merged module with the prototype and with the three prototypes of the design. The columns of the prototypes are the engineering review’s measurements on the same programs, on the micro of their time; the merged column is the whole test’s.
| benchmark (ms) | merged | proposal | d2 | d3 | d1 |
|---|---|---|---|---|---|
typeof of the Church numeral 400 | 210 | 254 | 441 | 105 | 385 |
copy of the Church numeral 400 | 200 | 256 | 442 | 116 | 314 |
typeof of 150 nested binders | 1266 | 1306 | — | 1409 | — |
copy of 150 nested binders | 1698 | 1745 | — | 1779 | — |
typeof backwards, 30 (term, type) pairs | 11 | 10 | 11 | — | — |
one pattern equation under 50 ∀ | 2 | 2 | 6 | — | — |
f84cf9c.The merged module is about 2.1 times faster than d2 on the Church numeral and twice as slow as d3. Against
the port of the prototype onto 5f406fd, measured in the same run, every λ workload is within 0.5%,
so the 17% gained over the prototype on the Church numeral is master’s micro, not the merge. The prototype’s
history on typeof of Church 400 shows where the time went before:
| step | ms |
|---|---|
| d2 ported, with instantiation that shifts only open terms | 463 |
allocation-free μkanren-plain? for the scope check | 330 |
| no check for bindings of variables at the top level | 311 |
the atom? hook: micro’s occurs check stops rebuilding eigenvariables | 254 |
The last step is worth explaining. micro’s occurs check rebuilds a foreign record as the list of its slots to look inside it. An eigenvariable holds no logic variable, so the hook lets micro skip it, and that alone saved 18%.
A profile of the prototype put the remaining time in micro’s walks, μkanren-state-find and its sbral
lookup. These are the var–var chains that the type variables of typeof form, since micro binds
the older variable to the newer, plus the occurs check of every binding of a subterm. Both are on micro’s
hot path, outside the extension’s reach. d3’s lead comes from its in-core binding, which does the occurs
check and the level check in one walk. Item (a) of Section 14.5.1, in its variant with a
verdict hook, is the closest the protocol comes to it. On 150 nested binders the merged module is
5–10% faster than d3. The module’s cost on nested binders grows quadratically with the nesting
(Section 14.2.8).
14.4The merge into the aux repository#
The proposal planned a merge in three stages: the protocol into micro, then the module and its suites,
then the show module, each reviewed and tested on its own. That plan met a moving micro. Between the
prototype’s commit, f84cf9c, and 5f406fd, twenty commits rewrote micro’s stores as records
by variable, spared the occurs check, posted an absento with a variable datum as faster-miniKanren does,
sorted the forms of answers, and fixed the aggregations. micro.diff failed 12 of its 19 hunks on
the new sources, and the module did not compile against them: five names of the protocol were unresolved.
So the merge began with a re-validation. The prototype was ported by hand onto 5f406fd and checked
by differential runs, adversarial probes, mutants and benchmarks; the design held, the code had to follow.
The merge itself is five commits on master, each reviewed against a gate of suites, differential
runs, mutants and benchmarks before the next one was written.
| commit | subject | what |
|---|---|---|
26b4708 | Open (aux kanren micro) to extensions | the protocol of Section 11.4: the slot X, the registry, thirteen hooks, E1–E6, test/microkanren-extension.scm; micro |
5be5f35 | Add (aux kanren lambda) | src/aux.kanren.lambda.scm (1298 lines), its suites and programs, the egg line, the Makefile targets; sorted residual forms, merged up to α |
d501822 | Move the prefixes of D to N per binding in (aux kanren lambda) | the watch hook, the index W, the prefix readers of micro: a linear migration |
e97f7ef | Read λ-terms in (aux kanren micro show) | show’s own registry of extensions in place of show.diff, which the module fills |
c0ff08c | Describe (aux kanren lambda) and the extensions of (aux kanren micro) in the README | the README’s section on the module and the protocol; doc/hol-kanren/README.md marks the prototype frozen |
5f406fd.The hashes are those of the commits as written, in a clone of the repository; they hold on
master if the series lands there by a fast-forward, as doc/hol-kanren/README.md, which
cites them, assumes.
14.4.1The five commits#
26b4708, the protocol. It is the protocol of Section 11.4: the slot
X threaded through every constructor of the new state, the registry, thirteen hooks, the
exports for the hooks, and the invariants E1–E6 written next to micro’s I1–I6. Its new suite,
test/microkanren-extension.scm, registers small extensions in a process of its own, since the
registry cannot be taken back, and checks the order of E3 and the replacement of an extension registered
again. test/extension/forget in micro’s suite calls μkanren-state-forget directly. Nine
mutants of the new code each fail one of the two suites. With no extension the answers are byte-identical
to 5f406fd, and the rows of bench.scm longer than 12 ms are 0.7% to 2.2% slower.
5be5f35, the module. The port of the prototype onto that protocol, with three changes
of its own. It no longer exports μkanren-repr->datum, which clashed with the export * of the
show module, so that which one a program saw hung on the order of its imports. Its post hook asks
μkanren-state-no-D? before it looks at the new bindings, so a query without disequalities pays only
the hook. And the forms of E and N are sorted, and kept once up to α (Section 12.6). The suites
are src/test/microkanren-lambda.scm with 88 cases, -limits.scm with 6, and the programs,
renamed microkanren-lambda-programs.scm. The egg gains
(extension aux.kanren.lambda (component-dependencies aux.base aux.stream aux.fds.sbral aux.kanren.micro))(e97f7ef adds aux.kanren.micro.show), and the Makefile the targets
test-microkanren-lambda and test-microkanren-with-lambda of Section 14.1.4, both
run by make test; make format indents the module. The new group R4 holds cases with
hand-checked answers for the defects of Section 14.4.3. Two expectations change, each in the
order of two forms, and one changed already in the port: R3/absento-datum-reduces, whose fourth case is now
the denial (begin (deny (≐ (@ α 'b) 'a))), the same constraint in the representation of
9cecddf. The migration of D was inherited from the prototype and not fixed here: the row
“≠° store of 3000, then bind” went from 62 to 5332 ms with λ loaded.
d501822, the migration per binding. The post hook now looks only at the prefixes
that a new binding reaches (Section 12.5): those that micro’s records list under the bound
variable, read with the new μkanren-state-prefix-ids, and those that the module’s index W lists, which
the new watch hook fills for every prefix that D takes. It walks the bound value once for all of
them. The first version of the commit walked the reached prefixes instead, and review found that this
made a recursion that extends the open tail of a prefix quadratic again (7033 ms at , against
22 ms before); the final version walks only the values. The answers do not change: every λ program of the
gate prints byte-identically to the previous commit. Eleven of thirteen mutants of the new code fail the
suites. The scaling figures are in Table 14.5.
e97f7ef, the show module. show.diff hard-coded λ’s forms in show. The commit
gives show a registry of extensions of its own instead (Section 11.4.8), which the module fills,
and changes three things for every answer: a type’s arguments are read as expressions, the new
°->pretty gives the αKanren-style view, and the cells view draws a disequality as a tuple only when
its form is micro’s tuple. The last one fixes a crash, found in review: the cells view took every
disequality with a list on its left for one of micro’s tuples, so (≠ (@ α a) a) raised “bad
argument type”, and so did the markdown and SXML reports that draw it. Rendering the answers of 2000 random
λ programs raised it on 23 of 586 answer sets for one seed and 22 of 663 for another before, and on none
after. Every view of the answers of 1500 random first-order programs, for two seeds, is byte-identical to
master. The λ suite reaches 93 cases, and thirteen mutants of the new code each fail it.
c0ff08c, the documentation. A section of the README on the module and the protocol,
whose nine examples print what the README says on the merged tree, and doc/hol-kanren/README.md,
which says that the prototype is frozen at f84cf9c and superseded. No source changes.
14.4.2What changed against the prototype#
The design did not change. The code changed where micro had changed under it, and where the merge’s reviews asked:
- in micro, the protocol points of Section 11.4.9: nine fields and
Xthrough every constructor, the internal unifier for the hooks,postbefore the handing on of constraints,diseqwith anabsentoflag for every prefix that holds a λ-term, thetaghook inμkanren-post-type, aμkanren-state-forgetthat makes M admit its variable, the newwatchhook, and no change ofabsent°; - in the module, five adaptations to that protocol, the export of
μkanren-repr->datumdropped, the guard ofμkanren-state-no-D?, the sorted and merged forms of E and N, the per-binding migration with its index W, and the reading of its answers registered with the show module; - in the tests, micro’s six suites run with the module loaded through
csi -Rinstead of a copy, the program file renamed, one expectation changed for the new absento, two for the sorted forms, and the new groups R4 and S and the caseR/D-migration-reach; - in show, a registry of extensions in place of
show.diff.
14.4.3Defects found and fixed#
The re-validation and the reviews of the merge found defects that the prototype’s three review rounds could not have found, since most came from the changes of micro.
- A cycle through forget and M. Since
d5b6f34the binding site spares its occurs check when M says the variable cannot occur in the bound value. The prototype’sμkanren-state-forgetunbound a variable and left M as it was, though another binding of the same unification may have written the variable into S. A later binding of that variable to such a value then skipped its occurs check: the repro gave one answer, cyclic. The merged forget makes M admit the variable (Section 11.4.4), andtest/extension/forgetpins it; R4/occurs-under-forall covers the cycles under∀°. No λ program of the four tried reached the cycle; the test calls forget directly. - λ-terms in D.
9cecddfturns an absento with a variable datum into disequalities with the parts of its term, and a typed variable’s absentos into prefixes. These bypass≠°, so in a naive port they put λ-terms, or an empty prefix, into D, which crashed at reification; and the module’s test of an absento, “T empty means it holds”, became unsound. The merged micro routes such prefixes to thediseqhook with theabsentoflag (E4). The mutant that answers “holds” on any success, which the prototype’s suites missed, now fails R4/discharge and R4/handover. - Eigenvariables leaking through aggregations. On the prototype’s micro,
∀°and λ-terms in the bodies ofset°andgroupby°were unsound: four probes succeeded that must fail, one leaked an eigenvariable, one lost its answer, one conflated two variables.5f406fd, the last commit ofmasterbefore the merge, fixed this for micro alone, by running the bodies past the variables of their from goal (Section 10.8). The merged module inherits the fix; R4 has cases for it. - A quadratic migration. The prototype’s
posthook walked all of D whenever the new bindings were too long to check at a glance. On master’s faster stores that walk became 86 times the cost of a search with 3000 disequalities.d501822made it linear (Section 14.3.3). - A crash of the cells view. Every disequality with a list on its left was drawn as a tuple, which
crashed on λ’s
(≠ (@ α a) a);e97f7eftells micro’s tuple by its form. - Answers printed by goal order. The forms of E and N were printed in the order the constraints were
posted, and a constraint posted twice, or twice up to α, printed twice. With the forms sorted and merged,
the printed answers of 165 of 12,000 random λ programs depend on the order of the goals, against 578
before, and 161 of those have a residual
≐. - An export that depended on import order. Both the module and the show module exported
μkanren-repr->datum; which one a program saw hung on the order of its imports. The module no longer exports it.
14.4.4The whole test#
After the five commits, the whole test ran on the merged tree, against master before the merge.
- Suites. As in Section 14.1.4: 479 cases of the module, the protocol and micro,
0 failures; 73 of the 77 entries of
src/testpass, and the four that fail fail the same way onmaster. - First-order differential.
diff-all, 13 runs of about 22,000 random and hand-written first-order programs, reports the same answers asmaster, forms included; the four seeds offuzz3, 4000 programs each, print byte-identically to the reference outputs; the check of the aggregations finds 0 differences on three seeds of 3000 programs. The same 20 runs with every fuzzer importing(aux kanren lambda)are byte-identical tomaster’s plain runs. - λ differential. 48,000 random λ programs (
rfuzz, with and without their constraint forms, andrfuzz2withset°,groupby°and∀°) print byte-identically on the merged tree and on the commit that added the module. Against the port of the prototype, the answers as data are identical; with their forms printed, 648 of 16,000 lines differ, 585 in the order of the forms and 63 by a form the port printed twice, and none in an answer. Printed in every order of their goals, 211 of those 16,000 programs depend on the order on the merged tree, against 736 on the port; 202 of the 207 left once forms are compared as sets have a residual≐in some order. - Mutants. The five mutants of the soundness review all fail the suites: forget keeping M
(micro’s
test/extension/forget, and a hang of R4/occurs-under-forall in the λ suite), no routing of λ prefixes out of D (three λ cases), post hooks after the handing on (four cases of the extension suite, four λ cases), “holds” on any success for λ-absent (three λ cases), no tag hook (four λ cases and one of the limits suite). - Probes. Of the 28 adversarial probe files kept with the port, 25 print byte-identically to
the port. Two others differ in the order of their printed forms, which are sorted now (one goal-order
probe printed up to six different lists for one answer, and prints one), and the last in
gensymcounters shifted by the module’s imports. - Benchmarks. Section 14.3.
14.4.5What stays open#
Nothing the whole test found is a wrong answer, but these remain:
- Inherited limits. Non-patterns are suspended (Section 14.2.3), so an answer may
carry residuals that cannot be satisfied, and some answers depend on goal order;
set°andgroupby°compare keys withequal?, not modulo α; N is never checked against E, so one answer can assert and deny the same≐;°->list/grounddrops λ residuals with the rest, so such an answer looks unconditional. - Redundant constraints. Five of the 16,000 λ programs print differently by goal order with no
residual
≐, by a denial that an absento of the same answer already implies, or by an absento printed under a binder; four print one denial twice in one order and once in another. A cut-down case,(absent° a (@ G b))then(=° G (ƛ (x) x)), prints(deny (equal? α β))twice, as the port did. - Costs. With λ loaded, the rows of Table 14.4; after any
∀°, about 2.2 times on first-order search; on an open tail extended pair by pair, 1.7 to 2.4 times the port. The hook still retries all of N at every binding when N is not empty. - The protocol. It has one client, so its claim to be generic is untested, and the module takes
the whole slot
X: a second extension that keeps data there cannot be loaded with it. - Tests. Two mutants of the migration survive every suite: one that skips the walk of D on a
state whose stores are lists, where micro hands those prefixes to the
diseqhook anyway, and one that moves the prefixes in the other order, which the sorted forms hide. The forget mutant makes the λ suite hang rather than fail. Some adversarial probes still disagree with the expectations written into them, by the same counts as on the port; most are equivalent printings or residuals of non-patterns, and one, a disequality under∀°that the probe expects to fail, depends on the reading of∀and wants a second look. - Show. With λ loaded, the cells view draws any list headed by
ƛor@, the first-order'(@ a b)too, as a λ-term node, since the datum of an answer cannot tell them apart. - Not run.
chicken-installandmake format(scheme-indentis not installed on the machine of the test); the suites that need an API key, downloaded data or a benchmark harness.
14.5Later work#
Six items were left out of the proposal on purpose, and the merge did none of them. Each should be measured separately, against the figures of Section 14.3 and the suites of Section 14.1. For each, the paragraphs below say how it would fit the protocol and which concept of the book it serves.
14.5.1(a) Spare the scope check where micro spares its occurs check#
What. micro’s binding site, μkanren-state-update, runs the occurs check, and since
d5b6f34 spares it when the bound value is a part of a value of S that M says cannot hold the
variable (Section 10.4). The module’s post hook then walks the bound term for the scope
check, with no such sparing: after a ∀°, on append° backwards, that walk is the whole of the
+125% of Table 14.6. A held value was checked when it was written into S, but at the
level of the variable it was bound to, which may be above that of the variable it is now bound to, so the
sparing needs a bound on levels, as M is a bound on indices.
How it fits. Inside the extension, with a summary kept in X beside the levels: for the values
of S, the lowest level they are known to be valid at, so that the check of a held value against a variable
of that level or above can be skipped. The binding site would have to tell the hook that the value is held;
today only micro knows it. Alternatively, a new hook at the binding site that returns a verdict
instead of micro’s boolean: no occurrence and nothing out of scope; an occurs failure; or a term that needs
variable elimination, as d3’s in-core occurs/fast does. This was the prototype’s plan, when
micro’s occurs check still walked every bound tail; with micro’s walk spared, the verdict hook would save
less than the sparing of the scope check. Neither is designed in detail or measured.
What it buys. Most of the cost of first-order search after a ∀° (+122% to +127%,
Table 14.6), and perhaps some of the factor of 2 against d3 on Church 400
(Table 14.7). It keeps the host-escape guarantee, because the check still runs at depth
0 on every value it has not seen.
Book concept. The mixed prefix of a unification problem (Section 4.4), read as universe levels (Section A.10, Section 7.9). Nadathur, Jayaraman and Kwon’s binding ruleGopalan 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 is one condition on the bound term, so it is natural to check it where the occurs check is checked, and to spare it where that is spared.
14.5.2(b) Var–var orientation by level#
What. When two variables are unified, bind the one of higher level to the one of lower level. micro binds the older to the newer, so a variable of a deep scope may become the value of an outer one, and the scope check must then lower it (Definition A.34).
How it fits. It needs a hook in micro’s var–var clause, the hottest path after pair–pair. That is why the graft from d3 was declined. Check (Definition 12.8) already lowers the younger variable, which gives the same most general unifier up to renaming, so this item is about cost only: fewer lowering bindings, and perhaps shorter var–var chains, which the profile of Section 14.3.5 places among the remaining costs. It must be measured on first-order search too, where the hook would cost on every var–var binding.
Book concept. Raising and lowering in a mixed prefix (Section 4.5). Binding the deeper variable to the outer one is always within scope. Binding the outer variable to the deeper one is allowed only after the deeper one has been lowered, which is the extra work this item saves.
14.5.3(c) Indexing E and N by variable#
What. Today every =° retries all suspended equations of E and all disequalities of N, oldest
first, in rounds, until no round binds (Section 14.2.8). An index from each variable to the
constraints that mention it would retry only those the new bindings touch.
How it fits. Entirely inside the extension. E and N live in the slot X, which micro never
reads, and the post hook already receives the new bindings as assocs. No change to micro.
The index W that the merge added for the prefixes of D (Section 12.5) is the same idea, and
shows the shape of the code.
The care needed is in what “touches” means: a binding wakes a constraint on a variable it reaches
through the substitution, not only on the variable it binds, and the variables created by lowering and
pruning must be indexed too.
Book concept. Dynamic (Section 7.9): an equation that does not respect the condition is deferred “until such time that substitutions resulting from solving other parts of the problem have altered its status” [MN p. 226]. An index decides cheaply which deferred equations a substitution may have altered.
14.5.4(d) Huet pre-unification as an optional search#
What. An opt-in goal that takes the suspended equations of E and searches their solutions with Huet’s imitation and projection stepsGérard Huet. A unification algorithm for typed -calculus. Theoretical Computer Science, 1:27–57, 1975, each choice a branch of the interleaving search. On Example 8.A it would enumerate the four unifiers of Example 7.5. On the first problem of Section 14.2.3 it would find no solution and fail, so floundering would be detected, not only reported.
How it fits. E is the natural agenda: it already holds the non-pattern equations, closed over the eigenvariables they mention, and woken equations are retried by the existing loop. Huet’s branching is don’t-know nondeterminism, which a miniKanren stream represents directly. It should be a goal the user calls, not the default, because the search may not terminate (Section 7.3).
The obstacle. Projection needs the target type and arities, and imitation the arity and argument types of the constant: “Huet’s procedure cannot run without types” (Section 7.4). So this item presupposes (f).
Book concept. Huet’s procedure and its matching trees [MN p. 214–220], and the limit of pattern unification that Section 5.8 discusses.
14.5.5(e) Predicate quantification#
What. Goals such as pi rev\ (... rev ...) => rev L K nil, which introduce a hidden predicate
local to one call [MN p. 125–126].
How it fits. Through dynamic relations created at run time. Γ is an alist keyed by relation, so a
∀ over a predicate would allocate a new key, a new dynamic relation with no static clauses, and
pass it to the body. Clauses assumed for it are then visible only inside that body, and no program text
outside can name it. This is a sketch: the proposal does not implement it.
Book concept. hohh (Definition 5.7): a clause head may be a variable bound by an essentially universal quantifier. By the time the clause is assumed, has replaced the variable by a new constant, so the operational behaviour does not change. Only the visibility of names does.
14.5.6(f) Simple types#
What. Optional simple types on λ-terms and on logic variables.
How it fits. Through the interplay of the atom? and tag hooks, which the proposal
names for this item without designing it. One reading: a type is a tag on a term, and a typed variable can
be η-expanded by its type. Unification could then work on η-long forms,
as λProlog does, instead of η-expanding only when one side is an abstraction
(Section 14.2.2).
What it buys. Type-directed η, β that is guaranteed to terminate, the existence check on possibly empty types, and with them item (d).
Book concept. The simply typed terms of Chapter 4 and the βη-long normal forms on which the book’s unification algorithms are stated (Section 4.3).
14.6Open questions for the author#
The proposal makes a choice wherever one was needed to build it and test it, and the merge kept those choices. Some of them are the maintainer’s to make, and are listed here as questions. Each says what the merged module does now and what is at stake.
- The module’s name. The proposal keeps
(aux kanren lambda). The layer is λProlog’s logic, and λKanren is the name the literature gives this line of work, Ma and Friedman’s paper includedWeixi Ma and Daniel P. Friedman. A new higher-order unification algorithm for Kanren. In miniKanren and Relational Programming Workshop, 2021. A name such as(aux kanren hohh)would describe only the goals, while the module also gives λ-tree syntax and unification. The names inside followaux: goals end in°, their applicative forms inª, term constructors have no suffix (ƛ,@), and internals carry theμkanren-prefix. - The extensional reading.
μkanren-λ-readingexposes a second meaning of≠°under∀°(Definition 14.1). It costs code and one edge case, the reading of a migrated disequality (Section 14.2.5). Keep it public, keep it as an internal option, or remove it and keep only λProlog’s generic reading? - Keep the protocol stable? The merge put a generic extension protocol in micro, a global
registry, and one client. The alternatives were a layered module that leaves micro untouched
(d1, which leaked eigenvariables through micro’s own
=°) and λ-terms native in micro (d3, a 931-line diff that special-cases every walker). A per-state hook list instead of a global registry would require every initial state to carry the hooks, since°->liststarts fromμkanren-state-empty. Now that it is in micro, with fourteen hooks and the invariants E1–E6, every change of micro’s stores must keep them, as the merge’s port onto the records had to: is that a contract the maintainer wants to keep? And shouldXbe shared, keyed by extension, before a second client comes, since the λ layer takes all of it? - The cost after a
∀°. First-order search after any∀°takes about 2.2 times as long (Table 14.6). The cheap fix gives up the host-escape guarantee (Section 14.2.6); the proper one is roadmap item (a). The module was merged with this cost: should (a) come next? And is it worth this price to catch escapes made withproject°andset!? - Which relations are dynamic. In λProlog every predicate takes hypotheses; here only those
made by
define-dynamic-relation, and⊃°on any other is an error (Section 14.2.1). Shoulddefine-relationitself become dynamic when the module is loaded? The proposal does not measure what that would cost. - α-equivalence and
equal?. Hints are interned, so terms built alike areequal?, but α-variants with different names are not (Section 14.2.7). Truly nameless records would makeequal?decide α, at the price of answers printed with generated names instead of the user’s. Which matters more for the intended use? - An answer inside
∀°. Reifying a variable created inside a∀°that holds its eigenvariable is an error, where λProlog reports no binding (Section 14.2.9). Keep the error, or answer with no binding as λProlog does? - Types outside micro’s contract. Under a type of the user’s that holds of pairs, micro’s
subsumption turns
absent° '(a) qintoq ≠ (a), so(absent° '(a) q) (nonnum° q) (=° q '((a)))succeeds, onmasteras in the prototype: the subsumption assumes that typed values are atoms.masternow writes that assumption down, as the contract ofdefine-μkanren-tag(aux.kanren.micro.scm:40–43), so this type is outside it, and so is the user type ofR3/user-types, which holds of λ-terms. Should micro check the contract, or keep it documented? - Two clause syntaxes. Hypothetical clauses may be written infix,
(H ← B), or prefix,(← H B); both are accepted. Keep both, or settle on one? - How the series lands. The five commits sit on top of
5f406fd, anddoc/hol-kanren/README.mdcites four of them by hash. A fast-forward keeps the hashes; a rebase or a squash changes them, and that table with them.
14.7Summary#
- The module is merged, in five commits on top of
5f406fd: the protocol (26b4708), the module (5be5f35), the migration of D per binding (d501822), the show module’s registry (e97f7ef) and the README (c0ff08c). The prototype stays frozen atf84cf9c. - The module has two suites: 93 cases with 421 hand-written assertions (acceptance A1–A9, the
regressions R, R2, R3 of three adversarial review rounds, and R4 and S of the merge), and 6 cases that pin
its limits. micro’s six suites, 187 cases, pass both without and with the module loaded, answer order
unchanged, and the protocol’s own suite has 6 cases: 479 cases, 0 failures. Every first-order
differential run is byte-identical to
master, with and without the module loaded, and the five mutants of the soundness review all fail the suites. - The suites test behaviour on examples, under several goal orders; the guarantees on pattern problems come from the theorems of Miller, of Nadathur, Jayaraman and Kwon, and of Nadathur and Linnell, which the algorithm follows.
- Nine limitations are documented and pinned. Only dynamic relations take hypotheses, and there is
no predicate quantification. Terms are untyped. Non-patterns are suspended, never enumerated, so
floundering is reported, not detected. Answer order is micro’s interleaving.
≠°,absent°and types use the generic reading of∀, with an extensional option for≠°. Levels police logic variables, not Scheme values. Binder names are hints. Constraints are retried unindexed, and the scope check runs after any∀°. The answer variable must be created outside every∀°. - With no extension the protocol costs 0–2.2% on first-order search, and 1 ms more on three rows
of about 30 ms. With the module loaded,
searches without stores cost under 2%, searches with disequalities 4–47% on the larger rows and up
to 2.4 times on short ones; after a
∀°, first-order search takes about 2.2 times as long, because the scope check walks the bound term where micro spares its own walk. The migration of D, 86 times the cost of a search in the first port, is linear. On λ workloads the merged module is 17% faster than the prototype, thanks to master’s micro, 2.1 times faster than d2 and twice as slow as d3 on Church 400. - The merge found and fixed a cycle through forget and M, λ-terms reaching D through the new absento,
a quadratic migration, a crash of the show module’s cells view, and printed answers that depended on
goal order; it inherited
master’s fix of eigenvariables leaking through aggregations. - Six later items: sparing the scope check where micro spares its occurs check; var–var orientation by level; an index of E and N; an optional Huet search, which needs types; predicate quantification through dynamic relations made at run time; simple types.
- Ten questions are the author’s to answer, among them the module’s name, the extensional reading,
whether the protocol is a contract to keep, and whether the cost after a
∀°must be paid down next.