Module contents
Lesson 21 of 22Core 115 min

Computability: Turing machines, undecidability and Rice's theorem

Explore what can be computed using Turing machines, universal interpretation, diagonalization, reductions, Rice's theorem, and the limits of static analysis and logic.

After this lesson you can

  • Program simple Turing machines and reason about configurations.
  • Explain the Church–Turing thesis and the universal machine as an interpreter.
  • Prove the halting problem undecidable by diagonalization.
  • Construct many-one reductions and prove Rice's theorem.
  • Classify program-analysis problems as decidable, semidecidable, or co-semidecidable.
  • State the undecidability of first-order validity and the incompleteness theorems.

Before you start

Motivation: the perfect analyzer cannot exist

Imagine being asked to build a Python static analyzer with a simple specification: given a service’s code, answer “vulnerable” if some input lets unsanitized user data reach a dangerous sink (a SQL query, eval, os.system), and “safe” otherwise. It must have no false alarms, miss no vulnerabilities, and finish in finite time for every program. It sounds like an engineering problem: better heuristics, more cases, more computation.

It is not. A four-line program suffices to see why:

def servicio(x):
    buscar_contraejemplo_de_goldbach()   # para solo si la conjetura de Goldbach es falsa
    consulta(f"SELECT * FROM t WHERE id = {x}")

Deciding whether servicio is vulnerable is equivalent to deciding whether buscar_contraejemplo_de_goldbach() terminates, an open number-theory problem. The trick does not depend on Goldbach: putting any program in place of that call would make a perfect vulnerability analyzer an algorithm deciding whether an arbitrary program terminates. This lesson proves that no such algorithm exists (the halting problem) and generalizes the result to Rice’s theorem: every nontrivial property of program behavior is undecidable. The practical consequence is clear. Every real analyzer chooses which failures to accept: false alarms, missed real cases, or nontermination on some programs.

To get there we must define an algorithm. Turing’s 1936 answer is a machine simple enough to reason about precisely and powerful enough, as far as we know, to compute everything computable. With it we will build, in order, the universal machine (an interpreter), the distinction between deciding and semideciding, diagonalization for halting, reductions, and Rice’s theorem. We conclude with first-order logic, Gödel’s theorems, and a recent frontier: the value of BB(5)\mathrm{BB}(5), determined in 2024 by an open collaboration and verified in Coq.

Turing machines

A Turing machine is a finite automaton (like the deterministic finite automata in the previous lesson) equipped with an infinite tape it can read, write, and move along in both directions. That unlimited, rewritable memory is the entire difference, and it is enormous.

A run is thus a sequence of configurations, and each step is a function: determinism fixes the next configuration from the current one. There are three possible outcomes for each input: the machine accepts (halts in qsıˊq_{\mathrm{sí}}), rejects (halts otherwise), or never halts. This third outcome, absent in finite automata, drives everything that follows. The language of MM is L(M)={w∈Σ∗:M acepta w}L(M) = \{w \in \Sigma^* : M \text{ acepta } w\}.

Recognizing palindromes over {a,b}\{a, b\} takes ingenuity because the machine has no memory beyond its tape and state. The strategy is to erase the first symbol and remember it in the state (one state “carrying aa” and another “carrying bb”), run to the end, check that the last symbol matches, erase it, and return to the beginning. Each pass traverses the whole word, so time is quadratic: O(n2)\bigO(n^2) steps for a word of length nn. Program them and watch them run:

InteractiveTuring machine simulator
000000000111101011A
Table δ(q,s)\delta(q, s): write, move, next state
q \ s01
A
B
C
D
Space-time: one row per step (first 400)
  • 1
  • head
20 steps/s
Steps60
S(4)S(4) known107
StateA
Ones on tape8
Cells visited10
Configuration u q vu\,q\,v  qA  0111101 ⋯\texttt{}\;q_{\mathrm{A}}\;\texttt{0111101}\,\cdots
The 4-state champion (Brady, 1983): 107 steps and 13 ones.
Choose a machine and run it step by step or continuously. The table highlights the next transition; click a cell to reprogram it. At bottom right, the space–time diagram shows the tape at each instant from top to bottom. Compare binary increment (linear) with palindromes (the zigzag of the quadratic strategy). Then explore the 2-, 3-, and 4-state busy beavers and see how many steps they take before halting. The 5-state machine takes 47 176 870: set maximum speed and let the browser execute them all.

Busy beavers

The busy beavers in the figure pose an innocent-looking question raised by Tibor Radó in 1962: among machines with nn states and alphabet {0,1}\{0, 1\} which, started on a blank tape, eventually halt, what is the maximum number of steps? Call it S(n)S(n), and call the maximum number of ones left on the tape Σ(n)\Sigma(n). The usual convention counts the transition into the halting state as a step; it also writes and moves.

The maximum exists because there are finitely many machines with nn states: each of the 2n2n table cells chooses what to write (2 options), where to move (2), and the next state (nn states or halt), giving (4(n+1))2n(4(n + 1))^{2n} machines. For n=2n = 2 there are 124=2073612^4 = 20736 and for n=5n = 5 about 6.3×10136.3 \times 10^{13}. Known values are:

nnS(n)S(n)Σ(n)\Sigma(n)Determined by
111trivial
264Radó (1962)
3216Lin and Radó (1965)
410713Brady (1983)
547 176 8704098bbchallenge (2024)

Finding a machine that takes many steps is easy; the difficulty is proving that none of the other halting machines takes more. That requires knowing, for each machine that has not halted after S(n)S(n) steps, that it will never halt. We will see there is no general algorithmic solution and consequently SS grows faster than every computable function.

Variants that change nothing

There are many reasonable variants: multiple tapes, a tape infinite in only one direction, more symbols, moves that can stay put, nondeterminism. All recognize exactly the same languages. The argument is always simulation. For example, an kk-tape machine is simulated on one tape by interleaving the kk tapes and marking each head position with a special symbol: each original step requires a sweep of the used area, so tt steps are simulated in O(t2)\bigO(t^2). A nondeterministic machine is simulated by breadth-first exploration of its execution tree, at exponential cost. Whether costs are polynomial or exponential matters greatly for complexity, but not for the question “can it be computed?”

Church–Turing thesis

