Mika Bohinen / NixCon 2026

Trampolining Nix

I need to run the next step

Trampolining Nix

How I nearly lost my mind fighting the evaluator

Mika Bohinen - NixCon 2026

Charlie Kelly tries to explain a wall of papers connected by red string.Kleisli

nix-effects is my attempt to see how far Nix can be taken as a programming language: algebraic effects, a type system and an evaluator, all written in Nix. I assume you know some Nix; the compiler terminology is explained as we go.

How far can we take Nix as a programming language?

I wanted to build effects, a type system and an evaluator in Nix.

nix-effects / README.md

The goal of nix-effects was to see what could be built in Nix itself: algebraic effects, an MLTT-inspired type checker and an evaluator for a richer language. This talk is about running those programs: how to keep taking steps without growing the stack, when to force lazy state, and how to represent the work that is still left to do.

The program asks for state; the handler supplies it.

An effect is a request whose meaning is supplied by a handler
Code
get
An operation and the handler that answers it
Program asksgetrequest the state
Handler replies21the current state

With algebraic effects, a program makes requests and a handler decides how to answer them. get asks for the current state. Here the handler holds 21, so it replies with 21.

bind passes that reply to the rest of the program.

A continuation: the function to run after get replies
Code
s: put (s * 2)
The continuation turns the reply into the next request
get repliess = 21
continuation
Next requestput (s * 2)
Handler storesstate = 42

The reply becomes s. The function says what to do next: ask the handler to store twice s. A function that represents the rest of the computation is called a continuation, and bind attaches one to an operation.

The program changes the state, then returns the original value.

Read state, store twice the value, return the original
Code
bind get (s:
  bind (put (s * 2)) (_:
    pure s))
Follow the requests and replies
get repliess = 21
put storesstate = 42
pure s returns21the original value

The state ends at 42; the program returns 21.

nix-effects / README.md

The first bind passes get's reply to s. The second asks for put (s * 2) and then returns pure s, the original value. The handler ends with 42 and the program returns 21. So far this only describes the program. Something still has to handle each request and resume its continuation until the program finishes.

This call waits for the next call to return.

step returns either a final value or the next state
Code
run = state:
  let next = step state;
  in
    if next.done
    then next.value
    else run next.state;
run s0 is waiting for run s1
run s0 is waiting for run s1run s0 calls run s1 and waits for its answer. Both calls remain open. Calls to step are omitted; each has already returned before the next run begins.1234stack limitrun s1run s0callerexecution orderopen callsrun s0 is waiting for run s1run s0 calls run s1 and waits for its answer. Both calls remain open. Calls to step are omitted; each has already returned before the next run begins.1234stack limitrun s1run s0callerexecution orderopen calls

Each call to step returns before run calls itself.

step performs one transition and returns either the final value or the next state. If there is more work, run calls itself with that state. run s0 needs the answer from run s1 before it can return its own answer. Both calls are still open. Each call to step returns before run calls itself.

Each step leaves another call waiting.

step returns either a final value or the next state
Code
run = state:
  let next = step state;
  in
    if next.done
    then next.value
    else run next.state;
run s0 and run s1 are both waiting
run s0 and run s1 are both waitingrun s1 calls run s2. The two earlier calls remain open, waiting for the final answer. Each transition adds another waiting caller.1234stack limitrun s2run s1run s0callerexecution orderopen callsrun s0 and run s1 are both waitingrun s1 calls run s2. The two earlier calls remain open, waiting for the final answer. Each transition adds another waiting caller.1234stack limitrun s2run s1run s0callerexecution orderopen calls

The earlier calls cannot return until they have the answer.

run s1 now calls run s2. The earlier calls are still waiting for the same final answer. The height counts calls that have started but have not returned. That chain of unfinished calls is the call stack. More transitions make it taller.

The answer returns through every waiting call.

step returns either a final value or the next state
Code
run = state:
  let next = step state;
  in
    if next.done
    then next.value
    else run next.state;
Each caller passes back the same value
Each caller passes back the same valuerun s2 returns value to run s1, which returns the same value to run s0. Each return closes one call. No caller performs further work on the answer.1234stack limitrun s2valuerun s1valuerun s0valuecallerexecution orderopen callsEach caller passes back the same valuerun s2 returns value to run s1, which returns the same value to run s0. Each return closes one call. No caller performs further work on the answer.1234stack limitrun s2valuerun s1valuerun s0valuecallerexecution orderopen calls

The final value travels back through the waiting calls.

Suppose the computation finishes at s2. run s2 returns the final value to run s1, which returns it to run s0. Only now can the first call return. Each downward edge closes one of the waiting calls.

Even a tail-recursive driver consumes stack in Nix.

step returns either a final value or the next state
Code
run = state:
  let next = step state;
  in
    if next.done
    then next.value
    else run next.state;
