An endless scheme loop happens when evaluation keeps returning to the same state: a recursive procedure that never reaches its base case, a macro that expands back into itself, a build rule that regenerates its own input, or a chain of scheme transformations whose "next" step equals the "current" step. The fix is not one trick but an ordered procedure: reproduce the cycle, instrument the state, prove that some measure is decreasing and that the base case is reachable, then change the algorithm or the guarding condition so termination is guaranteed by construction. If a measure can't be found and the loop is expected to continue, the correct action is an explicit cycle check or a hard iteration bound, not a bigger timeout.

The rest of this article works through that procedure in order. "Scheme" is kept in its general sense, because the same failure mode appears under that name in three places: Scheme-family Lisp code that overflows its stack, recursive rewriting systems such as graph schemes and term-rewriting macros, and combinatorial "schemes" like the Josephus circle, path-covering puzzles, and Horner's evaluation scheme. The diagnosis steps are shared; the escape differs by case, so each gets concrete treatment.

When "Endless Scheme Loop" Actually Means Stack Overflow

In Scheme and other Lisp dialects, an endless loop usually announces itself as unbounded recursion. Guile, Chez, Racket, and most other implementations perform tail-call optimization, so a self-call in tail position runs in constant stack space—which means an accidentally infinite tail loop hangs without an error, while a non-tail loop overflows. A recursive function that calls itself with a slightly changed argument and no terminating branch will do exactly that.

The first job is to classify the symptom. If the process keeps running and one CPU core sits at 100 percent with flat memory, you likely have a tail loop that never terminates. If memory climbs steadily or you get a stack-overflow error, the recursion is non-tail and the chain of frames is growing. A hang with near-zero CPU suggests the loop is waiting on I/O, a mutex, or a condition variable inside the recursion. Each point to different instrumentation.

For the classic Scheme case, the terminating structure you want is a named let with an explicit test and a tail call:

Success here is checkable: the test (>= i 10) is false initially, i strictly increases each iteration, and the base case is reached in exactly ten steps. A bug that breaks this—say (loop i …) instead of (loop (+ i 1) …)—leaves i unchanged, the test never becomes true, and the tail loop spins forever. That single-character class of bug is the most common source of the endless loop, and the remedy is the structural discipline in the next sections rather than a patch.

If your loop is non-tail (for example, it must do work after the recursive call), you can convert it to tail form by carrying an accumulator, which buys constant stack space. Occasionally the conversion is not possible without changing the algorithm, and then a bounded depth is the honest answer: pass an explicit depth parameter and stop with a clear error at a documented limit instead of crashing the runtime.

Reproduce the Loop and Capture the Repeating State

Before changing code, make the loop visible and reproducible. Random or time-dependent inputs hide the cycle, so freeze the seed and the input. Then decide what "state" means for your scheme: the argument tuple of a recursive call, the left-hand side and right-hand side of a rewrite rule, the pair of nodes in a graph traversal, the full environment of an interpreter. A loop exists when the sequence of states revisits a state you have already seen.

A concrete recording method is cheap and works in nearly any language: log each state with a sequence number, then scan for the first repeated state and the distance between the two occurrences. That distance is the period of the cycle, and the prefix before it is the run-up. In a Scheme tail loop, log i and acc length every hundred iterations. In a macro expander, log the rule name and a hash of the term. In a graph scheme, log the visited set and the current node. The moment you can print "state at step 57 equals state at step 43," you have converted a mystery hang into a named cycle of period 14.

Two cautions apply to this recording step. First, log state that fully determines the next step. If you log only a counter, a loop that changes something else will look identical at every step and mislead you. Second, avoid logging inside a hot inner loop at full verbosity for a long run; sample instead. A practical compromise: record the first ten thousand states in memory in a ring buffer, the last ten thousand as well, and detect a repeat across that window—periods longer than the window will evade detection, which is itself diagnostic information.

The output of this step is a minimal reproducer: the smallest input and the shortest state trace that still loops. Everything after this point is verified against that reproducer.

