ADR-chain-loop-v2: A Chain Is One Loop the Compiler Writes, With No List Between Its Steps and No Step Library; a Chain Kept as a Value Is a State the Compiler Writes; Where Its Lambdas Touch Nothing, the Order They Run In and Where an Overflow Stops It Are Not Fixed

Status: Accepted Date: November 30, 2026 (the consolidation: D8 joins this record, #2925); D6 and D7 November 29, 2026 (owner, #2899); D8 October 3, 2026; the other decisions October 12, 2026 (#595) History: the records this one replaces are archived in docs/history/adr; read them only for how the decisions were reached Answers: whether xs.map(f).map(g) builds a list between its two steps; what the compiler may change in a chain so that the chain a program writes runs as the loop a person tunes by hand, with every check the language promises; and how a chain over a sequence is lowered: as a pipeline of library steps, or as a loop the compiler writes, and what a chain kept as a value becomes (#2899); what a sequence’s pipeline allocates, what type its map hands on and what type its counts are (D8) Supersedes / Related: takes every decision of the record before with its number, D1-D7, and as D8 the decision on a sequence’s pipeline from the record on maps, sequences and takings now in the history (one loop with nothing allocated between its steps, stated as D6 lowers it); ADR-collections-v4 D27-D30 (what a sequence says it is as a whole, and every place it is taken), D33 (a list’s windows and chunks hand out runs); ADR-285 D1 (no usize a program meets); ADR-prover-checks-v1 (a check a proof shows unneeded is not emitted, and the program means the same either way); ADR-327 D5, D10 (what a task allocates counts against its budget); ADR-375 D4 (a consumer right after a std sequence is the one the ledger names); ADR-stream-buffers-v1 D1, D2 (a stream’s item views a pool buffer for one turn); ADR-361, ADR-proof-kani-v1 D2 (a loop’s invariant, proved and checked on the emitted loop); ADR-platform-layer-v1 (Rust only as a platform call with no decision in it); Part I 4.5, 5.3 (a list’s map is a list), Part III 13.5 (touches), Part III A.2 (an overflow stops the task and names its line), Part III’s Seq[T] (not in a program’s type grammar, walked once, NK2702)

1. Question

How does a chain run, and what may the compiler change in it? Three questions under one: may a chain over a list run its steps element by element; is a chain over a sequence lowered as a pipeline of library steps or as a loop the compiler writes; and what does a chain become that a program keeps as a value instead of consuming where it is made.

A list’s map hands back a list (Part I 5.3), so xs.map(f).map(g) walks the list twice and builds a list nobody names between the walks. Under ADR-327 that list takes room in the task’s block. A chain over a sequence, xs.iter().map(f).filter(g), was lowered to the language below’s iterator adapters (the lowering D8 had before D6), which the language below fuses into one loop; but every overflow check in it is a branch per element, and a loop with a branch per element is not vectorized; a filter with two conditions is two branches per element. A program written as a plain chain - the way a model writes it - is the one that has to be fast.

The adapters also hide the loop from everything that works on loops: the prover’s bounds and invariants and Kani’s loop contracts find no loop in the emitted code, only a call into the iterator’s implementation, and a view lent for one turn (io::lines()’s items, ADR-stream-buffers-v1 D1) does not fit an adapter that hands out owned items, so std grew a second step library in Rust for it (#2881), with decisions in it (how take counts a failed line).

A chain need not be consumed where it is made: a program may push it into a list and walk it after drain() (what NK2702’s help advises), keep it in a generic struct’s field or a tuple, or choose between two chains with if. What such a chain is at run time has to be decided with the loop.

2. How others do it

Language / tool Its answer What it costs there Source
Rust iterators, C++20 ranges, Swift lazy sequences lazy: each chain is a value of a type per shape (Filter<Skip<Iter>, F>), a struct with the cursor, the counters and the closures; the generics write the type, and the loop appears when the language below inlines next an item lent for one step needs a lending iterator (generic associated types), which Rust’s std does not have; two chains of different shapes in one list or one if need Either or Box<dyn Iterator> (a dynamic call and an allocation), written by hand from memory, not checked
Java streams, C# LINQ, Kotlin Sequence a library pipeline of objects, single use in Java as fast as the JIT inlines it; C# writes a state machine class for a yield generator, the compiler’s own state type from memory, not checked
Kotlin List.map, Swift Array.map a list per step; asSequence() / .lazy to fuse the fused form is a second spelling from memory, not checked
Haskell (GHC) fused by rewrite rules (foldr/build, stream fusion) where producer and consumer meet in one expression where a list is kept or shared, fusion does not fire and the program falls back to the lazy list, a library at run time, silently and much slower from memory, not checked
Go 1.23 range-over-func: push iterators, func(yield func(T) bool); the producer calls the loop body an item valid only during the call is natural; zipping or merging two producers needs a pull adapter (iter.Pull, a coroutine) from memory, not checked
Julia, Halide, Futhark the compiler fuses: dot broadcasting, scheduled pipelines, array fusion; what is kept is materialized lazy sequences as values do not exist (Halide, Futhark) or are Rust-like types (Julia’s generators) from memory, not checked
Mojo vectorized where the program writes it: SIMD[DType, n], vectorize the fast code is a second program; integer overflow is not checked from memory, not checked
C and C++ compilers loop fusion and vectorization only where the effects allow a check per element (-ftrapv) stops vectorization from memory, not checked

What does not transfer: Haskell’s purity. Nikaia knows per lambda whether it touches anything (Part III 13.5) and whether it changes a name outside it (NK2107), so D1 can ask what Haskell takes for granted. What transfers: the fast languages all give a kept chain a state type per shape (Rust, C++, Swift, C#’s generators); none of the languages with lazy sequences as values refuses to keep one. What Nikaia has that they do not: a sequence is not in a program’s type grammar and is walked once, so the compiler sees every chain from its producer to its consumer.

3. Options, weighed

For D1-D5, a chain over a list:

Option Why it lost, or won
A Keep every step’s list, as today passes and memory the program never asked for
B A list’s map becomes lazy everywhere, as Rust’s changes the order of effects in programs that print or read in a lambda, and let ids = users.map … stops being a list
C Fuse only where nothing at all could differ, panics included nearly every lambda with arithmetic can overflow, so it would almost never apply
D Explicit vector types, as Mojo the fast program is a second program; the plain chain stays slow
E Element by element where the lambdas touch nothing; which panic stops such a chain, and where an overflow does, not fixed chosen
  D1 the special case pays D2 the compiler works D3 no cost for the common case D4 consistent If it is wrong
A yes yes no: a pass and a list per step yes -
B no: programs with effects change yes yes no: map is a list in 5.3 silent reordering of output
E yes: a chain that panics twice may report the other one yes yes yes: a chain over a sequence already runs element by element a panic message names the other step

For D6, how a chain over a sequence is lowered:

Option Why it lost, or won
L One step library in the language below that also lends items the steps stay outside Nikaia with their decisions in them (ADR-platform-layer-v1 allows a platform call, not a library of decisions); whatever the compiler knows about the chain ends at the library’s boundary, so D3 and D4 cannot reach into it
P The steps written in Nikaia, push style (Go’s form) every step is a closure chain whose speed depends on the language below inlining it; zip and a merge need a pull form anyway
W The compiler writes the chain as one loop over the producer’s cursor chosen: a sequence is not in a program’s type grammar and is walked once, so a chain is made and consumed in one body and the compiler sees all of it; the loop is where D3, D4, the prover’s and Kani’s invariants and a view lent for one turn work

Whether W gives up speed against a library, case by case: the language below’s fusion is the best a library can reach, and W writes that loop directly; W adds what the compiler knows before the language below sees it (a sized length for collect, a bound the prover drops, a view’s turn); flat_map and early ends are nested loops and breaks, which external iteration reaches only through try_fold; a pausing lambda is an .await in the loop, the same state machine the language below builds. W would lose only where it is built badly: a producer’s own consumer replaced by a loop per item, a flat loop that checks for a refill at every item and so is not vectorized, a push form that cannot zip, or code size. D6’s four rules close each of these.

For D7, a chain kept as a value:

Option Why it lost, or won
a Refuse keeping a sequence in a list, a field or a tuple breaks programs that run today and the form NK2702’s help advises; no language with lazy sequences as values refuses it
b1 The compiler writes a state type per chain shape: the cursor, the counters and the lambdas as fields, and a next whose body is the loop’s body; two chains joined by if become an enum over both chosen: Rust’s, C++’s and Swift’s model, as fast as their iterators, with the type and the enum written by the compiler instead of by generics and by hand
b2 A step library for kept chains only keeps a library in the language below with decisions in it, and falls back silently to the slower path, as GHC does

4. Decision

D1 — A list’s map whose result goes straight into another step runs element by element with it.

xs.map(f).map(g), xs.map(f).iter()…, for x in xs.map(f) and xs.map(f).len() build no list between the steps, where every lambda of the chain touches nothing (Part III 13.5) and changes no name outside it - what a par_iter lambda is asked, except that it may pause. A result that is named, or that a step needs whole (sort, an index), is a list as it is today. A chain with a lambda that touches something runs as written, step after step.

D2 — In such a chain, the order in which the lambdas reach the elements is not fixed, and neither is which panic stops it.

The chain computes the same result in any order. Where more than one of its steps would panic, which one stops the task is not fixed. It stops only for a reason one of its steps has on a value the chain computes as written. This holds for a chain over a sequence too (D8).

D3 — An overflow in such a chain may stop it after its last element.

The compiler may carry an overflow to the end of the chain, or of a run of its elements, and stop there, naming the line of the operation that overflowed, as A.2 does. Nothing the chain computed is seen in between: its result does not exist yet. A value that overflowed reaches no index, division or condition before the stop, so D2’s last sentence holds. This is what lets a chain keep its overflow checks and still be vectorized.

D4 — A filter’s conditions may be read without a branch.

Where a filter’s later condition cannot panic, both conditions may be read and joined with one branch (& for &&). A filter may write every element and move its end by the condition, with no branch at all. Either changes nothing a program means.

D5 — What can be slower than what it replaces is measured, not what can only be faster.

D1 does less work than the steps it replaces, and is built without a measurement. D3 and D4 can be slower: an overflowing_ operation and an or where nothing is vectorized, a write per element where the condition was predictable, a second condition read that a short circuit skipped. Each is emitted for the shapes of chain where a count (instructions and mispredicted branches, callgrind) shows it is not slower than today’s code; elsewhere today’s code stays. D1 is measured for one shape only: a fused loop whose one step would be vectorized on its own and whose other would not.

D6 — A chain over a sequence is one loop the compiler writes, not a pipeline of library steps.

A chain from a producer to its consumer (io::lines().filter(f).map(g).collect(), xs.iter().map(f).sum(), a for over one) is lowered as the loop a person would write: filter a condition, map a value computed in the body, take, skip and step_by counters (take ending the loop), any, all and find an early end, count, sum, fold and join an accumulator, zip a second cursor, a pausing lambda an .await in the body. No step library runs: what stays in the language below is the producer’s platform part (reading into a buffer, handing the next item), with no decision in it (ADR-platform-layer-v1). This replaces the lowering D8 had, through the language below’s adapters; D8’s promise, one loop with nothing allocated between the steps, holds.

The loop is where the rest of this record and of the language works: D3’s overflow carried to the chain’s end is an accumulator across the loop, D4’s filter without a branch is a rewrite of the loop’s body, the prover’s bounds and invariants (ADR-361) and Kani’s loop contracts (ADR-proof-kani-v1 D2) attach to a loop the emitted code has, and a view lent for one turn (ADR-stream-buffers-v1 D1, D2) is a name in the loop’s body, checked as in a for.

Four rules come with it:

  1. A producer’s own consumer first. Where the ledger names a consumer for the producer it follows (ADR-375 D4, find_all(set).count() per block), that is used, not a loop per item.
  2. Two levels where the producer hands out buffers. The loop walks the buffers and, inside, the items of one buffer over a contiguous range, so the inner loop can be vectorized; a flat loop that checks for a refill at every item is not written.
  3. A producer is a cursor the loop pulls from, not a body it calls, so zip and a merge of two producers are loops too.
  4. Measured against what it replaces (D5): no chain is slower than with the library steps it replaces or a plain chain of the language below’s adapters (callgrind, instructions and mispredicted branches), and the code size is reported.

D7 — A chain kept as a value is a state the compiler writes; two chains joined by if are an enum of their states.

A chain pushed into a list, kept in a field or a tuple, or named and walked later where its walk is not in reach of the loop D6 writes, is a value of a type the compiler writes for that chain’s shape: the producer’s cursor, each step’s counter and lambda as fields, and a next that runs the steps’ body once and hands out the next item or none. A walk of it is a loop over that next, so a kept chain is as fast as the language below’s iterators after inlining, with no library. Where an if, a match or the elements of one list join chains of different shapes, the compiler writes an enum over their states, and next dispatches on it. The view rules of the items apply to next’s result as they do to the loop’s name; a kept chain over a stream counts as a place that holds its view (ADR-stream-buffers-v1 D2). The report of a build names, per chain, whether it was lowered as a loop (D6) or as a state (D7).

D8 — A sequence’s pipeline allocates nothing between its steps.

map keeps its element type: $U binds from what the lambda’s body comes to. A chain over a sequence - Seq::rev, zip, take, skip, step_by, and on a list iter, windows and chunks among its steps - is one loop with nothing allocated between the steps, the loop the compiler writes (D6), or, kept as a value, the state the compiler writes (D7). A count - take, skip, step_by, nth, chunks, windows - is an i64 here and a usize below, converted where the call resolved to that entry. enumerate is not among them: its position is a usize (ADR-285 D1).

5. Consequences

6. What this does not decide

This site is open source. Improve this page.