Each caller passes back the same value
Each caller passes back the same valuerun s2 returns value to run s1, which returns the same value to run s0. Each return closes one call. No caller performs further work on the answer.1234stack limitrun s2valuerun s1valuerun s0valuecallerexecution orderopen callsEach caller passes back the same valuerun s2 returns value to run s1, which returns the same value to run s0. Each return closes one call. No caller performs further work on the answer.1234stack limitrun s2valuerun s1valuerun s0valuecallerexecution orderopen calls

Tail-call elimination could discard these waiting callers. Nix keeps them.

Notice that each caller only passes the answer back. There is no addition or other operation left to perform after run next.state returns. That makes it a tail call. Tail-call elimination would let the evaluator discard the waiting caller, but Nix does not eliminate it. A long enough run exhausts call depth or stack even if the carried state is forced correctly. We need repetition that does not keep another Nix call open at every step.

Let the step return before taking another.

Every step gives control back to the driver
Every step gives control back to the driverThree calls to step each return to the driver before the next begins, so depth never exceeds one. The first two replies say what to do next; the last reply is the result.1234stack limitstepnextstepnextstep3driverexecution orderopen step callsEvery step gives control back to the driverThree calls to step each return to the driver before the next begins, so depth never exceeds one. The first two replies say what to do next; the last reply is the result.1234stack limitstepnextstepnextstep3driverexecution orderopen step calls

The driver has called the first step. It is the only call above the driver.

Move repetition into a native driver. It calls step once, and step describes what to do next instead of calling run. Height still counts open calls, now above the native driver. The call must return before the driver takes another step.

That call returns before the next one begins.

Every step gives control back to the driver
Every step gives control back to the driverThree calls to step each return to the driver before the next begins, so depth never exceeds one. The first two replies say what to do next; the last reply is the result.1234stack limitstepnextstepnextstep3driverexecution orderopen step callsEvery step gives control back to the driverThree calls to step each return to the driver before the next begins, so depth never exceeds one. The first two replies say what to do next; the last reply is the result.1234stack limitstepnextstepnextstep3driverexecution orderopen step calls

The first step has returned its reply. Its call is gone before the next one starts.

The first call has returned, so we are back at the baseline. Its reply, next, describes the next piece of work, which the driver has not started yet.

More steps. The same nesting depth.

Every step gives control back to the driver
Every step gives control back to the driverThree calls to step each return to the driver before the next begins, so depth never exceeds one. The first two replies say what to do next; the last reply is the result.1234stack limitstepnextstepnextstep3driverexecution orderopen step callsEvery step gives control back to the driverThree calls to step each return to the driver before the next begins, so depth never exceeds one. The first two replies say what to do next; the last reply is the result.1234stack limitstepnextstepnextstep3driverexecution orderopen step calls

Each step returns before the next call; the depth stays at one.

A trampoline is a driver that runs one step at a time. Each step either finishes with a value or returns a continuation: a function or some data describing what to do next. The driver starts that work only after the previous step has returned, so the calls do not pile up. The driver must supply native repetition; rewriting run recursively in Nix would bring back the waiting calls. A step can still recurse inside its own body, and the values passed between steps can still be lazy.

A fold passes the running total to this function.

One addition per input
Code
total: _: total + 1
Accumulatortotal = 0the initial value
total + 1
Next accumulator1
becomes total in the next call

The list is only there to supply iterations; the callback ignores its elements. Starting from zero, each call adds one.

A strict scalar fold already solves this fixed counter.

ticks is a list of 100000 inputs
Code
builtins.foldl'
  (total: _: total + 1)
  0
  ticks
scalarFold100000
Explore code

foldl' evaluates each new accumulator, and here the accumulator is the number itself. With n = 100000, scalarFold returns 100000, and the loop runs natively without a Nix call per iteration. A fold is a for-each loop over a list we supply up front, though. Our interpreter needs a while loop that keeps stepping until the computation is done. A done flag can turn the remaining callbacks into no-ops, but the fold still visits every element. genericClosure is different: it discovers new work as it goes, because it was made for finding everything reachable in a graph.

A dependency closure collects every reachable package.

Each package has a unique id and a dependencies list
Code
builtins.genericClosure {
  startSet = [{ key = app.id; package = app; }];
  operator = item:
    map (package: {
      key = package.id;
      inherit package;
    }) item.package.dependencies;
}
operator runs once for each new key
operator runs once for each new keygenericClosure starts with app. operator returns lib-a and lib-b; each library returns lib-c. The first copy of lib-c is visited. The second is skipped when it leaves the queue because its key has already been seen. lib-c returns an empty list. The result lists app, lib-a, lib-b and lib-c in the order they were visited.key seenapplib-alib-blib-c[ ]resultapplib-alib-blib-coperator runs once for each new keygenericClosure starts with app. operator returns lib-a and lib-b; each library returns lib-c. The first copy of lib-c is visited. The second is skipped when it leaves the queue because its key has already been seen. lib-c returns an empty list. The result lists app, lib-a, lib-b and lib-c in the order they were visited.key seenapplib-alib-blib-c[ ]resultapplib-alib-blib-c

