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 , 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 ), rejects (halts otherwise), or never halts. This third outcome, absent in finite automata, drives everything that follows. The language of is .
Recognizing palindromes over 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 ” and another “carrying ”), 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: steps for a word of length . Program them and watch them run:
Busy beavers
The busy beavers in the figure pose an innocent-looking question raised by Tibor Radó in 1962: among machines with states and alphabet which, started on a blank tape, eventually halt, what is the maximum number of steps? Call it , and call the maximum number of ones left on the tape . 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 states: each of the table cells chooses what to write (2 options), where to move (2), and the next state ( states or halt), giving machines. For there are and for about . Known values are:
| Determined by | |||
|---|---|---|---|
| 1 | 1 | 1 | trivial |
| 2 | 6 | 4 | Radó (1962) |
| 3 | 21 | 6 | Lin and Radó (1965) |
| 4 | 107 | 13 | Brady (1983) |
| 5 | 47 176 870 | 4098 | bbchallenge (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 steps, that it will never halt. We will see there is no general algorithmic solution and consequently 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 -tape machine is simulated on one tape by interleaving the tapes and marking each head position with a special symbol: each original step requires a sweep of the used area, so steps are simulated in . 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 to . 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 for the encoding of and 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 , by contrast, are subsets of , 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. uses three tapes (reducible to one at the quadratic cost above): the first holds table ; the second, the tape of , each symbol of encoded in binary using a fixed number of cells; the third, the current state of in binary. At each iteration 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, halts with the same result. In the three-tape version, each step of costs a number of steps depending on but not ; in every version halts exactly when 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 . 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 , depending on what it does with words outside .
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: is semidecidable if and only if a machine prints all the words in 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 valuations (SAT; decidable, though perhaps not quickly).
- Semidecidable. : 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 execute steps for each input . Every pair (input, step count) is eventually visited, as in the diagonal enumeration of in lesson 3. The same trick proves the theorem connecting the three classes.
One direction is immediate: if decides , then semidecides , and the machine running and swapping answers decides (hence semidecides) . The other direction dovetails two semideciders, one for and one for ; 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 decides : it halts on every input and accepts if and only if halts on . Construct machine which, on input :
- runs on input (always terminating because is a decider);
- if accepts, enters an infinite loop; if it rejects, halts.
is a legitimate Turing machine: it is with a preamble duplicating the input and a two-state epilogue. By construction, for every machine ,
Taking , halts on if and only if does not halt on . Contradiction, so does not exist. The second claim follows from the previous theorem: if were semidecidable, would be decidable.
∎The proof is short, but see it for what it is: Cantor’s diagonal applied to programs. Put all machines in the rows of an infinite table and their codes in the columns; cell records whether halts on . Machine reverses the diagonal: it differs from each at , so it is no row. Cantor concluded the table cannot contain every possible row. Turing adds an ingredient: if were computable, ‘s row would be too and would have to be in the table, which contains all machines. The contradiction is not in countability, but in 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.
Notice how the clock decider fails. begins by asking about , and responds by simulating for steps; thus takes more than steps merely to receive the answer. The clock runs out, says “does not halt,” and , obeying its definition, halts: in steps under the figure’s convention. Any 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 enters its loop. The theorem does not show these deciders are bad; it shows every decider has its 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 decides , consider the machine calculating and running on the result. It halts on every input (because is total and computable and is a decider) and accepts exactly when , that is, when . With a semidecider for the same argument gives a semidecider for . The same satisfies , the reduction between complements. If reduces to and reduces to , is computable and reduces to .
∎In practice use the contrapositive: to prove undecidable, reduce a known undecidable problem to . Direction matters and is the most frequent error: reducing to only proves no harder than halting (in particular that is semidecidable), which says nothing about undecidability. And must be computable without solving anything: in every reduction in this section, merely writes text.
This example settles what remained about busy beavers. If were computable, would be decidable: given with states (and alphabet , to which any other can be reduced), simulate steps; if it has not halted, it never will, by definition of . Thus is not computable. More: the same argument with any computable bound instead of would decide halting, so no computable function bounds . Radó proved a stronger statement directly: for each computable function , for every sufficiently large . The idea is that a machine with states can write on the tape with its first states and use the remaining , a fixed number depending only on , to compute and spend at least that many steps before halting; since is increasing, once , and a similar adjustment covers odd values. Thus 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 on 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 , either and 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 be a machine that never halts (its language is empty). If lacks , choose that has it (it exists because is nontrivial), and given construct that on input simulates on and, if it halts, behaves like on . If halts on , and has ; otherwise and it does not. If has , 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 behaves either like or like a program that never halts and does nothing observable. The figure instantiates the template with concrete security properties.
The “never writes the secret” variant deserves comment. Since the never-halting program () has the property, the reduction constructs it with that does not, and then has the property if and only if does not halt on . This is a reduction ; since the complement of halting is not semidecidable, neither is : 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: , “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 flagging programs as vulnerable:
- is sound if it has no false negatives: it flags every vulnerable program. This amounts to computing an overapproximation of behavior.
- 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 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.
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 and , write a formula whose predicates describe the configurations of 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 halts on . 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 is -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 is sound (it proves only true statements) and proves every true statement of the form “ does not halt on ,” expressible in arithmetic. Then the following algorithm decides halting: given , dovetail simulation of on with enumeration of proofs in ; if simulation finishes, answer “halts”; if a proof of “ does not halt on ” appears, answer “does not halt.” One event always occurs and the answer is correct. Since halting is undecidable, some machine does not halt without being able to prove it: that true statement is unprovable. The second incompleteness theorem adds that if is consistent and somewhat stronger (Peano arithmetic suffices), cannot prove its own consistency.
The frontier: BB(5) = 47 176 870
The fact that 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. 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: and . 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 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 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 beyond which the theory cannot prove the value of .
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 to , and a missing key means “no transition.”
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, 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 in fewer steps: the two records need not coincide.)
Now the universal machine and machine count. Encode an -state machine as its bbchallenge string; interpreter U receives that string as data. The same interpreter lets us enumerate the 2-state machines and rediscover by brute force.
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 one must prove they never halt. For this is easy (with a 10 000-step limit the same 10952 remain, all entering cycles or shifting patterns detectable mechanically). For 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.
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 exhausts any budget (by construction it is in while True); the syntactic decider sees while True in the code of , says “does not halt,” and halts; the clock decider exhausts its 300 lines simulating the simulation of itself, says “does not halt,” and 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.
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.
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:
| Guarantee | Technique | Example tools | Sacrifice |
|---|---|---|---|
| Sound (no false negatives) | abstract interpretation | Astrée, Frama-C (Eva), IKOS | false alarms; sometimes restricted languages |
| Complete (no false positives) | tests, fuzzing, symbolic execution, bounded verification | AFL++, libFuzzer, KLEE, CBMC | cases beyond the bound |
| Neither, but cheap | patterns and approximate flow | linters, Semgrep, CodeQL, Pysa | both, to varying degrees |
| Both for a specific program | proof with supplied invariants | Coq, Lean, Isabelle, Dafny | human 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
More than one answer may be correct.
More than one answer may be correct.
tabla_anbn(), returning the table of a Turing machine that decides the language , 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 {}Step 1 of 4. What machine do you construct from ?
Step 1 of 5. Why may you assume does not have ?
Step 1 of 3. What does the machine you construct do on input ?
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_srcSummary
- 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 does the opposite of ‘s prediction about . Its complement is not semidecidable.
- Under many-one reductions , undecidability passes from to . 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). is not computable, although was determined in 2024 using certificates verified in Coq.