In 1936, several definitions of “effective procedure” were proposed independently and almost simultaneously. Alonzo Church used λ-calculus, a rewriting system for anonymous functions (you will see its typed form in the next lesson); Kleene, building on Gödel and Herbrand, used μ-recursive functions, closed under composition, primitive recursion, and unbounded search; Turing used his machines; Post used a closely related system. The first three were soon proved to define exactly the same class of functions from N\N to N\N. The same has held for every reasonable model proposed since: random-access machines (RAM), cellular automata such as rule 110, rewriting systems, and any general-purpose programming language with unlimited memory.

It is not a theorem and cannot be one: “effective procedure” is an informal notion. The thesis is supported by three kinds of evidence: equivalence of every proposed model, Turing’s conceptual analysis (a human calculator with pencil, paper, and finitely many mental states does exactly what a machine does), and ninety years without a counterexample. In practice it lets us describe algorithms in pseudocode or Python and conclude that a Turing machine exists to execute them. We will do so without further comment.

A programming language able to simulate any Turing machine is called Turing complete. Python, C, C++‘s type system, and even spreadsheet formulas with recursion are examples. A recurrent neural network with infinite precision is too; a transformer with finite context and precision, strictly speaking, is not: it is an enormous finite automaton. “Turing complete” always assumes unlimited memory.

The universal machine: programs are data

A Turing machine is a finite object: a table. Once a convention is fixed, it can be written as a string. For example, the 2-state busy beaver is 1RB1LB_1LA1RH in community notation: blocks by state, each containing transitions for 0 and 1 (here H is the halting state; bbchallenge usually writes Z). We write ⟨M⟩\langle M \rangle for the encoding of MM and ⟨M,w⟩\langle M, w\rangle for that of a pair. The convention does not matter as long as encoding and decoding are computable.

Two consequences follow. First, there are countably many Turing machines, each being a finite string over a finite alphabet. Languages over Σ={0,1}\Sigma = \{0, 1\}, by contrast, are subsets of Σ∗\Sigma^*, which is countably infinite, and by Cantor’s diagonal argument form an uncountable set. Thus almost all languages are no machine’s language: problems without algorithms exist by counting alone. The argument exhibits none explicitly; the next step is to find a natural example.

The second consequence is the most influential idea in Turing’s paper: one machine can execute all the others.

Proof

By the thesis it suffices to describe the algorithm, which is that of any interpreter. UU uses three tapes (reducible to one at the quadratic cost above): the first holds table ⟨M⟩\langle M\rangle; the second, the tape of MM, each symbol of ΓM\Gamma_M encoded in binary using a fixed number of cells; the third, the current state of MM in binary. At each iteration UU reads the symbol under the simulated head, searches the table for the matching state and symbol (a string comparison), rewrites the symbol, moves the simulated head one block, and updates the state. If the simulated state is halting, UU halts with the same result. In the three-tape version, each step of MM costs UU a number of steps depending on ∣⟨M⟩∣\abs{\langle M\rangle} but not ww; in every version UU halts exactly when MM does.

∎

Today this seems obvious because universal machines surround us: the CPython interpreter is a fixed program executing any Python program supplied as data, and exec(src) is literally U(⟨M⟩,w)U(\langle M\rangle, w). In 1936 this was a new idea, separating fixed hardware from interchangeable software, and it helped give rise to the von Neumann architecture. Its theoretical importance is different: it allows programs to reason about programs, including themselves. We will turn this self-reference into a contradiction.

Deciding and semideciding

There are two ways for a machine to “solve” a language LL, depending on what it does with words outside LL.

A semidecider is asymmetric: when the answer is “yes” it eventually says so, but when it is “no” it may compute forever, and at no finite point do you know whether you need more patience or the answer is negative. “Recursively enumerable” comes from an equivalent characterization: LL is semidecidable if and only if a machine prints all the words in LL one after another (possibly never stopping). In the Chomsky hierarchy these are the top level, generated by unrestricted grammars.

Some examples:

  • Decidable. Every regular and every finite language. Whether a DFA accepts any word: search its graph for a path from initial to accepting state. Whether two DFAs accept the same language: construct the product for symmetric difference and check emptiness. Whether a propositional formula is satisfiable: try all 2n2^n valuations (SAT; decidable, though perhaps not quickly).
  • Semidecidable. AMT={⟨M,w⟩:M acepta w}A_{\mathrm{MT}} = \{\langle M, w\rangle : M \text{ acepta } w\}: the universal machine is a semidecider. “There is an input on which the program executes line 42”: run it on all inputs in parallel and accept when one reaches the line.
  • Co-semidecidable. “The program never divides by zero”: if false, a finite counterexample will eventually be found by executing; if true, there is nothing to find.

The technique “run on all inputs in parallel” has a name: dovetailing. One cannot run input 1 to completion and then input 2, because input 1 might never finish. Instead use rounds: in round kk execute kk steps for each input w1,…,wkw_1, \dots, w_k. Every pair (input, step count) is eventually visited, as in the diagonal enumeration of N×N\N \times \N in lesson 3. The same trick proves the theorem connecting the three classes.

One direction is immediate: if DD decides LL, then DD semidecides LL, and the machine running DD and swapping answers decides (hence semidecides) Lˉ\bar L. The other direction dovetails two semideciders, one for LL and one for Lˉ\bar L; you will prove it in a guided exercise. The consequence we use is that if a language is semidecidable but undecidable, its complement is not semidecidable.

The halting problem

It is semidecidable: the universal machine, modified to accept whenever simulation finishes, semidecides it. The question is whether any machine decides it, that is, whether a program para(M, w) always halts and always answers correctly.

Proof

Suppose machine HH decides PARADA\mathsf{PARADA}: it halts on every input and accepts ⟨M,w⟩\langle M, w\rangle if and only if MM halts on ww. Construct machine DD which, on input ⟨M⟩\langle M\rangle:

  1. runs HH on input ⟨M,⟨M⟩⟩\langle M, \langle M\rangle\rangle (always terminating because HH is a decider);
  2. if HH accepts, enters an infinite loop; if it rejects, halts.

DD is a legitimate Turing machine: it is HH with a preamble duplicating the input and a two-state epilogue. By construction, for every machine MM,

D para con ⟨M⟩  ⟺  H rechaza ⟨M,⟨M⟩⟩  ⟺  M no para con ⟨M⟩.D \text{ para con } \langle M\rangle \iff H \text{ rechaza } \langle M, \langle M\rangle\rangle \iff M \text{ no para con } \langle M\rangle.