Each box is one call to operator; its arrows are the dependencies it returns.

Start with app and let operator return records for its direct dependencies. genericClosure takes records off a queue in the order they arrived and calls operator once for each new key. lib-a and lib-b both depend on lib-c, so lib-c is queued twice. The second copy is dropped when it comes off the queue, because its key has already been seen. The result is the root and every reachable package, in the order they were visited. If each record is an interpreter state instead of a package, the same queue can drive an interpreter.

One successor continues execution; no successors means done.

genericClosure owns the loop; operator chooses the next state
genericClosure owns the loop; operator chooses the next stateStarting from key 0, operator returns one successor with key 1, then one with key 2. At key 2 it returns an empty list, so the traversal stops. The result lists all three visited states, not just the last.012[ ]result012genericClosure owns the loop; operator chooses the next stateStarting from key 0, operator returns one successor with key 1, then one with key 2. At key 2 it returns an empty list, so the traversal stops. The result lists all three visited states, not just the last.012[ ]result012

Illustrative traversal; each key is expanded once, in visit order.

Instead of dependencies, operator now returns the next interpreter state: a one-element list to continue, or an empty list to stop. Each transition gets a fresh key, so a state whose payload repeats is not mistaken for one we have already visited. genericClosure runs the loop and operator decides when it ends. genericClosure returns the list of every visited record. Only the keys are forced; the other fields can stay unevaluated.

Start with one record: an identity and a running total.

genericClosure input; total stands in for interpreter state
Code
startSet = [{ key = 0; total = 0; }];
One state, two jobs
key = 0

Identity used by the worklist

total = 0

Payload used by our counter

Interpreter state is the data carried from one step to the next. The counter is a small stand-in for that: total plays the role of the state, and key is what genericClosure uses to tell records apart. A fold would be enough for this counter, but we want to try the worklist as a driver. key and total both start at 0, but they have different jobs.

Build the successor from the current record, item.

Code
{
  key = item.key + 1;
  total = item.total + 1;
}
The first call to operator
Current itemkey = 0total = 0the seed
operator
Successorkey = item.key + 1total = item.total + 1fields can remain unevaluated

item is the record being visited. The successor increments its key and total. Nothing here says when either addition is actually computed.

Return no successors when the key reaches the limit.

Operator excerpt; the else branch returns the successor in a list
Code
operator = item:
  if item.key >= n then [] else
The operator returns a list
Conditionoperator returnsEffect
item.key < n[ successor ]one more state
item.key >= n[]this branch stops

n = 100000. The seed has key 0; the last visited record has key n.

operator takes one item and returns a list of successors: the record we just built while the key is below n, and an empty list once it reaches n. Here n = 100000.

naive names the returned list, including the initial state.

Code
naive = builtins.genericClosure {
  inherit startSet operator;
};

We call this first attempt naive. It returns the list of all visited records, starting with the initial one. We will ask it for two things: its length and the last total.

Surely the hard part is over.

A toddler clenches his fist with a triumphant expression.
Found a while loop in Nix.

We now have a builtin to drive the loop and a counter to put inside it.

The same program succeeds or overflows depending on what I ask for.

How many states were visited?
builtins.length naive100001
Explore code
What is the final total?
(last naive).totalerror: stack overflow (possible infinite recursion)
Explore code

Counting the visited states does not compute their totals.

With n = 100000, counting the visited states works. Asking for the final total overflows the stack.

Then I asked for the total.

KC Green's dog calmly sits in a burning room.

The worklist reached the last state, but its total still contains deferred work.

I need the answer, too

The key and the total have separate demand paths.

The successor record returned by the operator
Code
{
  key = item.key + 1;
  total = item.total + 1;
}
Keys move forward; each total refers back
keytotal
00
1total[0] + 1
2total[1] + 1
  • computed number
  • deferred expression
  • evaluated record
Three states shown; total[k] is the total of the state with key k.

Each state is a record with a key and a total. The worklist needs the key to continue, but nothing asks for the total, so it can remain a thunk. The stop condition is omitted here; it ends the traversal when the key reaches n.

Counting visited states does not demand their totals.

The successor record returned by the operator
Code
{
  key = item.key + 1;
  total = item.total + 1;
}
Visiting evaluates each record and its key
keytotal
00
1total[0] + 1
2total[1] + 1
  • computed number
  • deferred expression
  • evaluated record
