Skip to content

Commit Loops

Commit loops are the core Nilakan feature. They initialize state with init, run a while guard, stage primed next-state updates, and commit those updates together at the end of each round.

A commit loop expresses one repeated state transition. This is useful for algorithms that are most naturally written as difference equations: each round reads the current state, computes the next state, and then commits the next state all at once.

In a loop over state x, x means the current value for this round and x' means the next value being staged. At the beginning of every round, Nilakan seeds x' from x. Explicit primed assignments override that seed. At the commit boundary, x' becomes x for the next round.

def exchange() -> tuple[num, num]:
init:
left = 1
right = 2
done = False
while not done:
left' = right
right' = left
done' = True
return left, right
Run in playground

init must be adjacent to the while it introduces. State names assigned in init may be assigned with one prime in the loop body. init assignments may also carry type annotations.

Fragment — valid only immediately before its while
init:
i: num = 0
seen: set[str] = set()

pragma acc_prime: sequential may appear as the first statement inside a commit-loop body. It applies to that containing loop. A bare nested while is only valid inside a commit-loop body, where it becomes another commit loop.

Sparse list and dict updates use primed subscript assignment.

def swap_first_two(xs: list[num]) -> list[num]:
init:
items = xs
done = False
while not done:
items'[0] = items[1]
items'[1] = items[0]
done' = True
return items
Run in playground

Before each round, Nilakan applies the following rule to every state variable:

  1. Copy the current value into the next-state layer.
  2. Apply the primed writes selected by that round.
  3. Commit the complete next-state layer together.

Therefore, omitting a primed write means “retain the current value.” It does not mean “clear the value,” “reset it to its initializer,” or “leave it undefined.” Sparse list and dict updates depend on this seed: items'[1] = value starts with a copy of items, replaces one position in that copy, and leaves every other position unchanged.

Temporary assignments inside a commit loop are local to the round. By default, Nilakan schedules the round with a dependency DAG over temporaries, branch guards, and staged writes.

State variables must be updated with primed assignment. Unprimed assignment to a state variable inside the loop body is rejected.

Branches in a commit loop are selected once for the round. Mutually exclusive branches may write the same primed target.

A normal guard is checked before the round. A guard containing a primed value requires a speculative round to create that next state, and a false result discards it.

Normal commit loops use a dependency DAG for temporaries and next-state equations. A primed read observes its effective definition, scheduled before the consumer, or the seeded current value if that location has no definition. Unprimed reads always observe the frozen current state.

The scheduler is deterministic. Dependencies always run before their consumers. When two nodes are ready at the same time and neither depends on the other, they run in source order. Visualizations should display that same order.

if, elif, and else can appear anywhere in a loop body and can nest. Each guard must be boolean. Guards are evaluated once, in order, until one succeeds. Later guards and unselected bodies do not execute or contribute dependencies to the round.

Selecting a branch adds its statements to the active dependency graph. Those statements can run between statements from the containing block when their dependencies require it. A conditional is not an indivisible scheduling unit.

def choose(flag: bool) -> num:
init: result = 0; done = False
while not done:
if flag:
chosen = 3
else:
chosen = 4
doubled = chosen * 2
result' = doubled
done' = True
return result
print(choose(True))
Run in playground

This prints 6. Assignments in a selected branch make their temporary values available to later code in that round. An existing temporary keeps its incoming value when a branch does not replace it. A new temporary remains uninitialized on paths that do not assign it; reading it on such a path raises UndefinedVariableError. A declaration in some branch does not give the name a default value. Temporaries are recreated for every round, so a value from an earlier round cannot fill that gap.

Separate conditionals may share a temporary when their selected path initializes it before use:

def maybe_double(flag: bool) -> num:
init: result = 0; done = False
while not done:
if flag:
chosen = 3
if flag:
result' = chosen * 2
done' = True
return result
print(maybe_double(False))
Run in playground

This prints 0: neither branch runs, so the program never reads chosen and result retains its seeded value. DAG scheduling also allows a first use to precede its declaration in source when the selected dependencies are acyclic. Temporary reassignments preserve the values observed by earlier consumers. A later assignment in the containing block cannot replace a branch’s local value before that branch consumes it.

Dependency cycles within any conditional branch body are rejected statically, even if that branch is not selected at runtime. Only selected branches and tested guards contribute dependencies to the runtime schedule.

Next-state dependencies include whole values, sparse components, function arguments, and guards. For example, total' = total + i' may appear before i' = i + 1: the scheduler evaluates the latter first. Distinct literal components can depend on one another. Dynamic or negative indices are treated conservatively because they may name the same component.

Self-dependent equations such as x' = x' + 1, and mutual dependency cycles, fail with NLK3012. A conditional guard that depends on the value defined by its own branch is also cyclic. Use sequential accumulation when an expression needs to read and replace the accumulating draft.

Standalone function call statements act as scheduling barriers: statements before the call stay before it, and statements after the call stay after it.

Output is part of a round’s transaction. A print(...) call records output in the active round. Nilakan publishes those records, in call order, only when the round commits. It discards them when a primed guard rejects a speculative round or when the round fails.

Nested rounds merge committed output into the containing round rather than publishing it early. If the containing round is later discarded, output from its nested loops is discarded with it. Output outside a commit loop is immediate.

The first statement in a loop body can select an accumulation contract:

def ordered_total() -> num:
init: total = 0; done = False
while not done:
pragma acc_prime: sequential
total' = total' + 1
total' = total' + 2
done' = True
return total
print(ordered_total())
Run in playground