Taking M=DM = D, DD halts on ⟨D⟩\langle D\rangle if and only if DD does not halt on ⟨D⟩\langle D\rangle. Contradiction, so HH does not exist. The second claim follows from the previous theorem: if PARADA‾\overline{\mathsf{PARADA}} were semidecidable, PARADA\mathsf{PARADA} would be decidable.

∎

The proof is short, but see it for what it is: Cantor’s diagonal applied to programs. Put all machines M1,M2,…M_1, M_2, \dots in the rows of an infinite table and their codes ⟨M1⟩,⟨M2⟩,…\langle M_1\rangle, \langle M_2\rangle, \dots in the columns; cell (i,j)(i, j) records whether MiM_i halts on ⟨Mj⟩\langle M_j\rangle. Machine DD reverses the diagonal: it differs from each MiM_i at (i,i)(i, i), so it is no row. Cantor concluded the table cannot contain every possible row. Turing adds an ingredient: if HH were computable, DD‘s row would be too and DD would have to be in the table, which contains all machines. The contradiction is not in countability, but in DD having to be there and being unable to be there.

The figure makes the argument concrete with actual candidate deciders: an optimist, one simulating a fixed number of steps, one examining the text, and one also detecting cycles. Each gets many cells right, and for each the construction produces a program on which it must fail.

InteractiveBuild a program that fools the decider
⟨P1⟩⟨P2⟩⟨P3⟩⟨P4⟩⟨P5⟩⟨P6⟩P1P2P3P4P5P6haltshaltshaltshaltshaltshalts∞∞∞∞∞∞∞∞∞∞haltshalts∞✗∞✗∞✗∞✗∞✗∞✗haltshaltshaltshaltshaltshaltshalts∞∞∞✗halts∞
  • prediction of HH
  • diagonal
  • what D0D₀ does
  • HH is wrong
P1: returns its input: halts on every input in 1 step
def P1(x):
    return x
Candidate decider HH
Simulates T steps: if the program has halted, “halts”; otherwise, “does not halt”.
1 000
1/4
StepH table
Errors of HH among P1,…,P6P_1, \dots, P_67 of 36
Patches applied0
Each cell is the prediction of HH for the row program using the column code as input. Some fail (red border), but a better decider might fix that... or could it?
Each cell is decider H's prediction: does the row's program halt with the column's code as input? Red borders are errors. Advance with the player: the diagonal, program D that reverses it (its row differs from every row), and D's column, where cell (D, D) is a guaranteed contradiction. Try the clock with T = 10 and T = 10⁷: P4 errors disappear, but the (D, D) error does not. Press ‘Patch’: the decider fixed at that cell has its own diagonal program that fools it again. Click a program name to read its code.

Notice how the clock decider fails. D(D)D(D) begins by asking HH about (D,D)(D, D), and HH responds by simulating D(D)D(D) for TT steps; thus D(D)D(D) takes more than TT steps merely to receive the answer. The clock runs out, HH says “does not halt,” and DD, obeying its definition, halts: in T+2T + 2 steps under the figure’s convention. Any TT behaves similarly. The cycle-detecting decider is not spared: nested simulation never repeats a configuration, so it sees no cycle, answers “halts” by default, and DD enters its loop. The theorem does not show these deciders are bad; it shows every decider has its (D,D)(D, D) cell.

Reductions and Rice’s theorem

Once we have an undecidable problem, we obtain more by transforming the known problem into the new one: if you could solve the new one, you could solve the old one.

Proof

If DBD_B decides BB, consider the machine calculating f(x)f(x) and running DBD_B on the result. It halts on every input (because ff is total and computable and DBD_B is a decider) and accepts exactly when f(x)∈Bf(x) \in B, that is, when x∈Ax \in A. With a semidecider for BB the same argument gives a semidecider for AA. The same ff satisfies x∉A  ⟺  f(x)∉Bx \notin A \iff f(x) \notin B, the reduction between complements. If ff reduces AA to BB and gg reduces BB to CC, g∘fg \circ f is computable and reduces AA to CC.

∎

In practice use the contrapositive: to prove BB undecidable, reduce a known undecidable problem to BB. Direction matters and is the most frequent error: reducing BB to PARADA\mathsf{PARADA} only proves BB no harder than halting (in particular that BB is semidecidable), which says nothing about undecidability. And ff must be computable without solving anything: in every reduction in this section, ff merely writes text.

This example settles what remained about busy beavers. If SS were computable, PARADAε\mathsf{PARADA}_\varepsilon would be decidable: given MM with nn states (and alphabet {0,1}\{0, 1\}, to which any other can be reduced), simulate S(n)S(n) steps; if it has not halted, it never will, by definition of SS. Thus SS is not computable. More: the same argument with any computable bound g(n)≥S(n)g(n) \ge S(n) instead of S(n)S(n) would decide halting, so no computable function bounds SS. Radó proved a stronger statement directly: for each computable function gg, S(n)>g(n)S(n) > g(n) for every sufficiently large nn. The idea is that a machine with n+cn + c states can write nn on the tape with its first nn states and use the remaining cc, a fixed number depending only on gg, to compute g(2n)+1g(2n) + 1 and spend at least that many steps before halting; since SS is increasing, S(2n)≥S(n+c)>g(2n)S(2n) \ge S(n + c) > g(2n) once n≥cn \ge c, and a similar adjustment covers odd values. Thus SS eventually exceeds every computable function, whether exponential, an exponential tower, or the Ackermann function.

Rice’s theorem

The blank-tape halting reduction has a recurring structure: build a machine that first simulates MM on ww and then does something else. Rice turned this template into a theorem settling nearly every question about program behavior at once.

A semantic property of machines depends only on the language they recognize (or, for programs, the partial function they compute): if L(M1)=L(M2)L(M_1) = L(M_2), either M1M_1 and M2M_2 both have it or neither does. It is trivial if every machine has it or none does. “Accepts the empty word,” “computes the same as this other version,” and “halts on every input” (the latter viewed as the computed partial function being defined everywhere) are semantic and nontrivial. So is “there exists an input on which user data reaches eval” if behavior means the program’s observable trace (inputs, outputs, and sink calls) rather than only its result. “Has fewer than 20 states,” “its code contains eval,” and “halts in fewer than 1000 steps on input 0” are not semantic: programs computing the same thing can differ on them.