Three states shown; total[k] is the total of the state with key k.
builtins.length naive100001
Explore code

Starting from key = 0 and total = 0, the traversal visits n + 1 states. Taking the length of the result goes through all of them without asking for a single total.

The final total depends on earlier deferred additions.

The successor record returned by the operator
Code
{
  key = item.key + 1;
  total = item.total + 1;
}
Reading the final total climbs through every deferred addition
Reading the final total climbs through every deferred additionBuilding the states returns after each step without evaluating any total. Reading the final total forces the previous total, which forces the one before it. Each forced addition waits inside the previous one until the evaluator reaches its stack limit.1234stack limittotal[n−2]total[n−1]total[n]⋯stack overflowevaluatorvisit statesread totalforcing depthReading the final total climbs through every deferred additionBuilding the states returns after each step without evaluating any total. Reading the final total forces the previous total, which forces the one before it. Each forced addition waits inside the previous one until the evaluator reaches its stack limit.1234stack limittotal[n−2]total[n−1]total[n]⋯stack overflowevaluatorvisit statesread totalforcing depth

Demanding the final total enters n deferred additions; at n = 100000, the recorded run overflows.

(last naive).totalerror: stack overflow (possible infinite recursion)
Explore code

The last total needs the previous total, which needs the one before it, and so on back to zero. Forcing it climbs one level per step, and at 100000 steps this overflows the stack.

Forcing the record leaves its total field deferred.

shallow: the same traversal, forcing next
Code
let next = { total = item.total + 1; };
in {
  key = builtins.seq next (item.key + 1);
  inherit (next) total;
}
seq next evaluates the record, not its total
keytotal
00
1total[0] + 1
2total[1] + 1
  • computed number
  • deferred expression
  • evaluated record
Three states shown; total[k] is the total of the state with key k.
(last shallow).totalerror: stack overflow (possible infinite recursion)
Explore code

We name the carried data next so we can compare forcing the record with forcing its total field. seq next evaluates only the outer record. total is left untouched, so the chain of additions remains.

The next key becomes available after next.total has been computed.

The successor record returned by the operator
Code
let next = { total = item.total + 1; };
in {
  key = builtins.seq next.total (item.key + 1);
  inherit (next) total;
}
First transition: compute 1, then expose key 1
keytotal
00
11
next?
  • computed number
  • deferred expression
  • evaluated record
Three states shown; total[k] is the total of the state with key k.

The worklist has to evaluate the next key, so we put seq next.total in the key expression. The first transition now computes total = 1 before it returns key 1.

The following step receives a total that has already been computed.

The successor record returned by the operator
Code
let next = { total = item.total + 1; };
in {
  key = builtins.seq next.total (item.key + 1);
  inherit (next) total;
}
Each transition carries a computed number
keytotal
00
11
22
  • computed number
  • deferred expression
  • evaluated record
Three states shown; total[k] is the total of the state with key k.

The previous state already holds the number 1, so the next transition computes 2 with a single addition. The same holds for every step after that.

Asking for the final total now succeeds with the same input and limits.

targeted: the same traversal, forcing next.total
Code
let next = { total = item.total + 1; };
in {
  key = builtins.seq next.total (item.key + 1);
  inherit (next) total;
}
Each step computes its total before the next begins
Each step computes its total before the next beginsThe first peak labels the two nested evaluations: the step waits while seq forces one addition. Both finish before the next step begins. Reading the final total then uses an already computed number.1234stack limitforce additionstepread computed total100000⋯evaluatorvisit statesread totalforcing depthEach step computes its total before the next beginsThe first peak labels the two nested evaluations: the step waits while seq forces one addition. Both finish before the next step begins. Reading the final total then uses an already computed number.1234stack limitforce additionstepread computed total100000⋯evaluatorvisit statesread totalforcing depth

Each step computes its total before returning; the recorded run returns 100000.

(last targeted).total100000
Explore code

Same input, same limits. Each step now computes its total before passing it on, so the final total is already a number and we get 100000. The interpreter has the same problem with the data it carries between steps: having the next state record does not mean that its fields have been computed.

Is forcing next.stats enough?

The successor record returned by the operator
Code
let next = { stats.total = item.stats.total + 1; };
in {
  key = item.key + 1;
  inherit (next) stats;
}
Keys move forward; each total refers back
keystats.total
00
1stats.total[0] + 1
2stats.total[1] + 1
  • computed number
  • deferred expression
  • evaluated record
Three states shown; stats.total[k] is the stats.total of the state with key k.

Now total lives inside stats. Does forcing next.stats also compute the number the next step needs?

The stats record can still contain a deferred total.