Find the Invariant That Should Decrease

Termination arguments in computer science rest on a well-founded ordering: a measure maps each state to an element of a set with no infinite descending chains—typically a non-negative integer, or a lexicographic tuple of naturals—and every transition strictly decreases it. A loop is endless precisely because either no such measure exists, or the measure is not actually decreasing, or the base case is unreachable.

For an integer counter loop, the measure is the distance to the bound: bound - i when i counts up. The bug where i never changes makes the measure constant, not decreasing, and the proof fails immediately—which is exactly what the loop is telling you. For a recursive evaluator, the measure might be the size of the expression, the nesting depth, or the multiset of pending subgoals ordered by a ranking function. For a rewriting scheme, a common measure is term size or a polynomial interpretation of the function symbols, and a rewrite system is terminating if such an interpretation exists and each rule strictly reduces it.

Write the measure down explicitly, in a comment or a spec line, and check three things at the reproducer: it is non-negative, it strictly decreases on every transition, and zero is actually reachable from the initial state. Each failure maps to a distinct cause. Measure not decreasing: the step logic is wrong or the state update is missing. Measure decreasing but never reaching zero: the base-case condition is inconsistent with the measure—for example, i starts above the bound, or the comparison is strict when it should be non-strict. No measure expressible at all: the scheme is genuinely non-terminating on that input, and no amount of guarding will make it terminate; you must change the algorithm or add an external stop.

The reachability check is the one people skip. A loop where i decreases from 10 to 0 but the test is (= i 1) never fires at the intended point and either stops one step early or, if the update skips 1, never stops. Simulating five steps by hand on paper remains the fastest way to catch this.

Prove the Base Case Is Reachable, Then Check It With a Bound

A termination guarantee combines a decreasing measure with a reachable base case. In practice, add a hard iteration bound as a check even after you believe the proof, because the bound converts a silent hang into a loud failure that points at the exact state. The bound should be derived from the input, not picked arbitrarily: for a loop over n items with at most k retries per item, the bound is n * (k + 1) + 1. When the bound fires, throw an error that includes the state at failure, which is often enough to identify the missed update.

Illustrative calculation, with hypothetical inputs chosen to show the arithmetic: suppose a retry scheme processes 250 records and allows each record up to 3 re-evaluations before moving on. A correct bound is 250 × 4 = 1,000 iterations plus a final check, so 1,001. If the loop reaches 1,001 iterations, at least one record is being re-evaluated without the "move on" condition ever firing—a real bug, not a slow input. That reasoning is reproducible for any n and k and does not depend on runtime speed.

Be honest about what the bound does and does not prove. A bound that fires correctly proves the guard works and localizes the failure; it does not prove the algorithm terminates on all inputs. Conversely, a run that stays under the bound proves only that this input terminated, not that all do. The proof lives in the measure argument; the bound is the regression test. Once a bound is in place, a failure becomes an assertion with a reproducible state trace instead of an outage.

One practical note on the check: make the bound's error message include the measure's current value and the last transition. If the message says "iteration 1,001, measure 4, previous state identical to state at step 997," you have both the remaining distance and the period, and the fix is usually a one-line missing update.

Escape by Rewriting the Step Function

Most endless scheme loops are not deep design flaws; they are a step function that maps a state to itself or to a predecessor. The first escape is to restructure the step so progress is structural: make each iteration consume part of the input and carry the rest, rather than mutating a variable that may be forgotten. In Scheme terms, prefer (loop (cdr xs) …) over (loop i …) when the input is a list, because cdr cannot fail to progress, whereas an index can.

The second escape is the standard three-part loop skeleton: initialize, test, update, with the update written as a total function that is visibly different from its input. For example, a path-covering or graph-walk scheme should track visited nodes in a set and refuse to re-enter one; the visited set both prevents the cycle and documents it. A rewriting scheme should apply rules in a fixed order and stop when the normal form—no rule applies—is reached; if the normal-form test is wrong, rules re-apply forever, so test it independently by checking that the term after a claimed final step is unchanged by every rule.