This is Rice’s theorem. The proof uses the previous template with a careful choice; you will reconstruct it step by step in the exercises. The idea: let M∅M_\varnothing be a machine that never halts (its language is empty). If M∅M_\varnothing lacks P\mathcal{P}, choose QQ that has it (it exists because P\mathcal{P} is nontrivial), and given ⟨M,w⟩\langle M, w\rangle construct M′M' that on input xx simulates MM on ww and, if it halts, behaves like QQ on xx. If MM halts on ww, L(M′)=L(Q)L(M') = L(Q) and M′M' has P\mathcal{P}; otherwise L(M′)=∅L(M') = \varnothing and it does not. If M∅M_\varnothing has P\mathcal{P}, apply the same argument to the complementary property. Nothing in the proof is specific to languages: it also works when “behavior” is the computed partial function or observable trace, since M′M' behaves either like QQ or like a program that never halts and does nothing observable. The figure instantiates the template with concrete security properties.

InteractiveA reduction chain to Rice
DiagonalTuring, 1936HALTundecidableSINKundecidablediagonalization (§ halting)≤ₘ with f(⟨M, w⟩) = ⟨M′⟩
The program M′M' constructed by ff (with a QQ that has PP)
def M(w):
n = int(w)
while n != 1:
n = n // 2 if n % 2 == 0 else 3 * n + 1
def Q(x):
sink(x)
def M_prima(x):
# 1. simulate M on w (may not terminate)
M("27")
# 2. if it terminates, behave like Q
return Q(x)
If M halts on w
M′ does the same as Q on any x
⇒ M′ has P
If M does not halt on w
M′ never halts on any x: it behaves like the never-halting program
⇒ M′ does not have P
M halts on w: the sequence from 27 reaches 1 in 111 steps. Therefore M′∈M' \in SINK   ⟺  \iff M halts on w. A decider for SINK would decide halting: halts(M, w) = decide_P(f(M, w)).
Code
Semantic? (depends only on what it computes)yes
Nontrivial? (Q has it and the never-halting program does not, or vice versa)yes
Never-halting program (M∅M_\varnothing)does not have P
f(⟨M,w⟩)f(\langle M, w\rangle) constructed without running MM244 characters
This instance: does M′M\prime have PP?yes
Conclusion. Undecidable. It is semidecidable: run M′ on all inputs in parallel, and if it reaches sink you will eventually see it.
Choose a property and a halting instance, and read the program M′ built by the reduction: it simulates M on w and, if that halts, behaves like Q. The two cards beside the code show the two cases. Look at the length of f(⟨M, w⟩): it is text constructed without running M, so f always finishes. Try ‘Never writes the secret to the log’, which the never-halting program satisfies: the reduction starts from the complement of halting and proves a stronger result. With ‘Searches for an odd perfect number’, deciding M′'s property would solve an open problem. Rice does not apply to the last two properties: why does the template fail?

The “never writes the secret” variant deserves comment. Since the never-halting program (M∅M_\varnothing) has the property, the reduction constructs it with QQ that does not, and then M′M' has the property if and only if MM does not halt on ww. This is a reduction PARADA‾≤mNOFUGA\overline{\mathsf{PARADA}} \le_m \mathsf{NOFUGA}; since the complement of halting is not semidecidable, neither is NOFUGA\mathsf{NOFUGA}: no procedure can always eventually confirm a program is safe in this sense. Safety properties (“nothing bad ever happens”) are typically co-semidecidable: a finite counterexample can be found, but absence of counterexamples cannot. Reachability properties (“something happens eventually”) are semidecidable. Some are worse than both: TOTAL\mathsf{TOTAL}, “halts on every input,” is neither semidecidable nor co-semidecidable.

Consequence: sound static analysis overapproximates

Return to the motivating tool. “There exists an input on which tainted data reaches a sink” is a nontrivial semantic property, so no analyzer that always halts can decide it exactly. For an analyzer AA flagging programs as vulnerable:

  • AA is sound if it has no false negatives: it flags every vulnerable program. This amounts to computing an overapproximation of behavior.
  • AA is complete if it has no false positives: everything it flags is vulnerable. This is an underapproximation: each alarm has an execution proving it.

Rice says that for a nontrivial semantic property no AA can be sound, complete, and always halt: at least one guarantee must be given up. (The names come from logic, with the same meaning as soundness and completeness of a proof system: “sound” means “what it says is true” when it says “there is no error,” and “complete” means “it says everything true.”)

Sound overapproximation has an elegant theory, Cousot and Cousot’s abstract interpretation (1977). Instead of running a program with concrete values, run it with abstract values (tainted or clean, an interval, a sign) forming a lattice; take both branches and join their results, and iterate loops to a fixed point, with a widening operator forcing convergence in finitely many steps. The result includes every real behavior plus some impossible ones: these are false alarms. On the other side, bounded execution (tests, fuzzing, bounded model checking, symbolic execution) explores real behaviors up to a limit: what it finds is real, but what it misses may lie beyond the limit.

InteractiveSound, complete, or bounded: choose the guarantee to give up
programtruthanalyzer
000.50.511false-alarm ratefalse-negative ratenone reaches (0, 0)order ignoredorder trackedconstantspatternK=2, B=100K=8, B=1000K=64, B=10⁴
  • sound
  • bounded
  • pattern
debug = 0
x = input()
if debug == 1:
sink(x)
Dead branch: safe. debug is 0, so the sink branch never executes.
False alarm.
Following statement order, but assuming every branch and loop exit is possible, x may reach sink tainted.
Analyzer
Sound analysis precision
False alarms (safe programs flagged)6 of 9
False negatives (vulnerable programs missed)0 of 7
Sound: it never misses a real vulnerability (0 false negatives), at the cost of false alarms. More precision removes some, never all.
Fifteen toy programs whose ground truth is computed by running all 64 possible input() values. Choose an analyzer. The sound one (abstract taint interpretation) never has false negatives; increase its precision and see which false alarms disappear and which remain. The bounded one tries K inputs with B steps each: it never gives false alarms, but misses the rare trigger and long loop. The syntactic pattern fails in both directions. With K = 64 and B = 10⁴ the bounded one gets all fifteen right... until you include the adversary, a program constructed against that configuration. No point on the map reaches (0, 0).

Consider three programs in the figure. “Dead branch” (debug = 0; if debug == 1: sink(x)) fools the basic sound analysis, but not one propagating constants. “Impossible condition” (if x * x % 4 == 2) resists constant propagation because seeing that a square is never 2 modulo 4 requires some number theory; an abstract domain of congruences would eliminate it, whereupon another condition would remain. “Never terminates” resists every sound analysis: discarding the sink after the loop requires proving the loop never terminates, exactly what Rice forbids in general. Each precision improvement moves the problem; it never eliminates it.