nestedShallowResult: final total after forcing stats
Code
let next = { stats.total = item.stats.total + 1; };
in {
  key = builtins.seq next.stats (item.key + 1);
  inherit (next) stats;
}
seq next.stats evaluates stats, not stats.total
keystats.total
00
1stats.total[0] + 1
2stats.total[1] + 1
  • computed number
  • deferred expression
  • evaluated record
Three states shown; stats.total[k] is the stats.total of the state with key k.
nestedShallowResulterror: stack overflow (possible infinite recursion)
Explore code

next.stats is evaluated, but it is just another record. Its total still refers to the previous total, so the chain of additions is left for later.

Computing next.stats.total at each step breaks the nested dependency chain.

nestedTargetedResult: final total after forcing stats.total
Code
let next = { stats.total = item.stats.total + 1; };
in {
  key = builtins.seq next.stats.total (item.key + 1);
  inherit (next) stats;
}
Each transition carries a computed number
keystats.total
00
11
22
  • computed number
  • deferred expression
  • evaluated record
Three states shown; stats.total[k] is the stats.total of the state with key k.
nestedTargetedResult100000
Explore code

Forcing next.stats.total before returning the key computes the number itself, so each transition starts from a number again.

Perhaps I can force everything

Programs choose the state. This interpreter uses deepSeq.

newState: the data carried between interpreter steps
Code
k = builtins.deepSeq newState (step.key + 1);

We know to force total in our counter. The interpreter accepts differently shaped program state, so it chooses recursive forcing.

The same counter, using deepSeq before each next key
(last deep).total100000
Explore code

nix-effects / src/trampoline.nix

newState is the data carried between interpreter steps; the key and pending computation are separate fields. We could select total because we knew our counter's state. The interpreter accepts state supplied by different programs, so it cannot hard-code that field. This implementation chooses deepSeq to recursively evaluate the carried lists and records before exposing the next key. The same policy also repairs our unchanged counter. What does it cost when a program's state grows?

Suppose the program also keeps a growing log.

Add history to the counter's carried data
Code
history = {
  head = item.key;
  tail = item.history;
};
New cellhead = item.keytail = item.history
tail
Previous cellitem.historyshared, not copied
tail
Earlier cells…

The counter now keeps a program log in history. Each transition adds one cell: head stores the current key and tail points to the previous history. The old cells are shared. The next addition still needs only total; the log is extra data the program chooses to carry.

deepSeq computes the total and walks the program's log.

next now carries a history
Code
next = {
  total = item.total + 1;
  history = { head = item.key; tail = item.history; };
};
The same state, three demand boundaries
DemandEvaluatesStill deferred
seq nextthe recordtotal, history
seq next.totaltotalhistory
deepSeq nexttotal and every history cellnothing

seq next evaluates the outer record, and seq next.total computes the number. deepSeq next reaches the number too, but also follows every cell in history. The next addition needs no log entries. Recursive forcing still traverses them because they belong to the carried data.

Repeated deep traversal revisits the growing prefix.

A traversal of the whole retained chain after every extension
Step 1
cell 1
1 visit
Step 2
cell 1cell 2
2 visits
Step 3
cell 1cell 2cell 3
3 visits

3 new cells. 1 + 2 + 3 = 6 visits.

Stored values can already be evaluated. Each traversal walks the links again.

n steps cost n(n + 1) / 2 visits: about 5 billion at n = 100000.

Watch the oldest cell appear in every traversal. We add three cells but make 1 + 2 + 3 = 6 visits. After N extensions, walking the entire log at every step gives N(N + 1)/2 structural visits. Its stored numbers can already be evaluated; the repeated work is walking the links. This cost follows from this growing state and the decision to force it deeply at every step.

Precise forcing requires knowledge of the state.

We know this counter's state

seq next.total

Computes the number; leaves the program log alone.

The interpreter accepts different state

deepSeq next

Recursive forcing also walks this program's growing log.

The interpreter cannot hard-code total. Its forcing cost depends on what the program carries.

Knowing this counter lets us use seq next.total and leave its log alone. That field-specific choice is not a general replacement for the interpreter's policy: other programs supply different state. deepSeq repairs the counter too, but traverses its growing log at every step.

Now the functions are the problem

Can my checker compare this deeply nested type with itself?

nix-effects: an MLTT-inspired type checker
Π (x₁ : A₁).
  Π (x₂ : A₂).
    …
      Π (xₙ : Aₙ). R

What about 10,000 binders?

A Π type describes a function whose result type may depend on its argument.

nix-effects includes a type checker loosely based on Martin-Löf type theory. A Π type describes a function whose result type may depend on its argument. Here the domains and result may also refer to earlier bindings. The checker must inspect and compare these nested types. I wanted this to keep working with 10000 binders.

One driver step can still enter deeply nested Nix calls.