This prints 3. Sequential mode executes each statement once in source order. Primed reads see the latest draft, initially seeded from current state. Repeated scalar and component writes are allowed. A whole-container write replaces earlier sparse changes; later sparse writes patch that replacement. Index expressions and right-hand sides are evaluated at their source positions. Destructuring evaluates its entire right-hand side before writing its targets.

Unprimed reads remain frozen throughout the round. Temporary values must be available before use; source-order mode does not support forward temporary references. Bounds checks and type contracts apply to every write. The final draft commits once, together with the round’s output.

Mode Contract Executable today
no pragma Acyclic, single-definition next-state equations yes
sequential One ordered sweep over the accumulating draft yes
convergent Stabilization under every permitted fair schedule no
monotone_convergent Monotone fixed-point construction over a checked order no
idempotent Repeating an ordered sweep preserves its result no
confluent Reachable states have a unique reachable normal form no
associative_commutative Exactly-once reduction by a lawful operation no

The five remaining names are recognized but rejected with UnsupportedPragmaModeError/NLK3013. Their evaluators and verification checks are planned; selecting a name does not assert that its mathematical law has been checked. Ordinary acyclic dependencies require no pragma.

A directive applies only to its containing loop. Nested loops select their own policy and use ordinary equations by default. A directive after an executable statement, in a conditional branch, between init and while, or duplicated in one body fails with NLK3010.

If a guard reads primed state, Nilakan runs a speculative body round before evaluating the guard. When that guard exits the loop, the final speculative next state is discarded. Errors raised while computing the speculative round are still reported. The example returns limit - 1 for a positive integer limit: when the speculative next value reaches limit, the guard becomes false and that round is discarded.

def advance_until(limit: num) -> num:
init:
x = 0
while x' < limit:
x' = x + 1
return x
Run in playground

Nested commit loops apply the same current/next rule one prime layer deeper.

Context Current Next
outer loop x x'
nested loop x' x''
third-level nested x'' x'''

Statements preceding a nested loop finish before it starts. The inner loop treats the parent’s staged next-state layer as its current layer. When the inner loop commits, x'' becomes x'; when the outer loop later commits, x' becomes x.

In equation mode, reading x' before a nested loop that may write x'' creates a dependency cycle across this scheduling boundary and reports NLK3012. This also applies to overlapping list slots and dictionary keys, including conditional nested writes. Place the read after the nested loop to consume its committed result. With pragma acc_prime: sequential in the containing loop, an earlier read observes the draft value available at that source position.

Likewise, a nested loop cannot read a parent’s draft value whose producer appears after the boundary in equation mode. Move that producer before the nested loop, or use sequential mode in the containing loop when the nested read should observe the earlier draft.

For the nested loop, x' is current state and x'' is next state. Ordinary reads of x'' follow that loop’s own dependency graph. Reading and replacing x'' in a self-dependent update requires pragma acc_prime: sequential first inside that nested body.

Primed assignment is only legal inside a commit loop. In default equation mode, duplicate primed writes to the same target on the same path are rejected. Sequential mode permits repeated writes. Sparse primed updates are implemented for lists and dicts, not for sets or tuples.

In default equation mode, whole writes and sparse writes to the same state variable conflict on the same path. Duplicate literal sparse slots or keys also conflict on the same path. Mutually exclusive branches may write the same state variable. Separate conditionals may also select writes to the same target when only one of those writes executes. Conditional conflicts are checked against the selected round; an unselected write does not conflict with an executed write.

A nested invocation contributes its executed, committed write locations to the enclosing round. Multiple inner rounds contribute one combined footprint. Default equation mode checks that footprint against sibling writes; sequential mode permits their ordered overlap. Writes in unselected branches or discarded speculative rounds do not contribute. An inner whole write covers that variable’s component writes at the parent boundary.

Set and tuple sparse primed updates are rejected.

A nested loop is a scheduling boundary. When it finishes, execution resumes with the remaining statements in the containing branch or loop body. Statements after that boundary may consume its committed result from the parent’s next-state layer. Output from both the nested loop and the resumed statements remains part of the enclosing round’s transaction.

Commit loops finish only when their while guard is false. break, continue, and early return are not supported in their bodies, including inside conditional branches.

Nested loops inherit parent state at the current prime depth. A nested init can create local state with unprimed spelling, and that local state does not leak after the nested loop exits. A nested init can also override inherited state at the inherited spelling, such as init: x' = x + 1 inside a loop where x' is the nested current state. New nested local state must use unprimed spelling.

The default maximum source prime depth is 5.

Sparse list update:

def swap_edges(values: list[num]) -> list[num]:
init:
arr = values
step = 0
while step < 1:
arr'[0] = arr[2]
arr'[2] = arr[0]
step' = step + 1
return arr
print(swap_edges([1, 2, 3]))
Run in playground

Next-state dependencies:

def accumulate() -> list[num]:
init:
xs = [1, 2]
step = 0
while step < 1:
xs'[1] = xs'[0] + 1
xs'[0] = 11 if xs[0] < 11 else xs[0]
step' = 1
return xs
print(accumulate())
Run in playground

This prints [11, 12]. The definition of index 0 runs before the consumer at index 1, even though it appears later in the source.

Nested next-state dependencies:

def nested_next_read() -> num:
init:
i = 0
total = 0
outer = 0
while outer < 1:
outer' = outer + 1
while i' < 1:
total'' = total' + i''
i'' = i' + 1
return total
print(nested_next_read())
Run in playground

Duplicate write error shape:

Intentional failure — NLK3005
def bad() -> num:
init:
x = 0
while x < 1:
x' = 1
x' = 2
return x