The third escape is the explicit cycle check, which is the right tool when termination genuinely cannot be proven because the scheme is designed to explore indefinitely, as in a search over unbounded states. Maintain a set of canonicalized states—hash the term or serialize the tuple—and stop when a state repeats. Deduplication by canonical form is what makes this correct: two states that differ only in variable names or in ordering of a commutative operand are the same state and should hash the same. Bloom filters are tempting here and are acceptable when a false positive merely stops a search early, but not when it silently changes a computed result.

A worked walkthrough shows how the escapes differ. Consider a toy rewriting scheme with rules A → B, B → C, and C → A. On input A, the trace is A, B, C, A, … —period 3, no normal form. The measure approach cannot save this rule set because no ranking function makes all three rules strictly decrease; you must either delete a rule, or add a cycle check that stops on the repeated A. A different rule set, A → B, B → C, with no C rule, terminates at C and needs no cycle check at all. Same shape, opposite outcome: the rules decide which escape is correct, not the code around them.

Break Out of Combinatorial Scheme Traps: Josephus and Recursive Path Counting

The word "scheme" also labels classic puzzles whose naive solutions recurse forever. The Josephus problem is the clearest case: n people in a circle, every k-th eliminated, last survivor wins. A direct step-by-step simulation with a shrinking circular list terminates for every positive n and k and is easy to verify by hand for n = 5, k = 2 (survivor position 3 when counting from 1). The trap appears when someone tries to define the survivor by a recursive rule without specifying which direction the position is measured from, which yields a circular definition rather than a recursion. The standard recurrence J(n) = (J(n - 1) + k - 1) mod n + 1 with J(1) = 1 is a genuine recursion on n with an explicit base case for exactly this reason. A further trap: reducing k modulo n is valid only in contexts where the circle shrinks by one each step; applying a modulo shortcut in a variant where multiple eliminations happen per pass changes the answer, so verify the reduction against direct simulation on small inputs before trusting it.

Recursive path counting has a parallel failure. Counting simple paths, or the number of ways to cover a board with polyominoes, must treat each placement as consuming the cells it covers, so the remaining problem is strictly smaller. A scheme that tries to count coverings while allowing a piece to be placed again over partly used cells does not recurse on a smaller problem—it recurses on the same problem, forever. The test that catches it is a check that the measure (uncovered cells) strictly decreases with each recursive call. If a call can leave the measure unchanged, the recursion is not well-founded, regardless of what the base case says.

Both cases share a practical rule: write the termination condition as a property of the data (no uncovered cells, one person left), not of the call depth. If no such property exists, the formulation is wrong, and the fix belongs in the problem statement, not the recursion.

Fix Macro and Rewrite Cycles in Build and Code Generation Schemes

A macro scheme that expands back into itself is the hardest version to see, because it looks perfectly normal. The macro A expands to something containing B, B expands to something containing A, and the expander recurses or loops. Compilers limit expansion depth precisely because this is possible, so a build that hangs in a macro expansion phase, or a code generator that keeps emitting the same construct, is a cycle-suspect.

The escape order for this case is: (1) ask the expander to print the step-by-step expansion for the failing input, if the tool offers it; (2) hash each intermediate expansion and log the chain of hashes; (3) on the first repeated hash, print the term before and after the repeat—that pair of rules is the cycle; (4) break it by making one rule conditional on a context that eventually holds false, or by converting the recursive pattern into a bounded iteration. A common concrete cause: a rule that rewrites f(g(x)) toward g(f(x)) and another that rewrites g(f(x)) back toward f(g(x)). Both are locally sensible; together they oscillate. The diagnostic is that the measure under any non-negative interpretation is not strictly reduced by both rules—for that pair, no such interpretation exists, and the correct fix is to remove one direction or add an orientation constraint. Rewrite-system literature calls this the non-termination of the rule pair, and it is decidable for finite rule sets in many cases by searching for such interpretations.