Recursive comparison inside one driver step
Recursive comparison inside one driver stepA native driver invokes one comparison. That call waits for a comparison under the next binder, which waits for another. Three host calls remain open; further descent would add more. The driver cannot take its next step until this operation returns.1234compare bodycompare bodycomparenative driverexecution orderopen Nix callsRecursive comparison inside one driver stepA native driver invokes one comparison. That call waits for a comparison under the next binder, which waits for another. Three host calls remain open; further descent would add more. The driver cannot take its next step until this operation returns.1234compare bodycompare bodycomparenative driverexecution orderopen Nix calls

The driver can take another step only after this operation returns.

A recursive comparison works inward through the types. Each call compares another body while earlier calls wait for its answer. Nix functions and scope were attractive building blocks, but representing a term as data did not make its processing iterative. The outer driver cannot schedule the work inside an invocation until that invocation returns.

This function remembers which function to call first.

Code
f0 = x: x;
step = previous: x: previous x + 1;
Callstep f0
returns
A new functionx: previous x + 1remembers previous = f0

We can see the same execution problem with a function that adds one. step wraps previous in a new function. Calling it calls previous x first, and the addition waits until that call returns. Constructing a wrapper captures previous; applying it runs the body.

Each new function remembers the one before it.

Code
f1 = step f0;
f2 = step f1;
f3 = step f2;
Wrapperf3adds 1 after previous
previous
Wrapperf2adds 1 after previous
previous
Wrapperf1adds 1 after previous
previous
Base functionf0returns x

The arrows are captured references: f3 remembers f2, which remembers f1, which remembers f0. closureChain builds the same thing 100000 times with a strict fold. So far we have only built functions; none of them has been called.

A function value can be ready while its body still has work.

closureChain: the same construction, repeated 100000 times
Code
builtins.deepSeq closureChain true
builtins.deepSeq closureChain truetrue
Explore code

deepSeq evaluates closureChain to a function value, and that succeeds. It cannot apply the function, since it has no argument to give it, so the chain of calls is still inside the body.

Applying the function enters the remembered calls.

Run the larger construction
Code
closureChain 0
f3 0 nests four calls before any addition
f3 0 nests four calls before any additionEach call waits for the next one and owes an addition. Four calls are open when the base case returns zero; the replies then come back one, two, three. A large enough count reaches the stack limit before any call returns.1234stack limitf0 00f1 01f2 02f3 03callerexecution orderopen callsf3 0 nests four calls before any additionEach call waits for the next one and owes an addition. Four calls are open when the base case returns zero; the replies then come back one, two, three. A large enough count reaches the stack limit before any call returns.1234stack limitf0 00f1 01f2 02f3 03callerexecution orderopen calls

Illustrative trace; spacing shows order, not elapsed time.

closureChain 0error: stack overflow (possible infinite recursion)
Explore code

f3 0 calls f2, then f1, then f0, and each still has an addition to do when the inner call returns. For three functions that gives 3. For closureChain it means 100000 nested calls, and the stack runs out. All of those calls happen inside the operation the driver started.

The recursion has moved inside the callback.

Pikachu stares in open-mouthed surprise.
I forced the function.

And then I called it.

Forcing the function did not run its body, and the driver cannot schedule the calls hidden inside it. Handling deeply nested terms was part of the goal, so I needed control over that pending work.

Return after one transition. Store the remaining work.

Function bodyx: previous x + 1

previous is the remembered function. The pending operation is + 1.

Explicit pending operation{ tag = "add"; amount = 1; }

Store the operation for the dispatcher to perform. Written add 1 below.

Where did previous go? Its links become the order of the frame list.

First: f1's additionadd 1
Then: f2's additionadd 1
Last: f3's additionadd 1
Defunctionalization

I needed each transition to return control and leave the remaining work for the next step. Each wrapper holds previous and the amount to add after it returns. A frame stores that addition with an add tag and an amount. The links through previous become the execution order of frames. A dispatcher performs one operation and returns. Replacing this known family of functions with tagged data and a dispatcher is defunctionalization.

The dispatcher reads one frame and performs its operation.

apply: the dispatcher for add frames
Code
apply = value: frame:
  if frame.tag == "add"
  then value + frame.amount
  else throw "Unknown frame";
Hand trace: one frame
Current value0
apply reads the frametag = "add"amount = 1
New value1value + frame.amount

One call performs one pending operation and returns control to the driver. The diagram applies a single add frame to 0. Recursively interpreting the remaining frames before returning would leave the scheduling problem in place.

The dispatcher performs the same three additions.

frames holds the three add records
Code
builtins.foldl' apply 0 frames
Initial value0
add 1
New value1
add 1
New value2
add 1
New value3
f3 03
Explore code
builtins.foldl' apply 0 frames3
Explore code