Does this make static analysis useless? On the contrary: it means choosing the desired guarantee carefully. Astrée, an abstract-interpretation analyzer, proves absence of runtime errors in Airbus flight-control code because that code is written in a style its abstract domain understands. Random testing and bounded verifiers find real bugs without false alarms, and O’Hearn’s incorrectness logic (2019) is the theory of underapproximation supporting industrial tools of this kind. The theorem rules out promising both guarantees for every program without human intervention. In formal verification, humans provide what the algorithm cannot find: the invariants and variant functions of Hoare logic.

First-order logic and Gödel’s theorems

Turing’s motivating problem was not halting, but Hilbert and Ackermann’s Entscheidungsproblem (1928): find an algorithm deciding whether a first-order logic formula is valid (true in every structure). Church and Turing independently gave a negative answer in 1936. This is the undecidability of first-order logic, with the following precise profile:

Semidecidability follows from Gödel’s completeness theorem: every valid formula has a finite proof in a calculus such as lesson 4’s natural deduction, and proofs can be mechanically enumerated and checked. Thus a program testing every proof in order of length eventually finds one for every valid formula and does not halt on the others. This is exactly what automated provers based on resolution and its first-order version do more cleverly. Undecidability follows by reduction from halting: given MM and ww, write a formula φM,w\varphi_{M,w} whose predicates describe the configurations of MM over time (as in encoding problems in SAT or the Cook–Levin theorem, but with an infinite domain for time and tape), valid if and only if MM halts on ww. Decidable fragments include propositional and monadic logic (only unary predicates), and decidable theories include Presburger arithmetic (natural numbers with addition but no multiplication).

Gödel had previously taken another direction: from pure logic to concrete theories such as arithmetic.

Gödel proved this assuming TT is ω\omega-consistent, stronger than consistency; Rosser weakened the hypothesis to consistency alone in 1936, as commonly stated today.

A slightly weaker version follows in three lines from what you know. Suppose TT is sound (it proves only true statements) and proves every true statement of the form “MM does not halt on ww,” expressible in arithmetic. Then the following algorithm decides halting: given ⟨M,w⟩\langle M, w\rangle, dovetail simulation of MM on ww with enumeration of proofs in TT; if simulation finishes, answer “halts”; if a proof of “MM does not halt on ww” appears, answer “does not halt.” One event always occurs and the answer is correct. Since halting is undecidable, some machine does not halt without TT being able to prove it: that true statement is unprovable. The second incompleteness theorem adds that if TT is consistent and somewhat stronger (Peano arithmetic suffices), TT cannot prove its own consistency.

The frontier: BB(5) = 47 176 870

The fact that SS is not computable does not prevent computing individual values: it prevents one algorithm from computing all of them. Each value is a finite, though enormous, problem requiring ingenuity. S(4)=107S(4) = 107 was established in 1983. For five states, Heiner Marxen and Jürgen Buntrock found the champion machine 1RB1LC_1RC1RB_1RD0LE_1LA1LD_1RH0LA in 1989, halting after 47 176 870 steps with 4098 ones (the one you ran in the simulator). For 35 years it was unknown whether another machine beat it.

In 2024 the open bbchallenge collaboration settled the problem: S(5)=47 176 870S(5) = 47\,176\,870 and Σ(5)=4098\Sigma(5) = 4098. Its method followed the theory. It enumerated 5-state machines up to symmetries, simulated those halting quickly, and for each remaining machine provided a certificate of nonhalting produced by a specialized decider: cycle and shifting-cycle detectors, backward reasoning from the halting state, finite automata recognizing a tape invariant, and individual proofs for a handful of hard machines. None works for every machine (none can); together they cover the 5-state cases. The reasoning was formalized and verified in the Coq proof assistant, and the paper appeared in 2025 (bbchallenge, 2025). This was possible partly because proof assistants, which you will study in the next lesson, let us trust proofs no one can check by hand.

With six states the situation changes qualitatively. Known 6-state machines halt after more than 10↑↑1510 \uparrow\uparrow 15 steps (a tower of fifteen tens, Pavel Kropitz, 2022), and the collaboration identified 6-state machines whose behavior is equivalent to open problems resembling the Collatz conjecture. Determining BB(6)\mathrm{BB}(6) would require at least solving those problems. Moreover, by the Gödel argument above, for every consistent theory with decidable axioms containing arithmetic there is an nn beyond which the theory cannot prove the value of S(n)S(n).

Implementation from scratch