Build schemes have an operational analogue: a generated file that is itself an input to the generator. The generated file's timestamp updates, the generator reruns, and the loop is driven by file times rather than recursion. The fix is to separate generated artifacts from source inputs, or to mark generated files with a content hash and skip generation when the hash is unchanged. The success check is simple: run the build twice in a row and confirm the second run does no generation. This content-hash guard is also the standard way to keep incremental builds from oscillating on timestamp changes alone.

Know When to Guard Instead of Prove

Some schemes are supposed to run indefinitely—servers accumulating requests, searches over unbounded spaces, polling loops. For those, termination is not the goal, and the right move is a guard with a documented reason. A guard is acceptable when (a) the loop is genuinely event-driven, (b) each iteration has an independent stopping condition, and (c) a repeated state is either harmless or detected cheaply. A guard is not acceptable when the loop is supposed to compute a fixed result and is instead stuck at a fixed point—there, a guard hides a wrong answer, which is worse than a hang.

The decision test is short. Ask: does the loop's purpose require it to end for this input? If yes, prove termination or add a cycle check. If no, add a guard and make it explicit in the interface—a maximum iterations parameter with a named error—so callers know the bound exists. State each decision once in a comment, including the measured reasoning: "processes at most n × (k + 1) items; longer runs indicate a missed update and fail loudly." Future readers need that sentence more than they need the guard itself.

A specific stop condition matters for the rewrite case: if the cycle persists after you have confirmed the rule pair, removed one direction, and re-run the reproducer, the problem is in the expander's ordering or in the tool itself, and further work should go to the maintainer with the cycle trace and the two rules attached. Patching around a tool bug with a larger expansion limit is the kind of guard that hides the problem rather than fixing it.

A Compact Diagnostic Checklist

Use this as the ordered pass over a stuck loop; each line is a check with a result you can observe.

1: Freeze the input and seed; run the reproducer twice and confirm both produce the same behavior. 2: Record states that fully determine the next step, with sequence numbers; find the first repeated state and the period. 3: Write down the measure, the base case, and the reachability of the base case; test all three against the trace. 4: Classify the termination argument's failure: measure constant, measure not reduced every step, or base case unreachable. 5: Apply the matching escape: add the missing update, convert to tail form with an accumulator, add a canonical cycle check, or rewrite the rule pair. 6: Add a derived iteration bound that fails loudly with the state at failure; confirm the bound exceeds the longest correct run. 7: Re-run the reproducer and confirm it now stops at the base case or at the cycle check. 8: Run a second, independent input to confirm the fix generalizes rather than shifting the hang.

The final check is the one most likely to be skipped: a fix that works on the reproducer but hangs on the neighbor input means the measure argument is still incomplete, and the procedure should loop back to step 3 rather than to step 5.

FAQ

Does tail-call optimization in Scheme make an endless loop invisible? Partly. A self-call in tail position reuses the frame, so a non-terminating tail loop consumes no stack and does not crash—it keeps running, which is why the CPU and state-trace checks matter more than waiting for an error. A non-tail loop still overflows, and the overflow message often names the function and the recursion depth, which is a useful starting point.

Can a rewriting scheme under a fixed elimination order create a cycle that a random or simultaneous scheme would not? Yes. The order of rule application changes which sequence of states occurs. The cycle is still a property of the rules and the ordering together, so the diagnostic should reproduce the exact order the production system uses. Checking termination under one order does not certify another, and a rule pair that oscillates under one schedule may be stable under another.

Is a repeat of just the current position enough to detect a cycle in the Josephus scheme? Not always. A scheme can revisit a position through a different counter phase, so record the position together with the phase information that determines the next step. Detecting a repeat of the position alone can stop early on a legitimate revisit and change the answer. Record the full state, or a canonical hash of it, and compare those.

If no decreasing measure exists, is adding a counter bound legitimate? Only if the bound is derived and documented and the loop genuinely need not terminate—for example, an unbounded search. In a computation expected to produce a fixed result, the bound converts a wrong answer into an error, which is preferable to silence but is not a fix. Find the non-reducing rule or update and change it.