Starting from 0, foldl' applies the three add frames in order and gets 3, the same as f3 0. A fold is enough for a fixed list; a real machine chooses its next transition as it runs.

A machine makes its pending operations inspectable.

Each transition consumes one frame and carries the rest forward
Each transition consumes one frame and carries the rest forwardThe machine starts with value zero and three add-one frames. Each transition applies the top frame: zero becomes one, then two, then three. The remaining frames keep their order, and the run ends when no frames remain.pending framesvalueadd 1add 1add 10applyadd 1add 11applyadd 12applyno frames3Each transition consumes one frame and carries the rest forwardThe machine starts with value zero and three add-one frames. Each transition applies the top frame: zero becomes one, then two, then three. The remaining frames keep their order, and the run ends when no frames remain.pending framesvalueadd 1add 1add 10add 1add 11add 12no frames3

Each transition consumes the top frame; the remaining frames keep their order.

A CEK-style evaluator carries:

C: control
The expression being evaluated.
E: environment
The bindings available to that expression.
K: continuation
The pending evaluator work, stored as frames.

Deep terms require control over each recursive walk.

nix-effects / src/tc/eval/machine.nix

Our small machine carries a value and pending frames. Each transition performs the top frame and carries the rest forward. The richer evaluator is CEK-style: C is control, the current expression; E is the environment, its bindings; K is the continuation, pending evaluator work. To handle the deeply nested types, I also had to make the checker's other recursive walks return control this way.

The checker can return between comparisons.

Π₁ = Π (x₁ : A₁). Π₂

Π₁ is the outer type; Π₂ is its body: Π (x₂ : A₂). …

Compare the argument types, then resume the bodies
Compare the argument types, then resume the bodiesThe current comparison begins at the outer type, Pi one. It moves to the argument type A one and stores a frame to compare the bodies, Pi two. When the argument types match, the body comparison becomes current and its frame is removed. Each transition returns to the driver; comparison continues at the next binder.pending framescompareno framesΠ₁return to driverΠ₂A₁return to driverno framesΠ₂Compare the argument types, then resume the bodiesThe current comparison begins at the outer type, Pi one. It moves to the argument type A one and stores a frame to compare the bodies, Pi two. When the argument types match, the body comparison becomes current and its frame is removed. Each transition returns to the driver; comparison continues at the next binder.pending framescompareno framesΠ₁Π₂A₁no framesΠ₂

Each arrow returns to the driver. Open both bodies with the same stand-in for x₁, then continue at the next binder.

Go back to the deeply nested type. Comparing the outer Π types gives us two jobs: compare their argument types, then compare their bodies. While comparing A₁ with A₁, we keep the body comparison as pending work. Once the argument types match, we open both bodies with the same stand-in for x₁ and continue at the next binder. Each transition returns to the driver with the remaining work in its state. The driver can keep advancing through the nested type.

Now I can choose the next transition.

The hijacker in Captain Phillips points to his eyes while taking command.
Look at me.

I'm the evaluator now.

I set out to build an evaluator. Handling deeply nested terms meant taking control of its pending operations too. Now it can choose the next transition. Something still has to run those transitions, and the worklist we borrowed earlier retains states the machine no longer needs.

Why am I keeping every state?

genericClosure keeps every visited state reachable from its result.

The original counter: key and total
Code
{ key = 0; total = 0; }
The visited list holds every state until return
The visited list holds every state until returnStates zero, one and two enter the visited list at successive steps. None is released, so the number of held states climbs and all three remain reachable when the driver returns.123s2s1s0drivertraversal stepsstates heldThe visited list holds every state until returnStates zero, one and two enter the visited list at successive steps. None is released, so the number of held states climbs and all three remain reachable when the driver returns.123s2s1s0drivertraversal stepsstates held

Each held state keeps the data it references reachable.

The original counter carries key and total. genericClosure returns every visited record. The count rises because earlier records remain held as new ones arrive. Forcing their fields does not remove the list's references. With machine states, earlier records can retain references to work that later states have finished. A shared frame stays reachable through any earlier state that still refers to it.

genericClosure keeps every visited state reachable from its result.

The visited list holds every state until return
The visited list holds every state until returnStates zero, one and two enter the visited list at successive steps. None is released, so the number of held states climbs and all three remain reachable when the driver returns.123s2s1s0drivertraversal stepsstates heldThe visited list holds every state until returnStates zero, one and two enter the visited list at successive steps. None is released, so the number of held states climbs and all three remain reachable when the driver returns.123s2s1s0drivertraversal stepsstates held

Each held state keeps the data it references reachable.

A skeleton waits at a computer.
Me waiting for the garbage collector

while holding every visited state

The garbage collector cannot free records that remain reachable through the returned list. Waiting does not change that, even when every field has been evaluated.