Start with the simulator. The tape is a dictionary with a default blank, growing in both directions without allocating memory in advance; the table maps (q,s)(q, s) to (b,d,q′)(b, d, q'), and a missing key means “no transition.”

[ ]Turing machine simulatorBrowser
from collections import defaultdict

def ejecuta_mt(delta, inicio, cinta="", blanco="_", max_pasos=10**6, parada=("H", "SI", "NO")):
    """Simula una máquina de Turing de una cinta. delta[(q, s)] = (escribe, mueve, q')."""
    c = defaultdict(lambda: blanco, enumerate(cinta))
    q, cab, pasos = inicio, 0, 0
    while q not in parada and pasos < max_pasos:
        clave = (q, c[cab])
        if clave not in delta:                  # sin transición: la máquina se detiene
            break
        c[cab], mov, q = delta[clave]
        cab += 1 if mov == "R" else -1
        pasos += 1
    usadas = [i for i, s in c.items() if s != blanco]
    texto = "".join(c[i] for i in range(min(usadas), max(usadas) + 1)) if usadas else ""
    return q, pasos, texto

# incremento binario
INC = {("der", "0"): ("0", "R", "der"), ("der", "1"): ("1", "R", "der"), ("der", "_"): ("_", "L", "suma"),
       ("suma", "1"): ("0", "L", "suma"), ("suma", "0"): ("1", "R", "H"), ("suma", "_"): ("1", "R", "H")}
for w in ["1011", "111", "0"]:
    q, pasos, t = ejecuta_mt(INC, "der", w)
    print(f"{w:>5} + 1 = {t:>5}   ({pasos} pasos)")

# palíndromos: borra el primero, lo recuerda en el estado, comprueba el último y vuelve
PAL = {}
for s, ir, comp in [("a", "va", "ca"), ("b", "vb", "cb")]:
    PAL[("q0", s)] = ("_", "R", ir)
    for t in "ab":
        PAL[(ir, t)] = (t, "R", ir)
    PAL[(ir, "_")] = ("_", "L", comp)
    PAL[(comp, s)] = ("_", "L", "vuelve")
    PAL[(comp, "b" if s == "a" else "a")] = (s, "R", "NO")
    PAL[(comp, "_")] = ("_", "R", "SI")
PAL[("q0", "_")] = ("_", "R", "SI")
for t in "ab":
    PAL[("vuelve", t)] = (t, "L", "vuelve")
PAL[("vuelve", "_")] = ("_", "R", "q0")
for w in ["abba", "abab", "a" * 20, "ab" * 10]:
    q, pasos, _ = ejecuta_mt(PAL, "q0", w)
    print(f"{w:>20}: {q:2s} en {pasos:4d} pasos")

def desde_bbchallenge(codigo):
    """'1RB1LB_1LA1RH' -> tabla con estados A, B, ... y símbolos 0, 1."""
    delta = {}
    for i, bloque in enumerate(codigo.split("_")):
        for s in (0, 1):
            t = bloque[3 * s: 3 * s + 3]
            if t != "---":
                delta[("ABCDE"[i], str(s))] = (t[0], t[1], t[2])
    return delta

CASTORES = {2: "1RB1LB_1LA1RH", 3: "1RB1RH_1LB0RC_1LC1LA", 4: "1RB1LB_1LA0LC_1RH1LD_1RD0RA"}
for n, cod in CASTORES.items():
    q, pasos, t = ejecuta_mt(desde_bbchallenge(cod), "A", blanco="0")
    print(f"castor de {n} estados: para en {pasos} pasos con {t.count('1')} unos")

A palindrome of length 20 costs 231 steps, ten increasingly short full passes: the quadratic cost of the back-and-forth strategy. By contrast, (ab)10(ab)^{10} is rejected in 22 steps, at the end of the first pass. The busy beavers reproduce the table: 6, 21 and 107 steps. (The 3-state one leaves 5 ones; another machine attains the maximum Σ(3)=6\Sigma(3) = 6 in fewer steps: the two records need not coincide.)

Now the universal machine and machine count. Encode an nn-state machine as its bbchallenge string; interpreter U receives that string as data. The same interpreter lets us enumerate the (4(n+1))2n(4(n+1))^{2n} 2-state machines and rediscover S(2)=6S(2) = 6 by brute force.

[ ]Universal interpreter and S(2) by brute forceBrowser
from itertools import product

def U(codigo, max_pasos):
    """Máquina universal: interpreta la máquina descrita por la cadena `codigo` sobre la cinta en blanco."""
    q, pasos, t = ejecuta_mt(desde_bbchallenge(codigo), "A", blanco="0", max_pasos=max_pasos)
    return (pasos if q == "H" else None), t.count("1")

print("U(castor de 3) =", U("1RB1RH_1LB0RC_1LC1LA", 1000))
print("máquinas de n estados:", [(4 * (n + 1)) ** (2 * n) for n in range(1, 6)])

def todas(n):
    """Todas las cadenas de máquinas de n estados y 2 símbolos."""
    trans = [f"{w}{m}{q}" for w in "01" for m in "LR" for q in "ABCDE"[:n] + "H"]
    for t in product(trans, repeat=2 * n):
        yield "_".join("".join(t[2 * i: 2 * i + 2]) for i in range(n))

def corre_rapido(cod, n, limite):
    """Versión sin diccionarios de U para el barrido (mismo resultado, más rápida)."""
    tabla = [(int(b[0]), 1 if b[1] == "R" else -1, "ABCDEH".index(b[2]) if b[2] != "H" else n)
             for bloque in cod.split("_") for b in (bloque[:3], bloque[3:])]
    cinta, cab, q, pasos = {}, 0, 0, 0
    while q != n and pasos < limite:
        w, m, q = tabla[2 * q + cinta.get(cab, 0)]
        cinta[cab] = w
        cab += m
        pasos += 1
    return (pasos if q == n else None), sum(cinta.values())

res = [corre_rapido(c, 2, 50) for c in todas(2)]
paran = [r for r in res if r[0] is not None]
print(f"{len(res)} máquinas; paran en 50 pasos: {len(paran)}; no han parado: {len(res) - len(paran)}")
print("S(2) =", max(p for p, _ in paran), "  Sigma(2) =", max(u for _, u in paran))
assert U("1RB1LB_1LA1RH", 100) == corre_rapido("1RB1LB_1LA1RH", 2, 100)

Of the 20736 machines, 9784 halt and none takes more than 6 steps. The remaining 10952 have not halted in 50 steps, and here is the subtle point: to conclude S(2)=6S(2) = 6 one must prove they never halt. For n=2n = 2 this is easy (with a 10 000-step limit the same 10952 remain, all entering cycles or shifting patterns detectable mechanically). For n=5n = 5 that was bbchallenge’s work.

Diagonalization can be written as code. We need to run code with a step budget; Python permits this with sys.settrace, which calls our function at each executed line. The budget stack supports nested simulations: when a decider simulates a program that itself calls the decider, each line counts against every open budget, as in the figure.

[ ]The executable diagonalBrowser
import sys, inspect

class Agotado(Exception):
    pass

_presupuestos = []                       # presupuestos activos, del más exterior al más interior

def _traza(frame, evento, arg):
    if evento == "call" and frame.f_code is ejecuta.__code__:
        return None                      # las líneas del propio intérprete no cuentan ni se interrumpen
    if evento == "line":
        for i in range(len(_presupuestos)):
            _presupuestos[i] -= 1
            if _presupuestos[i] < 0:
                raise Agotado(i)
    return _traza

def ejecuta(src, entrada, pasos, entorno=None):
    """Ejecuta main(entrada) del código src con como mucho `pasos` líneas: ('para', valor) o ('agotado', None)."""
    ns = {"ejecuta": ejecuta, **(entorno or {})}
    exec(src, ns)                        # solo define funciones
    nivel = len(_presupuestos)
    _presupuestos.append(pasos)
    anterior = sys.gettrace()
    sys.settrace(_traza)
    try:
        return "para", ns["main"](entrada)
    except Agotado as e:
        if e.args[0] != nivel:           # se ha agotado un presupuesto exterior: no es asunto nuestro
            raise
        return "agotado", None
    finally:
        _presupuestos.pop()
        sys.settrace(anterior)

# tres decisores candidatos: H(src, x) dice si main(x) del código src para
def H_optimista(src, x):
    return True

def H_sintactico(src, x):
    return "while True" not in src

def H_reloj(src, x, T=300):
    return ejecuta(src, x, T)[0] == "para"

def diagonal(H):
    """Código del programa D que contradice a H: pregunta por (x, x) y hace lo contrario."""
    return inspect.getsource(H) + f"""
def main(x):
    if {H.__name__}(x, x):
        while True:
            pass
    return "he parado"
"""

for H in (H_optimista, H_sintactico, H_reloj):
    D = diagonal(H)
    dice = "para" if H(D, D) else "no para"
    real = ejecuta(D, D, 20_000)[0]
    print(f"{H.__name__:13s}  H(D, D) dice «{dice}»;  D(D) con 20 000 líneas: {real}")

The three lines are as theory predicts: the optimist says “halts” and D(D)D(D) exhausts any budget (by construction it is in while True); the syntactic decider sees while True in the code of DD, says “does not halt,” and D(D)D(D) halts; the clock decider exhausts its 300 lines simulating the simulation of itself, says “does not halt,” and D(D)D(D) halts. Do not just trust the table: change T, write your own decider, and run it again.

Finally, a toy taint analyzer on real Python code with the ast module. Sound analysis traverses statements in order, takes both branches of each if and joins results, and iterates each while to a fixed point. Bounded execution marks user-provided integers with a subclass of int whose operations preserve the mark, and tries a few inputs under a line budget.

[ ]Toy taint analysis: sound versus boundedBrowser
import ast, textwrap

PROGRAMAS = {
    "directo":    ("def main(x):\n    sink(x)", True),
    "saneado":    ("def main(x):\n    y = sanitize(x)\n    sink(y)", False),
    "rama muerta": ("def main(x):\n    debug = 0\n    if debug == 1:\n        sink(x)", False),
    "imposible":  ("def main(x):\n    if (x * x) % 4 == 2:\n        sink(x)", False),
    "raro":       ("def main(x):\n    if x == 23:\n        sink(x)", True),
    "bucle largo": ("def main(x):\n    k = 0\n    while k < 400:\n        k += 1\n    sink(x)", True),
    "nunca":      ("def main(x):\n    k = 1\n    while k > 0:\n        k += 1\n    sink(x)", False),
}

def solido(src):
    """Interpretación abstracta: conjunto de variables posiblemente contaminadas."""
    alarmas = []
    def sucio(e, S):
        if isinstance(e, ast.Name):
            return e.id in S
        if isinstance(e, ast.Call) and getattr(e.func, "id", "") == "sanitize":
            return False
        return any(sucio(h, S) for h in ast.iter_child_nodes(e) if isinstance(h, ast.expr))
    def bloque(ss, S):
        for s in ss:
            if isinstance(s, ast.Assign):
                S = (S | {s.targets[0].id}) if sucio(s.value, S) else (S - {s.targets[0].id})
            elif isinstance(s, ast.AugAssign) and sucio(s.value, S):
                S = S | {s.target.id}
            elif isinstance(s, ast.Expr) and getattr(s.value.func, "id", "") == "sink":
                if sucio(s.value.args[0], S):
                    alarmas.append(s.lineno)
            elif isinstance(s, ast.If):
                S = bloque(s.body, S) | bloque(s.orelse, S)       # las dos ramas, unidas
            elif isinstance(s, ast.While):
                cabeza = S
                while True:                                        # punto fijo de la cabeza del bucle
                    nueva = S | bloque(s.body, cabeza)
                    if nueva == cabeza:
                        break
                    cabeza = nueva
                S = cabeza                                         # se puede salir en cualquier vuelta
        return S
    f = ast.parse(src).body[0]
    bloque(f.body, {f.args.args[0].arg})
    return bool(alarmas)

class Sucio(int):
    """Entero que viene del usuario: la aritmética conserva la marca."""
for op in ("add", "radd", "sub", "rsub", "mul", "rmul", "mod", "rmod", "floordiv"):
    setattr(Sucio, f"__{op}__", lambda a, b, _op=op: Sucio(getattr(int, f"__{_op}__")(a, b)))

def acotado(src, entradas, pasos):
    """Ejecuta con entradas concretas; alarma solo si un Sucio llega a sink (testigo real)."""
    llegadas = []
    entorno = {"sink": lambda v: llegadas.append(isinstance(v, Sucio)), "sanitize": int}
    for x in entradas:
        ejecuta(src, Sucio(x), pasos, entorno)
        if any(llegadas):
            return True
    return False

fp = fn = 0
print(f"{'programa':12s} verdad       sólido       acotado (5 entradas, 500 líneas)")
for nombre, (src, vulnerable) in PROGRAMAS.items():
    s, a = solido(src), acotado(src, [3, 8, 15, 30, 31], 500)
    marca = lambda r: ("alarma" if r else "nada").ljust(7) + ("✓" if r == vulnerable else ("FP" if r else "FN"))
    print(f"{nombre:12s} {'vulnerable' if vulnerable else 'segura':12s} {marca(s):12s} {marca(a)}")

The table summarizes the lesson in seven rows. Sound analysis flags all three vulnerable programs and three of the four safe ones (dead branch, impossible condition, infinite loop): false alarms, never false negatives. The bounded one gives no false alarm but misses “rare” (none of its five inputs is 23) and “long loop” (reaching sink takes about 800 lines against a budget of 500). Raise the budget and add 23 to the inputs: it gets all seven right. The figure’s adversarial program shows why that is not the end.

Professional tools

In Python, the universal machine comes built in and code is data inspectable at every level: text, syntax tree, bytecode. compile translates text to a code object, dis displays it, exec runs it, and ast supplies the tree used by analyzers.

[ ]Code as data in CPythonBrowser
import ast, dis

src = "def f(x):\n    return 2 * x + 1"
arbol = ast.parse(src)
print(ast.dump(arbol.body[0].body[0], indent=1)[:200], "...")
codigo = compile(src, "<dato>", "exec")
ns = {}
exec(codigo, ns)                      # U(<f>, ·): el intérprete ejecuta un programa recibido como dato
print("f(20) =", ns["f"](20))
print("instrucciones de f:", [i.opname for i in dis.get_instructions(ns["f"])])

Real tools occupy the corners imposed by Rice:

GuaranteeTechniqueExample toolsSacrifice
Sound (no false negatives)abstract interpretationAstrée, Frama-C (Eva), IKOSfalse alarms; sometimes restricted languages
Complete (no false positives)tests, fuzzing, symbolic execution, bounded verificationAFL++, libFuzzer, KLEE, CBMCcases beyond the bound
Neither, but cheappatterns and approximate flowlinters, Semgrep, CodeQL, Pysaboth, to varying degrees
Both for a specific programproof with supplied invariantsCoq, Lean, Isabelle, Dafnyhuman work

Security data-flow analyzers are not strictly sound: they approximate reflection, dynamic calls, or libraries without source, and the community calls them soundy. This is not an engineering defect awaiting correction; it is a conscious choice about where errors occur.

The immediate consequence for builders of agents that execute code: since termination is undecidable, every generated-code execution environment needs an externally imposed time and resource limit, not merely hope that the program halts.

import subprocess

# el único detector de parada que funciona siempre: un reloj externo que mata el proceso
try:
    r = subprocess.run(["python", "-c", codigo_generado], capture_output=True, text=True, timeout=5)
except subprocess.TimeoutExpired:
    resultado = "sin respuesta en 5 s"      # no sabemos si habría parado: lo tratamos como fallo

Common mistakes

Exercises

QuizWhich are decidable?
Which of these problems are decidable? (Python programs with unlimited memory; DFAs as in the previous lesson.)

More than one answer may be correct.

QuizReduction direction
You want to prove EQUIV={⟨M1,M2⟩:L(M1)=L(M2)}\mathsf{EQUIV} = \{\langle M_1, M_2\rangle : L(M_1) = L(M_2)\} undecidable. What suffices to construct?
QuizDoes Rice apply?
For which of these properties of a program PP does Rice's theorem prove undecidability?

More than one answer may be correct.

QuizWhat silence means
A sound taint analyzer finishes with no alarms on your service. A fuzzing-based one also finds nothing after a million runs. What follows?
NumericThe two-state busy beaver
What is the maximum number of steps S(2)S(2) a halting 2-state, 2-symbol Turing machine can take starting on a blank tape? (Count the transition to the halting state.)
NumericHow many machines?
Each table cell of an nn-state machine over alphabet {0,1}\{0, 1\} chooses what to write, where to move, and the next state (one of the nn or halt). How many distinct tables exist for n=3n = 3?
NumericDecide halting using S(4)
You know S(4)=107S(4) = 107. Given a 4-state, 2-symbol machine, you want to decide by simulation whether it halts on a blank tape. What is the fewest steps you can simulate without a halt and conclude with certainty that it will never halt?
CodeProgram a Turing machine
Write tabla_anbn(), returning the table of a Turing machine that decides the language {anbn:n≥0}\{a^n b^n : n \ge 0\}, in the lesson simulator's format: a dictionary delta[(q, s)] = (escribe, mueve, q2) with moves 'L' or 'R'. The machine starts in state q0 with its head over the first symbol; blank is _ and you may also use markers X and Y. It accepts on reaching SI; reaching NO or having no defined transition halts without accepting. It must halt on every input.
def tabla_anbn():
  """delta[(q, s)] = (escribe, mueve, q'). Estado inicial q0; acepta si llega a SI."""
  return {}
Shift+Enter to run
ProofHalting is undecidable
Prove: No Turing machine decides PARADA={⟨M,w⟩:M para con w}\mathsf{PARADA} = \{\langle M, w\rangle : M \text{ para con } w\}.
0
Suppose for contradiction that HH decides PARADA\mathsf{PARADA}: it halts on every input and accepts ⟨M,w⟩\langle M, w\rangle if and only if MM halts on ww.

Step 1 of 4. What machine do you construct from HH?

ProofRice's theorem
Prove: If P\mathcal{P} is a nontrivial semantic property of Turing machines, LP={⟨M⟩:M tiene P}L_{\mathcal{P}} = \{\langle M\rangle : M \text{ tiene } \mathcal{P}\} is undecidable.
0
Let M∅M_\varnothing be a machine that halts on no input, so L(M∅)=∅L(M_\varnothing) = \varnothing.

Step 1 of 5. Why may you assume M∅M_\varnothing does not have P\mathcal{P}?

ProofDecidable iff semidecidable and co-semidecidable
Prove: If LL and Lˉ\bar L are semidecidable, LL is decidable.
0
Let M1M_1 semidecide LL and M2M_2 semidecide Lˉ\bar L.

Step 1 of 3. What does the machine DD you construct do on input ww?

CodeReduction as a code transformation
Implement reduce(M_src, w). M_src is Python code for a function M(w); return the code of a program defining (in addition to M) a function Mp(x) that returns `True` on some input if and only if `M` halts on `w`. reduce must not execute M: it only builds text. Take care with w: it may contain quotes and newlines. Tests execute the code you generate with a line limit.
def reduce(M_src, w):
  """Código de Mp(x): devuelve True con alguna x si y solo si M para con w. No ejecutes M."""
  # construye el texto del programa y devuélvelo
  return M_src
Shift+Enter to run

Summary

Key idea
A program is data another program can read, and this self-reference constructs, against any purported halting decider, a program contradicting it. Reductions then show every nontrivial property of program behavior is undecidable: every analyzer chooses between false alarms, false negatives, and nontermination.
  • A Turing machine is a finite automaton with an infinite rewritable tape. On each input it accepts, rejects, or never halts; the third case gives rise to undecidability. Reasonable variants and programming languages compute the same things (Church–Turing thesis).
  • The universal machine is an interpreter: a fixed program executing any program received as data. Machines are countable and languages are not, so almost no language is decidable.
  • Decidable means an algorithm always halts and answers correctly; semidecidable means it halts and accepts positive instances. A language is decidable exactly when it and its complement are semidecidable.
  • Halting is semidecidable and undecidable by diagonalization: program DD does the opposite of HH‘s prediction about (D,D)(D, D). Its complement is not semidecidable.
  • Under many-one reductions A≤mBA \le_m B, undecidability passes from AA to BB. Rice’s theorem does this for every nontrivial semantic property at once. Properties of text or runtime lie outside it.
  • In program analysis, soundness overapproximates (abstract interpretation, false alarms), completeness underapproximates (tests, fuzzing, bounded execution, false negatives), and each configuration has an adversarial program.
  • First-order validity is semidecidable (Gödel completeness) and undecidable (Church and Turing); arithmetic is incomplete (Gödel). S(n)S(n) is not computable, although S(5)=47 176 870S(5) = 47\,176\,870 was determined in 2024 using certificates verified in Coq.