Run several steps per fold, then recurse into another chunk.

The list supplies iterations; stepIf computes the next state
Code
chunk = builtins.genList (i: i) size;
after = builtins.foldl' stepIf state chunk;
fold chunks₀ → s₁ → … → sₖ
unfinished: recurse
fold next chunksₖ → … → sₘ

Finished: return the answer. Each recursive call leaves one driver call waiting.

nix-effects / src/tc/eval/machine.nix

The main CEK evaluator uses chunked strict folds. Each chunk is a list of iteration tokens: stepIf ignores their values and computes the next machine state from the current one. A finished state passes through the remaining callbacks unchanged. At the chunk boundary, the driver returns the answer or recurses with the resulting state. It discovers how much work remains as it runs. The fold carries an accumulator without constructing a list of every visited state. References in that accumulator can still keep older data reachable. After four initial transitions, the implementation uses shared chunks of 8, 16, 32 and so on up to 32768 iterations, then reuses that largest chunk. Each recursive call between chunks still consumes stack. This pattern can drive effects too; the published effects interpreter still uses genericClosure, and the quotation driver retains states at chunk boundaries.

A direct way to run the next step

Keep taking steps until the program finishes.

Thanos regards his opponent after receiving a small cut in Avengers: Infinity War.

All that for a while loop.

The worklist collects states. The illustrated chunk driver requires iteration tokens and recursive calls between chunks. Both can drive explicit machine steps, with different costs. The operation I wanted was to take a step, carry its state forward, and repeat until finished.

What I need is a while loop.

Code
run = state:
  let next = step state;
  in
    if next.done
    then next.value
    else run next.state;

This is the run function from the beginning. Each step returns either another state or the final answer. genericClosure supplies repetition but collects the visited states. The illustrated chunk driver avoids that collection but leaves recursive calls between chunks. Bounded nested folds can remove those calls by scheduling a finite budget, including unused outer ticks. A native loop could repeat directly until completion. The interpreter would still choose what to force and represent its pending work as frames.

A native trampoline could run those steps directly.

Interface sketch for a native primitive
Code
builtins.trampoline step initialState
Each step returns another state or the final answer
Initial stateinitialState
Native driverstep currentone call, then a reply
finished
Final answerresult
continue: next state becomes current

The machine's frames and forcing policy stay in the program.

A native trampoline would call step, get back either the next state or the final answer, and repeat once the call has returned. It would need neither a visited-state collection nor recursive calls between finite chunks. The step would still decide what to force, and frames would still describe pending work. This is a sketch of the interface; the evaluator used for these examples has no such builtin.

Should Nix provide this directly?

Nix already hosts languages with their own semantics.

The module system collects, merges and checks option definitions.

Should every interpreter have to build its own loop?

Native trampoline discussion: NixOS/nix #8430 / hsjobeki's prototype

Much of everyday Nix use happens through domain-specific languages. The module system is a familiar example: option declarations and definitions are collected, merged and checked under rules implemented in Nix. Those rules give the configuration language its semantics. An interpreter may need to keep processing work discovered during execution, with the next state deciding whether to continue. nix-effects exposed the stack, forcing and memory costs of expressing that repetition with the available primitives. Other interpreters can encounter the same constraints as their inputs and workloads grow. Should each implementation reconstruct a driver, or should Nix provide a documented way to run explicit steps until completion? A native trampoline or suitable tail-call support could supply that mechanism. State representation and forcing would remain the interpreter's responsibility. The existing proposals are a place to continue that discussion.

And that’s how I nearly lost my mind writing a loop in Nix.

nixcon2026.bohinen.no

Runnable examples - reading - PDFs

nix-effects / Native trampoline discussion

sternenseemann: trampolining Nix (2022)

I wanted to see what could be written in Nix. Running it meant working out how to loop without growing the stack, what to force at each step, and how to turn pending calls into data. A native loop would make the first of those much simpler. Thank you to sternenseemann for the genericClosure trampoline discussion, hsjobeki for exploring a native primitive, and the nix-effects contributors.

Sum requested memory

Sum the memory requested by service configurations and keep a report of entries missing a port. The report is only needed when requested.

let
Definitions
n = 100000;
entries = builtins.genList
  (i: if builtins.bitAnd i 1 == 0
      then { memoryMiB = 512; }
      else { memoryMiB = 1024; port = 8080; }) n;
makeReport = entries: builtins.toJSON
  (builtins.filter (entry: !(entry ? port)) entries);
diagnostics = makeReport entries;
initial = { total = 0; inherit diagnostics; };
result = builtins.foldl'
  (acc: entry: { total = acc.total + entry.memoryMiB; inherit diagnostics; })
  initial entries;

Empty source

    Inspect the record's fields without asking for the memory total or the report.