lineage

Respecting Equality: Complete Inference, Deterministic and Step-Optimal

Avik Jain · avikj@berkeley.edu

Equality of types is equivalence — Voevodsky's univalence — and it computes. The interval and the Glue type former build it with nothing assumed (§§0–2): an isomorphism A ≃ B becomes an identification A ≡ B whose transport is that isomorphism, so isomorphic structures are interchangeable by a program that runs.

Two facts stand on that. A step is reversible exactly when it is transport along such an identification (3.2); every additive measure of what a step destroys vanishes on the reversible ones (3.5), so reversible computation dissipates nothing and a step's only cost is the information it erases — its Landauer heat (§3). And the diagonal is a single lemma (Lawvere): a point-surjective table forces every endomap a fixed point, so a fixed-point-free map forbids the table — Cantor, Russell, Tarski, the halting problem; Gödel is that lemma together with representability and ω-consistency (§4).

They meet in the result (§5): proving, deciding, computing and answering are one act — build a term, normalize it. The answer is the term's unique normal form (5.18), reached in a number of steps fixed by where the reduction begins and ends and not by the strategy between them (5.13), and that number is already the least possible (5.17). Complete inference is thus deterministic and step-optimal; and where a question has no answer, the diagonal is what establishes it, in place of a search that never ends (5.19).

Read elsewhere, the same construction is the natural numbers as finite sets up to relabelling (§6); the complex numbers, and Maxwell's equations as one Schrödinger equation, as its reversible side (§7); and Boolean search as partition by output, where the gap between finding a solution and checking one is exactly the bit a lossy truncation discards (§8). §9 then runs all of it on one problem, end to end — ordering a finite set, where the cost is fixed by how its size is written as a sum. At each result the computational core is a term machine-checked against the cubical library, printed where it is proved.

0. The one fact

Definition 0.1 (type, function, dependent pair). A type is a collection of values, written a : A. A function f : A → B maps values to values. For a family P — one type P a for each a : A — the dependent pair Σ[ a ∈ A ] P a holds pairs (a , w) with w : P a.

Definition 0.2 (identity type). Equality is a type: x ≡ y is the type of proofs that x equals y, with refl : x ≡ x. A proof is a value you keep.

Definition 0.3 (the interval). 𝕀 has two endpoints 0 and 1, a meet ∧, a join ∨, and an operation ~ that exchanges the endpoints and reverses order. The laws are: ∧ and ∨ are associative, commutative and idempotent, absorb one another (x ∧ (x ∨ y) = x) and distribute over one another, with 0 the unit of ∨ and 1 of ∧; and ~ 0 = 1, ~ 1 = 0, ~ ~ x = x, ~(x ∧ y) = ~x ∨ ~y. The unit interval [0,1] with min, max and 1 − x satisfies all of this and is a usable picture; what is used below is only these laws, never any property of the real numbers. "Free De Morgan algebra on one generator" is the exact name for that restriction: the elements are the expressions built from one symbol i by ~, ∧ and ∨, and two are equal only where the laws just listed force it. It is built, not assumed.

Definition 0.4 (path). A proof of x ≡ y is a map p : 𝕀 → A with p 0 = x and p 1 = y. refl is the constant map.

Definition 0.5 (contractible). A is contractible when some point of it exists and every element is equal to that point — the whole type collapses onto it.

Definition 0.6 (transport). For a family P, a proof p : x ≡ y gives transport p : P x → P y.

Proposition 0.7 (reversibility of transport). transport is reversible and loses nothing: it runs backward along the reversed path λ i → p (~ i), and transport refl x ≡ x — moving nowhere changes nothing.

Proof. Reversal is ~ from the interval (0.3) applied to the map of paths (0.4). For the second, note what is and is not being claimed: transport refl x is not the same term as x — Agda rejects refl as a proof of it, since transp (λ i → refl i) i0 x has still to be computed — but it is path-equal to x, which is what ≡ asserts and all that is used below. The path is built by filling the constant line (transportRefl in the library). ∎

Theorem 0.8 (the one fact). Σ[ y ∈ A ] (x ≡ y) — the values equal to x, each with its proof — is contractible, with centre (x , refl).

Proof. The path from the centre to any (y , p) slides along p itself: at stage t sit at the point p t, holding as its proof the piece of p from x up to t, which shows x ≡ p t. At t = 0 that is (x , refl); at t = 1 it is (y , p). The piece of p up to t is λ j → p (t ∧ j) — the i ∧ j of the term below. Its two ends follow from 0.3 alone: at j = 0 it is p (t ∧ 0) = p 0 = x, and at j = 1 it is p (t ∧ 1) = p t. So it is a path from x to p t, which is the proof the pair at stage t must carry. That is the whole use of ∧ here: it cuts a path off at a point. ∎

the checked term
open import Cubical.Foundations.Prelude
private variable ℓ : Level ; A : Type ℓ

singleton-contractible : (x : A) → isContr (Σ[ y ∈ A ] x ≡ y)
singleton-contractible x = (x , refl) , λ (y , p) i → p i , λ j → p (i ∧ j)
Centre (x , refl); the second component is the contraction, sliding any (y , p) back along p — this is J. Verbatim, typechecks under Agda 2.8.0 --safe against the cubical library; no postulates, no holes.

Corollary 0.9 (path induction, J). To act on every (y , p : x ≡ y) it suffices to give the value at (x , refl).

Proof. Transport the value at the centre forward along the contraction path of the one fact (0.8). This is the eliminator of ≡. ∎

Remark 0.10 (transport is J). transport (0.6) is exactly J for a goal that ignores the proof — C(y , p) = P y — so transport (0.6) and J (0.9) are one thing. (The identity type's eliminator is its initiality as an inductive family: Awodey–Gambino–Sojakova 2012.)

Remark 0.11 (what the base is). Everything below — transport, J, function extensionality, univalence (§2) — is built from the interval (0.3) and one thing done with it: paths compose, and can be pushed along one another (the filling of 2.4), which each type former supplies for its own type. Of the interval's operations, ∧ builds the contraction in the one fact (0.8), ~ reverses a path in reversibility of transport (0.7), and ∨ earns its place in 2.4, where a square is closed from two of its sides. No axiom is added about any type.

Remark 0.12 (what §1 does). §1 is the one fact (0.8) with x replaced by a function's output.

1. Partition by output

Definition 1.1 (the inputs over an output). For f : A → B and b : B, write

f⁻¹(b)  =  Σ[ a ∈ A ] (f a ≡ b)

— the inputs that land on b, each kept with its proof that it does.

Theorem 1.2 (partition by output). A ≃ Σ[ b ∈ B ] f⁻¹(b).

Proof. Forward a ↦ (f a , (a , refl)); backward (b , (a , p)) ↦ a. Both round trips are refl, the return using the kept proof p : f a ≡ b. Nothing is lost, only regrouped. ∎

the checked term
open import Cubical.Foundations.Prelude
open import Cubical.Foundations.Isomorphism
open import Cubical.Foundations.Equiv
private variable ℓ : Level ; A B : Type ℓ

partition : (f : A → B) → A ≃ (Σ[ b ∈ B ] fiber f b)
partition f = isoToEquiv (iso fwd bwd rinv (λ _ → refl))
  where
  fwd  = λ a → f a , a , refl
  bwd  = λ (b , a , _) → a
  rinv = λ (b , a , p) i → p i , a , λ j → p (i ∧ j)
The equivalence A ≃ Σ (b : B) . f⁻¹(b); fwd sends a to its output with the refl witness, bwd reads the kept input back, and both round trips are refl. Verbatim, --safe.

Definition 1.3 (completion). A completion of f is a family T assigning a type T(b) to each b, together with an equivalence A ≃ Σ[ b ∈ B ] T(b) that respects the output map — an input's b is unchanged.

Theorem 1.4 (the partition is the only one). Every completion of f is f⁻¹.

Proof. Respecting the output map means the equivalence carries the piece over each b to the piece over that same b; by the partition (1.2) the inputs over b on the right are exactly T(b), so it carries f⁻¹(b) onto T(b). A completion is therefore a choice, at each b, of a type equivalent to f⁻¹(b). The types equivalent to a fixed one form a contractible type (2.4), and a per-b choice among contractible options is again contractible (2.5). So T = f⁻¹: the decomposition is forced, not a chosen encoding. ∎

Remark 1.5 (what §1 rests on). The partition (1.2) stands on §0 alone. Its uniqueness (1.4) is the one place §1 looks forward, borrowing univalence (2.4) and function extensionality (2.5). Every decomposition later in the page is that partition: group by output, keep the inputs over each b.

2. Isomorphism is substitution

Definition 2.1 (equivalence). A ≃ B is maps both ways with proofs that they cancel: runnable in both directions, nothing lost either way. This is the lossless match the partition (1.2) asserts.

Proposition 2.2 (two sides of one thing). f has a two-sided inverse if and only if f⁻¹(b) is contractible for every b.

Proof. An inverse g centres f⁻¹(b) at (g b , ·), and the cancellation laws contract every (a , p : f a ≡ b) onto that centre (0.5). Conversely, choosing the centre of each f⁻¹(b) is an inverse. ∎

Remark 2.3 (property against data). The two sides (2.2) are not the same type. Contractible-fibred is a property, true in at most one way; an inverse is data, which may be given differently. The second is the one carried around.

Theorem 2.4 (univalence). ua : (A ≃ B) → (A ≡ B), and it computes: transportua(e) = e. Hence Σ[ X ] (X ≃ Y) is contractible.

$$ (A \simeq B)\ \simeq\ (A \equiv B), \qquad \mathsf{ua} : (A \simeq B) \longrightarrow (A \equiv B), \qquad \mathrm{transport}^{\,\mathsf{ua}(e)} \;=\; e $$

Proof. The primitive is the interval (0.3): a path is a map out of the interval (0.4), and paths can be joined end-to-end and pushed along one another — Kan composition, which is what runs transport. The second ingredient is Glue, a type former whose defining property is exactly what is wanted: given a type B, and on part of the boundary a type A with an equivalence A ≃ B, it yields a type that is A on that part of the boundary and B elsewhere. Apply it along one interval coordinate with A and e at the 0 end: the result is a map 𝕀 → Type sending 0 to A and 1 to B, which by 0.4 is a path A ≡ B, and transport along it is e. Contractibility is then the one fact (0.8) read at the universe, with ≡ between types supplied by ua. Voevodsky's axiom, built from the interval and Glue (Cohen–Coquand–Huber–Mörtberg 2018). ∎

Corollary 2.5 (function extensionality). Functions that agree at every argument are equal.

Proof. Given h : (x : A) → f x ≡ g x, the map λ i x → h x i is a path f ≡ g by paths (0.4) — the interval is pulled out of the argument. ∎

Remark 2.6 (structures interchange). By univalence (2.4) isomorphic structures interchange by a program, losslessly. This is the fact used by 1.4.

3. A step is reversible when its input can be recovered

Definition 3.1 (reversible). A step is reversible when some map sends its output back to its input, so it runs backward as well as forward, losing nothing (2.1). By reversibility of transport (0.7), transport and every equivalence are of this kind.

Theorem 3.2 (every reversible operation is a transport). A reversible operation is transport along a path, namely the one its own reversibility names, and that path is the only one inducing it.

Proof. Maps both ways whose round trips are the identity are an equivalence (2.1, 2.2), which ua turns into a path A ≡ B (2.4). Transport along that path is the operation, by univalence (2.4)'s computation rule. Uniqueness is ua being an equivalence, again univalence (2.4). ∎

the checked term
open import Cubical.Foundations.Prelude
open import Cubical.Foundations.Isomorphism
open import Cubical.Foundations.Equiv
open import Cubical.Foundations.Univalence
private variable ℓ : Level

-- A reversible operation: maps both ways whose round trips are the identity.
module _ {A B : Type ℓ} (f : A → B) (g : B → A)
         (fg : (b : B) → f (g b) ≡ b) (gf : (a : A) → g (f a) ≡ a) where

  -- Its reversibility IS an equivalence, so it names a path.
  its-equivalence : A ≃ B
  its-equivalence = isoToEquiv (iso f g fg gf)

  its-path : A ≡ B
  its-path = ua its-equivalence

  -- And transport along that path is the operation itself.
  reversible-is-transport : (a : A) → transport its-path a ≡ f a
  reversible-is-transport a = uaβ its-equivalence a

  -- The path is the only one that induces it: ua is an equivalence.
  the-path-is-unique : pathToEquiv its-path ≡ its-equivalence
  the-path-is-unique = pathToEquiv-ua its-equivalence
3.2 as a term. isoToEquiv is the step from reversibility to an equivalence, ua the step to a path, uaβ the computation rule that makes the transport be the operation. Verbatim, typechecks under Agda 2.8.0 --safe.

Definition 3.3 (effect-cost). A step is irreversible when several inputs share one output b: then which of them the input was is gone. That forgotten "which one" is the only thing a step can ever destroy. Its effect-cost is the entropy of the input given the output: log₂ of the number of inputs mapping to b when those are equally likely (2ᵏ inputs give k bits), and less when they are not — the count is the most it can be. This is one of the two axes; the other is the number of steps taken (5.7).

Proposition 3.4 (Landauer's principle). Destroying k bits dissipates at least k · k_B T ln 2 of heat, with k_B Boltzmann's constant and T the temperature; a reversible step dissipates 0.

Proof. Landauer in units (5.9), which derives it from reversibility (3.1) and effect-cost (3.3). ∎

Theorem 3.5 (reversibility costs nothing, for any measure). Let ℓ be any ℕ-valued measure that adds under composition with ℓ e = 0. Then ℓ g = 0 wherever g has a right inverse — no group laws are used.

$$ \ell(g) + \ell(g^{-1}) = \ell(\mathrm{id}) = 0 \;\Longrightarrow\; \ell(g) = 0 \qquad (\text{naturals} \ge 0) $$

Proof. A sum of naturals is 0 only when each summand is. ∎

the checked term
open import Cubical.Foundations.Prelude
open import Cubical.Data.Nat using (ℕ ; zero ; suc ; _+_ ; snotz)
open import Cubical.Data.Empty using (rec)

+≡0→≡0 : (m n : ℕ) → m + n ≡ 0 → m ≡ 0
+≡0→≡0 zero    n p = refl
+≡0→≡0 (suc m) n p = rec (snotz p)

module _ (G : Type) (_·_ : G → G → G) (e : G) (inv : G → G)
  (invr : (g : G) → g · inv g ≡ e)
  (ℓ : G → ℕ) (ℓe : ℓ e ≡ 0) (ℓ· : (g h : G) → ℓ (g · h) ≡ ℓ g + ℓ h) where

  -- ℓ g + ℓ g⁻¹ = ℓ (g · g⁻¹) = ℓ e = 0, and a natural sum is 0 only at 0.
  grading-vanishes : (g : G) → ℓ g ≡ 0
  grading-vanishes g = +≡0→≡0 (ℓ g) (ℓ (inv g))
    (sym (ℓ· g (inv g)) ∙ cong ℓ (invr g) ∙ ℓe)
Any additive measure ℓ (adds under composition, ℓ e = 0) vanishes wherever an inverse exists: ℓ g + ℓ g⁻¹ = ℓ e = 0, and a sum of naturals is 0 only when each is. The hypotheses are an operation, a unit, and a right inverse for each element: no associativity, no left inverse, no group laws at all. Verbatim, typechecks under Agda 2.8.0 --safe.

Corollary 3.6 (§§1–2 destroy nothing). transport and every equivalence destroy nothing: every construction in §§1–2 runs backward and dissipates no heat.

Proof. Reversibility (3.1) and the vanishing grading (3.5), or reversibility (3.1) and Landauer (3.4) for the bit count alone. ∎

Remark 3.7 (what is lost). The only thing a computation ever loses is an input it chose to forget. How many steps it takes to reach the answer is the length axis (5.7), treated in §5.

4. The diagonal

Definition 4.1 (point-surjective). Picture e : A → (A → B) as a table whose row a is the function e a; reading row a at its own index gives e a a, the diagonal. Call e point-surjective when every h : A → B appears as some row, with the row index produced:

onto e  =  (h : A → B) → Σ[ a ∈ A ] (e a ≡ h)

The Σ is untruncated, which is why the fixed point below comes out as a value you can hold.

Theorem 4.2 (Lawvere 1969). If e : A → (A → B) is point-surjective then every g : B → B has a fixed point.

$$ \Big(\forall\, h : A \to B.\ \ \Sigma\, a : A.\ \ e\,a \equiv h\Big) \;\Longrightarrow\; \Big(\forall\, g : B \to B.\ \ \Sigma\, b : B.\ \ g\,b \equiv b\Big) $$

Proof. Put h a := g (e a a), the twist of e by g. Point-surjectivity gives a₀ with e a₀ ≡ h, so

$$ e(a_0)(a_0) \;\equiv\; h(a_0) \;\equiv\; g\big(e(a_0)(a_0)\big) $$

and e a₀ a₀ is a fixed point of g. ∎

The proof reads e at one argument only, so the hypothesis can be weakened to exactly what it uses: it is enough that e hits the single function h. That weaker form, lawvere-one-row in the box, is what the diagonal lemma (4.6) and halting (4.10) supply, where only the definable or computable functions are rows.

Corollary 4.3 (contrapositive). If some g : B → B has no fixed point, no e : A → (A → B) is point-surjective.

the checked term
open import Cubical.Foundations.Prelude
open import Cubical.Data.Bool using (Bool ; true ; false ; not ; true≢false)
open import Cubical.Relation.Nullary using (¬_)
private variable A B : Type

-- φ is point-surjective: every B-valued observation on A is a row of φ.
PtSurj : (A → (A → B)) → Type
PtSurj {A = A} {B = B} φ = (g : A → B) → Σ[ a ∈ A ] φ a ≡ g

-- Read the row at its own index, then apply f.
twist : (A → (A → B)) → (B → B) → (A → B)
twist φ f a = f (φ a a)

-- The argument reads φ at ONE argument, so one row is the whole hypothesis.
lawvere-one-row : (φ : A → (A → B)) (f : B → B)
  → Σ[ a ∈ A ] (φ a ≡ twist φ f) → Σ[ b ∈ B ] f b ≡ b
lawvere-one-row φ f (a₀ , hit) = φ a₀ a₀ , sym (funExt⁻ hit a₀)

-- Lawvere 1969: a point-surjective φ forces every endomap of B a fixed point.
lawvere : (φ : A → (A → B)) → PtSurj φ → (f : B → B) → Σ[ b ∈ B ] f b ≡ b
lawvere φ surj f = lawvere-one-row φ f (surj (twist φ f))

-- Contrapositive: one fixed-point-free f kills point-surjectivity of every φ.
noFix→noPtSurj : (φ : A → (A → B)) (f : B → B)
  → ((b : B) → ¬ (f b ≡ b)) → ¬ PtSurj φ
noFix→noPtSurj φ f nofix surj = nofix (lawvere φ surj f .fst) (lawvere φ surj f .snd)

-- not has no fixed point: not true = false and not false = true.
not-no-fix : (b : Bool) → ¬ (not b ≡ b)
not-no-fix true  p = true≢false (sym p)
not-no-fix false p = true≢false p

-- Cantor, as the B = Bool, f = not instance (not has no fixed point).
cantor : (φ : A → (A → Bool)) → ¬ PtSurj φ
cantor φ = noFix→noPtSurj φ not not-no-fix
4.2 in one term — lawvere is three lines — with the contrapositive (4.3) and Cantor (4.4) as the checked instances. Russell and Tarski (4.11) are that same term at their own (B, g); Gödel (4.6–4.9) is that diagonal plus the arithmetic hypotheses its own box isolates; Rice (4.13) reads it in the other direction (4.12). Verbatim, --safe, untruncated Σ (the escaping index is exhibited, not merely asserted).

The impossibility theorems are Lawvere (4.2) or the contrapositive (4.3) at a named (B , g). Each instance below supplies only that naming.

Corollary 4.4 (Cantor). No e : A → (A → 2) is point-surjective.

Proof. The contrapositive (4.3) with B = 2, g = ¬: negation swaps true and false, so it has no fixed point. (A → 2) is the decidable subsets of A by characteristic functions — not every subset, which would be maps into propositions. ∎

Lemma 4.5 (representability). Work in a theory with sentences, a derivability predicate ⊢, negation, and a provability formula Prov — the box names these Sent, Pf, neg, prov. Code each one-variable formula by a number and let sub(m , n) be the code of formula m with the numeral n̄ substituted for its variable. Then sub is represented by a formula.

Proof. sub is primitive recursive, and every primitive-recursive function is represented by a formula: induct on how it is built — the base functions (zero, successor, projection) are formulas, and composition and primitive recursion stay first-order by quantifying, boundedly, over the finite run that computes the value. A base as weak as Robinson's Q suffices. ∎

Theorem 4.6 (the diagonal lemma). For every formula ψ there is a sentence G with ⊢ G ↔ ψ(⌜G⌝).

Proof. Lawvere (4.2) in the one-row form, at the table e(m)(n) = sub(m , n): row m is the formula coded by m, and reading row m at its own index is sub(m , m). The row 4.2 needs is the twist's, and that it is a row is representability (4.5), nothing more — the full notion of 4.1 is false here, most families of formulas being cut out by no formula, which is why the one-row form is the one that fires. Concretely, for g = ψ the twist δ(x) := ψ(sub(x , x)) is a formula, has a code d, and the fixed point G := δ(d̄) has code sub(d , d). The B this fires over is the sentences up to provable equivalence, where ↔ is equality, so g b = b read there is exactly ⊢ G ↔ ψ(⌜G⌝). The box records formulas, their application, and the fixed point just built as the interface HasDiagonal, and reads it in the ¬Prov form as diagonalGivesGoedelFix. ∎

Corollary 4.7 (Gödel, first conjunct). Take ψ = ¬Prov, so 4.6 gives G with ⊢ G ↔ ¬Prov(⌜G⌝) — G says I am unprovable. If the theory is consistent and satisfies D1 (⊢ s ⇒ ⊢ Prov⌜s⌝), then ⊬ G, and by soundness G is true.

Proof. goedelHalfOne in the box. If ⊢ G then D1 gives ⊢ Prov⌜G⌝, and the forward half of the fixed point (4.6) gives ⊢ ¬Prov⌜G⌝, contradicting consistency. Prov(⌜G⌝) is the formula a proof of G exists — one unbounded existential over a decidable proof-check, which is what Σ₁ names — so G's unprovability is its truth. ∎

Proposition 4.8 (the second conjunct is a further hypothesis). Consistency, D1 and the fixed point do not give ⊬ ¬G.

Proof. noHalfTwo runs any claimed derivation of ⊬ ¬G against the four-sentence model Wit in the box — ⊤, ⊥, g, ¬g with Prov constantly ⊤. It is consistent, satisfies D1, and carries the fixed point at g — whose two arrows are both vacuous, not by accident but in every model of these hypotheses: those already force ⊬ g (fixIsAlwaysVacuous, from 4.7) and ⊬ ¬Prov⌜g⌝ (provNegEmpty), so neither arrow ever receives an input. What Wit alone adds is that ¬g is provable — so no such derivation exists. Wit fails exactly where it must: OmegaBad, proving Prov⌜g⌝ yet not g — consistent but ω-inconsistent. (In a real arithmetic that gap is consistency surviving because the asserted proof is a nonstandard one no numeral names; Wit is the same separation stripped to four points and no arithmetic.) ∎

Theorem 4.9 (Gödel's first incompleteness theorem). If the theory is also ω-consistent, and its logic carries contraposition, double-negation elimination and transitivity internally, then G is independent: ⊬ G and ⊬ ¬G.

Proof. independenceFromRepresentability in the box. The first conjunct is 4.7. For the second, the backward half of the fixed point (4.6), ¬Prov⌜G⌝ → G, contraposed and cleared of its double negation (internalFix), gives ¬G → Prov⌜G⌝; so ⊢ ¬G would force ⊢ Prov⌜G⌝ alongside ⊬ G (4.7) — the OmegaBad that 4.8 exhibits and ω-consistency forbids. ∎ (Rosser 1936 lowers ω-consistency to plain consistency by changing the fixed point.)

the checked term — the Gödel construction (larger)
open import Cubical.Foundations.Prelude
open import Cubical.Data.Sigma
open import Cubical.Data.Unit using (Unit ; tt)
open import Cubical.Data.Empty as Empty using (⊥)
open import Cubical.Relation.Nullary using (¬_)
private variable ℓ : Level

-- A theory: sentences, a derivability predicate Pf, negation, and the
-- internal provability operator prov (already "the formula at a code").
record Theory (ℓ : Level) : Type (ℓ-suc ℓ) where
  field
    Sent : Type ℓ
    Pf   : Sent → Type ℓ
    neg  : Sent → Sent
    prov : Sent → Sent
open Theory public

Consistent : Theory ℓ → Type ℓ
Consistent T = (s : Sent T) → Pf T s → Pf T (neg T s) → ⊥

HBL1 : Theory ℓ → Type ℓ                       -- D1:  ⊢ s  ⇒  ⊢ Prov⌜s⌝
HBL1 T = (s : Sent T) → Pf T s → Pf T (prov T s)

GoedelFix : (T : Theory ℓ) → Sent T → Type ℓ   -- ⊢ G ↔ ¬Prov⌜G⌝
GoedelFix T G =
  (Pf T G → Pf T (neg T (prov T G))) × (Pf T (neg T (prov T G)) → Pf T G)

OmegaBad : (T : Theory ℓ) → Sent T → Type ℓ    -- ⊢ Prov⌜G⌝ yet ⊬ G
OmegaBad T G = Pf T (prov T G) × (¬ Pf T G)

Independent : (T : Theory ℓ) → Sent T → Type ℓ
Independent T s = (¬ Pf T s) × (¬ Pf T (neg T s))

-- Conjunct 1 (⊬ G): the fixed point's forward half, D1, consistency.
goedelHalfOne : (T : Theory ℓ) (G : Sent T)
  → Consistent T → HBL1 T → GoedelFix T G → ¬ Pf T G
goedelHalfOne T G con d1 (fwd , _) pG = con (prov T G) (d1 G pG) (fwd pG)

-- …so ⊬ G in EVERY such model, and the fixed point's forward arrow is
-- vacuous there — not a quirk of Wit below. Only ⊢ ¬G can still vary.
fixIsAlwaysVacuous : (T : Theory ℓ) (G : Sent T)
  → Consistent T → HBL1 T → GoedelFix T G → (Pf T G → Pf T (neg T (prov T G)))
fixIsAlwaysVacuous T G con d1 gf pG = Empty.rec (goedelHalfOne T G con d1 gf pG)

-- …and its backward arrow too: ⊢ ¬Prov⌜G⌝ would give ⊢ G through it.
provNegEmpty : (T : Theory ℓ) (G : Sent T)
  → Consistent T → HBL1 T → (gf : GoedelFix T G) → ¬ Pf T (neg T (prov T G))
provNegEmpty T G con d1 gf pNP = goedelHalfOne T G con d1 gf (snd gf pNP)

-- Conjunct 2 (⊬ ¬G) does NOT follow: a four-sentence countermodel with
-- consistency, D1 and the fixed point, in which ¬G is provable.
data W : Type where wtop wbot wg wng : W
wneg : W → W
wneg wtop = wbot
wneg wbot = wtop
wneg wg   = wng
wneg wng  = wg
wPf : W → Type
wPf wtop = Unit
wPf wbot = ⊥
wPf wg   = ⊥
wPf wng  = Unit
Wit : Theory ℓ-zero
Sent Wit = W
Pf   Wit = wPf
neg  Wit = wneg
prov Wit = λ _ → wtop
witCon : Consistent Wit
witCon wtop _ b = b
witCon wbot a _ = a
witCon wg   a _ = a
witCon wng  _ b = b
witHBL1 : HBL1 Wit
witHBL1 _ _ = tt
witFix : GoedelFix Wit wg
witFix = Empty.rec , Empty.rec
witProvesNegG : wPf (wneg wg)
witProvesNegG = tt
noHalfTwo :
  ((T : Theory ℓ-zero) (G : Sent T)
     → Consistent T → HBL1 T → GoedelFix T G → ¬ Pf T (neg T G)) → ⊥
noHalfTwo half2 = half2 Wit wg witCon witHBL1 witFix witProvesNegG

-- Representability, as the structure the diagonal lemma needs.
record HasDiagonal (T : Theory ℓ) : Type (ℓ-suc ℓ) where
  field
    imp  : Sent T → Sent T → Sent T
    mp   : (a b : Sent T) → Pf T (imp a b) → Pf T a → Pf T b
    Form : Type ℓ
    app  : Form → Sent T → Sent T
    fix  : (φ : Form)
         → Σ[ G ∈ Sent T ]
             (Pf T (imp G (app φ G)) × Pf T (imp (app φ G) G))
    negProv    : Form
    negProv-is : (s : Sent T) → app negProv s ≡ neg T (prov T s)
open HasDiagonal public

module _ (T : Theory ℓ) (D : HasDiagonal T) where
  goedelSentence : Sent T                       -- built, with its own code
  goedelSentence = fst (fix D (negProv D))
  diagonalGivesGoedelFix : GoedelFix T goedelSentence
  diagonalGivesGoedelFix =
      (λ pG → subst (Pf T) (negProv-is D goedelSentence)
                (mp D goedelSentence _ (fst (snd (fix D (negProv D)))) pG))
    , (λ pNP → mp D _ goedelSentence (snd (snd (fix D (negProv D))))
                (subst (Pf T) (sym (negProv-is D goedelSentence)) pNP))

-- Full independence, given ω-consistency and the internal rules the
-- second conjunct needs: contraposition, double-negation, transitivity.
module _ (T : Theory ℓ) (D : HasDiagonal T)
         (contra : (a b : Sent T)
                 → Pf T (imp D a b) → Pf T (imp D (neg T b) (neg T a)))
         (dne    : (a : Sent T) → Pf T (imp D (neg T (neg T a)) a))
         (trans  : (a b c : Sent T)
                 → Pf T (imp D a b) → Pf T (imp D b c) → Pf T (imp D a c))
         where
  private
    G : Sent T
    G = goedelSentence T D
    bwd' : Pf T (imp D (neg T (prov T G)) G)
    bwd' = subst (λ s → Pf T (imp D s G)) (negProv-is D G)
             (snd (snd (fix D (negProv D))))
  internalFix : Pf T (imp D (neg T G) (prov T G))
  internalFix = trans (neg T G) (neg T (neg T (prov T G))) (prov T G)
                  (contra (neg T (prov T G)) G bwd') (dne (prov T G))
  secondConjunct : (¬ Pf T G) → (¬ OmegaBad T G) → ¬ Pf T (neg T G)
  secondConjunct notG notOmega pNegG =
    notOmega (mp D (neg T G) (prov T G) internalFix pNegG , notG)
  independenceFromRepresentability :
      Consistent T → HBL1 T → (¬ OmegaBad T G) → Independent T G
  independenceFromRepresentability con d1 notOmega =
      goedelHalfOne T G con d1 (diagonalGivesGoedelFix T D)
    , secondConjunct (goedelHalfOne T G con d1 (diagonalGivesGoedelFix T D)) notOmega
The Gödel cluster 4.6–4.9 as one module, each term echoing its statement. HasDiagonal records what representability (4.5) provides — one-place formulas, their application, and the fixed point as a pair of implications, since Theory has no conjunction for a biconditional — and diagonalGivesGoedelFix reads that fixed point in the ¬Prov form (4.6). goedelHalfOne is the first conjunct, three lines (4.7), and fixIsAlwaysVacuous and provNegEmpty read off that it already empties both Pf G and Pf ¬Prov⌜G⌝ in every such model; the four-sentence Wit drives noHalfTwo (4.8); independenceFromRepresentability assembles both halves given ω-consistency (4.9). Self-contained; typechecks under Agda 2.8.0 --cubical --guardedness --safe --no-import-sorts against agda-cubical v0.9.

Corollary 4.10 (halting). No total H decides, of an arbitrary machine and input, whether it halts.

Proof. Running code a on input x is partial, so it is no table of total functions; a total halting-decider H makes it one, since φ(a)(x) := if H(a,x) then run(a,x) else 0 is then total. Every total computable h : A → 2 is a row of it: take any program for h; it halts everywhere, so H never diverts it. Now Lawvere (4.2) at g = ¬, in the one-row form: the twist δ(a) := ¬ φ(a)(a) is total and computable, hence a row, so δ ≡ φ(d) for some code d, and reading row d at its own index gives φ(d)(d) = ¬ φ(d)(d), which ¬, having no fixed point, forbids. ∎

Corollary 4.11 (Russell, Tarski). The non-self-members are no set's membership, and no truth predicate is definable.

Proof. The contrapositive (4.3) twice. Russell: B the propositions, g = ¬ on x ∈ x — the non-self-members are the diagonal row, and ¬ fixes nothing. Tarski: B the truth values, g = ¬ — a truth predicate would make the liar a fixed point of negation. ∎

Theorem 4.12 (Kleene's recursion theorem — the positive reading). Where e has a section — e being the interpreter, sending a code to the function it runs, and the section the compiler, sending a function to a code for it — Lawvere (4.2) hands every g a fixed point: a program equal to its own transform, the quine.

Proof. Lawvere (4.2) unchanged. The fixed-point-free instances — Cantor (4.4), halting (4.10), Russell–Tarski (4.11) — read it where g has no fixed point and conclude against e; here e is given and the conclusion is kept. ∎

Corollary 4.13 (Rice). No decider exists for a nontrivial semantic property of programs.

Proof. Suppose one, and take programs a that has the property and b that lacks it. By the recursion theorem (4.12) build a program which reads its own code, runs the decider on it, and then behaves like b if the verdict is yes and like a if no. Either verdict is wrong about it. ∎

Remark 4.14 (one lemma, many instances). There is no family of impossibility theorems: one lemma (4.2), applied at a different (B , g) each time, read in the other direction for the recursion theorem (4.12), and — at Gödel (4.6–4.9) — carrying the extra arithmetic hypotheses the diagonal alone does not supply. Rice sits on that second side rather than among the fixed-point-free instances.

Remark 4.15 (the fixed points are built). Because the Σ of point-surjectivity (4.1) is untruncated, 4.2 returns a fixed point as a value, and each instance inherits that: 4.6 builds the Gödel sentence goedelSentence with its own code sub(d , d), 4.10 builds the diagonal program δ, and 4.12 builds the quine. The classical statements assert that such a thing exists; here each is produced by the term in the box, instantiated at its own (B , g).

5. Complete inference is deterministic and step-optimal

§§0–2 supply substitution along an equality (0.6, 2.4), §3 reversibility (3.1), §4 the diagonal (4.2). This section fixes a machine, defines two costs on it, and proves the result stated at the top. The division of labour is worth stating once: §§0–4 are the semantics — what a proof, an answer and a reversible step are — and §5.2 fixes the machine they run on. Every cost result below is a theorem about that machine, and takes exactly one property of it: the one-step diamond (5.11).

5.1 Terms, proofs, questions

Definition 5.1 (the correspondence). Each connective is read as a type former:

A ⇒ BA → B, the function type: a proof sends a proof of A to one of B
A ∧ BA × B, the pair
A ∨ BA ⊎ B, the tagged sum
falsehood⊥, the empty type
∀ x. P x(x : A) → P x, the dependent function
∃ x. P xΣ[ x ∈ A ] P x, the dependent pair
modus ponensapplication
checking a proofnormalizing its term: running it until no step is left

For the first four rows — the propositional part, with sums and the empty type — the connectives and the type formers are one structure: the free bicartesian closed category (Curry 1934; Howard 1969; Lambek 1980). The two quantifier rows go past it, since their types depend on a value; the setting for those is a locally cartesian closed category, which is what §0 has been building.

Definition 5.2 (question, answer). A computation is a term of a value type, a decision a term of Dec P = P ⊎ ¬ P, an answer a term of the type the question asks for. The answer to a question is the normal form of that term.

Proposition 5.3 (one operation). Proving, deciding, computing and answering are one operation: build the term, normalize it.

Proof. Immediate from the correspondence (5.1) and questions and answers (5.2): the four differ only in which type the term inhabits. ∎

5.2 The machine

Definition 5.4 (net). A cell has one distinguished principal port and finitely many auxiliary ports. A net is a finite set of cells with a partial matching of their ports by wires. The distance between two cells is the number of wires on a shortest path between them.

Definition 5.5 (interaction step). An active pair is two cells whose principal ports are wired to each other. For each pair of cell kinds a rule gives a net R on exactly the auxiliary wires of those two cells:

$$ \dfrac{\;(c_1,c_2)\ \text{an active pair of}\ N \qquad (c_1,c_2) \longrightarrow R\;}{\;N \longrightarrow N[(c_1,c_2) := R]\;} $$

Every other cell and wire of N is unchanged. Write Step s t for one such step.

Definition 5.6 (trace, length, normal form).

data Trace : ℕ → S → S → Type where
  done      : {s : S} → Trace zero s s
  stepTrace : {n : ℕ} {s u t : S} → Step s u → Trace n u t → Trace (suc n) s t

Normal : S → Type
Normal t = (u : S) → Step t u → ⊥

The length of a trace is its index n.

5.3 Two costs

Definition 5.7 (the two axes). The length of a reduction is the number of steps it takes (5.6). Its effect-cost is the quantity defined in 3.3: the entropy of its input given its output.

Proposition 5.8 (the two costs of a step). A reversible step has effect-cost 0 and length 1. A step merging 2ᵏ inputs into one output has effect-cost k and length 1.

Proof. A step whose input can be recovered is a bijection (3.1), so one input shares each output and log₂ 1 = 0; a 2ᵏ-fold merge gives log₂ 2ᵏ = k. Neither touches the step count. ∎

Proposition 5.9 (Landauer's bound, in units). A step of effect-cost k dissipates k · k_B T ln 2 of heat, and a reversible step dissipates 0.

Proof. Reversibility (3.1) and effect-cost (3.3) read twice — once on the datum, once on the dynamics carrying it. A 2 → 1 merge of microstates is an entropy drop of ln 2 nats, k_B ln 2 once k_B converts nats to thermodynamic entropy. Reversibility (3.1) splits the ambient dynamics into two cases. Injective: the two microstates the step merged stay distinct in it, so the distinction the datum lost is now in the surroundings, as heat T ΔS, with T the conversion of entropy to energy that defines temperature. Non-injective: it is a merging step itself, and effect-cost (3.3) charges it the same k one level down. Both cases pay k bits; k_B and T convert that to joules. By the two costs (5.8) a reversible step has k = 0, so the drop is 0 and the heat is 0. ∎ (Landauer 1961; Bennett 1973, 1982 named it.)

Remark 5.10 (what the price covers). The effect-cost is charged against the observation: the bits erased for the requested output, not for a whole trace. The length cost is a separate axis, bounded by a potential (5.15) and by no count of solutions (Search).

5.4 Every reduction is the shortest

Lemma 5.11 (one-step diamond). If Step s a and Step s b then a ≡ b, or there is c with Step a c and Step b c.

Proof. Two distinct active pairs are disjoint: distinct principal-port pairs cannot share a cell. By interaction (5.5) each step leaves everything outside its own pair untouched, so doing one leaves the other available and untouched, and the two converge in one further step each. This is structural to interaction nets (Lafont 1990), not an assumption. It is also why the machine is nets and not terms: β-reduction is confluent but has no one-step diamond — two overlapping β-redexes need several steps to reconverge, which is why the classical proof goes through parallel reduction — so the equal-length result below is false for it. A rule firing on an active pair cannot overlap another, by the disjointness just shown, and that is the whole difference. ∎

Lemma 5.12 (peel). Step s u → Trace (suc n) s t → Normal t → Trace n u t.

Proof. Induction on the trace's length. Apply the diamond (5.11) to the given step and the trace's first step: either they merge, and the tail is the required trace, or they reach a common term, from which the inductive hypothesis peels the shorter tail. At a normal form no step is left to carry, so the given step is absorbed exactly once. ∎

Theorem 5.13 (equal length). Trace n s t → Trace m s t → Normal t → n ≡ m.

Proof. Induction on the first trace, peeling its first step through the second by peel (5.12). ∎

the checked term
-- as a file: RandomDescent.agda
open import Cubical.Foundations.Prelude
open import Cubical.Data.Nat using (ℕ ; zero ; suc)
open import Cubical.Data.Nat.Order using (_≤_ ; ≤-refl)
open import Cubical.Data.Sigma
open import Cubical.Data.Sum using (_⊎_ ; inl ; inr)
open import Cubical.Data.Empty as Empty using (⊥)

module RandomDescent (S : Type) (Step : S → S → Type)
  (diamond : {s a b : S} → Step s a → Step s b
    → (a ≡ b) ⊎ (Σ[ c ∈ S ] (Step a c × Step b c))) where

  data Trace : ℕ → S → S → Type where
    done      : {s : S} → Trace zero s s
    stepTrace : {n : ℕ} {s u t : S} → Step s u → Trace n u t → Trace (suc n) s t

  Normal : S → Type
  Normal t = (u : S) → Step t u → ⊥

  -- Any available first interaction removes exactly one unit from any
  -- terminating reduction to the same normal form. It cannot detour.
  peel : {n : ℕ} {s u t : S} → Step s u → Trace (suc n) s t → Normal t → Trace n u t
  peel {zero} jump (stepTrace first done) normal with diamond first jump
  ... | inl same             = subst (λ v → Trace zero v _) same done
  ... | inr (z , left , right) = Empty.rec (normal z left)
  peel {suc n} jump (stepTrace first rest) normal with diamond first jump
  ... | inl same             = subst (λ v → Trace (suc n) v _) same rest
  ... | inr (z , left , right) = stepTrace right (peel left rest normal)

  normal-length-zero : {n : ℕ} {s t : S} → Normal s → Trace n s t → n ≡ zero
  normal-length-zero normal done                     = refl
  normal-length-zero normal (stepTrace first rest)   = Empty.rec (normal _ first)

  zero-endpoints : {s t : S} → Trace zero s t → s ≡ t
  zero-endpoints done = refl

  -- All complete reductions of THIS object to THIS normal form have one length.
  same-normalization-length : {n m : ℕ} {s t : S}
    → Trace n s t → Trace m s t → Normal t → n ≡ m
  same-normalization-length done other normal = sym (normal-length-zero normal other)
  same-normalization-length {m = zero} (stepTrace first rest) other normal =
    Empty.rec (normal _ (subst (λ s → Step s _) (zero-endpoints other) first))
  same-normalization-length {m = suc m} (stepTrace first rest) other normal =
    cong suc (same-normalization-length rest (peel first other normal) normal)

  normalization-is-geodesic : {n m : ℕ} {s t : S}
    → Trace n s t → Trace m s t → Normal t → n ≤ m
  normalization-is-geodesic chosen competitor normal =
    subst (_ ≤_) (same-normalization-length chosen competitor normal) ≤-refl
The step-count is fixed by the endpoints, never the strategy: peel pushes any first step through any reduction, and same-normalization-length inducts to equal length. Generic in (S, Step, diamond) — instantiated by any system with the interaction-net diamond. Verbatim, typechecks under Agda 2.8.0 --safe.

Corollary 5.14 (the length is fixed by the endpoints). Every reduction of a term to its normal form has the same length, so each is the minimum: the step-count is fixed by the endpoints, never by the strategy, and the cost is as deterministic as the answer.

Proof. Equal length (5.13) with ≤-refl, as normalization-is-geodesic in the box. ∎

Theorem 5.15 (Bellman). In the reduction graph — vertices terms, edges steps of cost c(u→v) — call Φ a potential when Φ(normal form) = 0 and Φ(u) ≤ c(u→v) + Φ(v) on every edge. Then every potential is a lower bound on every finishing path, and where a normal form is reachable the geodesic distance is the greatest potential, satisfying

$$ \Phi(\text{normal form}) = 0, \qquad \Phi(u) = \min_{v}\, \big[\, c(u \to v) + \Phi(v)\,\big] $$

Proof. Adding the edge inequality along any path to a normal form, where Φ = 0, gives Φ(u) ≤ the path's total cost. The geodesic distance satisfies both conditions, so it is a potential, and it meets the bound with equality at the cheapest edge (Bellman 1957). By minimality (5.14) it is attained by every reduction, so there is nothing to minimise over. ∎

Theorem 5.16 (unit lookahead). An output that must read input at distance n from it cannot be produced in fewer than n steps — a bound on every reduction, not on one chosen strategy.

Proof. By interaction (5.5) one step changes the datum only where its two cells sat, so its output at a position depends on that position and its one wired neighbour. Composing k steps, the output depends only on input within distance k of it in the net one started from: one step reaches a wired neighbour, so each widens the reach by exactly one. The rewriting does not let that slip — a rule replaces two cells by a net on their own auxiliary wires, and the cells it puts there can carry only what those two already held, so no interaction moves information further than one wire, however the distances in the rewritten net come out. ∎

Read from the other end, the same k is an information demand. Write x ≡ₙ y for agreement through observational depth n: the bound says x ≡ₙ₊ₖ y ⇒ w(x) ≡ₙ w(y) for every k-step w, so an output determined to depth n requires source read to depth n + k. One number, two orientations — elapsed interaction depth read dynamically, source information required read observationally — and both are the length axis (5.7), not a third cost: the effect-cost (3.3) counts what collides under an observation, this counts what must be read to produce it. In the observational orientation the criterion of 8.11 reads as a radius, since one step widens the source a position can consult by exactly one wire.

Corollary 5.17 (step-optimality). The native evolution attains the geodesic: no reduction is shorter than the one it takes.

Proof. Minimality (5.14). ∎

Theorem 5.18 (unique normal form). A term has at most one normal form.

Proof. The diamond (5.11), tiled. Take two reductions of one term; the diamond closes their first steps to a common term, and filling the grid step by step reconverges them. If both end at a normal form — nothing left to rewrite — that common reduct can only be each endpoint, so the two are equal. (Church–Rosser, here the diamond filled in.) ∎

Corollary 5.19 (the dichotomy). For every question there are two cases and no third. Either a normal form exists, and by minimality (5.14) and unique normal form (5.18) every reduction reaches that one answer in the one step-count the endpoints fix; or §4 proves there is none — a decider for one's own halting is among these, since asking for one asks for the fixed point the diagonal forbids — and the question had no answer to find, which the system establishes rather than running out of time looking.

Remark 5.20 (what well-formed names). Well-formed names the first case, and the reduction decides which case a question is in. What the dichotomy (5.19) fixes is reachability, not length: a long geodesic is a real price, charged honestly, and already the shortest (5.14).

5.5 What the length counts

Proposition 5.21 (the building route is the size of the answer). Take a rule set in which each interaction emits at most one constructor — true of the standard encodings, and a property of the rules rather than of interaction (5.5). The normal form is then a complete proof-carrying witness — the answer with its certificate — and the steps that build it number exactly its constructors.

Proof. Each building step emits exactly one constructor — one piece of the answer, a successor, a pair, a tag — so the building route's length equals the witness's size; building sucⁿ takes one successor per step. A term carrying extra redexes — spots still waiting to reduce, like (λx.x) t — clears those first, administrative steps building nothing, so its total length is its own geodesic by minimality (5.14) while the witness's size counts only the constructors built. Reading the finished term off is a fold that copies it, adding no step. ∎

Remark 5.22 (two exponentials). By the building route (5.21) the building route's length is the witness's size in unary. When that unary size is exponential in the question's succinct binary measure — as sucⁿ is, n against log n — the route is exponentially longer than the succinct measure. That exponential is the observer's lossy binary measure laid against a lossless unary object; change the measure, not the computation, and it is gone. The other exponential can be real: the geodesic length when a small witness ends a long reduction. That is a length, so no change of measure touches it; it is the reduction's own fixed distance, already the minimum by minimality (5.14).

Remark 5.23 (what is solved). The optimization problem — the fewest steps to an answer, what complexity theory exists to chase — is here solved: computation modeled as lossless reduction is optimal by construction, optimality its standing condition. The million wasteful ways to compute the same answer are departures from this model, not rival strategies within it. Only the diamond (5.11) is used, so 5.13–5.19 hold of any reduction that has the diamond.

Remark 5.24 (sharing). Sharing is written into the net. A shared subterm is held by a cell — a duplicator, wired in at ports like every other cell — so it belongs to the net's syntax, in place before any reduction begins: no bookkeeping outside the net itself, and the diamond (5.11) used only the disjointness of active pairs, not sharing. Its price is charged: a duplicator's interactions are steps on the length axis exactly like the rest, and on the effect axis they are free by the two costs (5.8), since folding along an equality is transport (0.6) and runs backward (0.7). What sharing buys is the one thing claimed for it: an active pair is never duplicated, so no step repeats work.

Remark 5.25 (termination). Where a term terminates it is reached in finitely many forced steps; a non-terminating term denotes a well-defined infinite (coinductive) object, not a gap.

Remark 5.26 (no outer layer). Evaluator, type-checker and optimizer are themselves terms of the same language, and a question about them is another term the same normalizer reduces. There is no meta-level, so no self-reference contradiction: reasoning about its own terms as data, it proves the §4 impossibilities as ordinary theorems — and, as those theorems say, it does not decide its own halting, and has a sentence it neither proves nor refutes (4.9) — which is 5.27’s case (b) twice over, since independence is the pair ⊬ G and ⊬ ¬G, two types established empty. Any expressible system, this one included, is lawful construction and identity, operated on exactly as everything else is: the language is its own metatheory, standing nowhere outside itself.

5.6 The result

Theorem 5.27 (complete inference). Let a declaration be any type — anything rationally stateable (the correspondence (5.1), 5.2). Pose it together with the identities available, which by uniqueness of the partition (1.4) is forced rather than a choice of encoding, and normalize. Then exactly one of two cases holds, and the reduction itself decides which:

(a) the declaration is inhabitable, and the normal form is an inhabitant of it — a proof, carrying its own acceptance as refl (decide = verify (8.6)) — reached in a number of steps fixed by where the reduction starts and ends (equal length (5.13)), which no order of applying the identities can beat (5.14, 5.17), and with no step repeating work (sharing (5.24));

(b) it is not inhabitable, and §4 names the obstruction: the system establishes that no inhabitant exists, rather than failing to find one (the dichotomy (5.19)). Case (b) is a statement about the declared type and never a term of a negation one level inside it — where the declaration is a theory’s provability of a sentence, establishing it empty is ⊬ G, not ⊢ ¬G (4.7, 4.8).

By no outer layer (5.26) this holds of declarations about the system itself.

Proof. One operation (5.3) makes proving, deciding, computing and answering the same act, so the four are this one statement. Unique normal form (5.18) makes the inhabitant unique; 5.13 makes every reduction to it the same length and 5.14 makes each one minimal; unit lookahead (5.16) is the matching lower bound; 5.19 supplies the two cases and no third. ∎

Remark 5.28 (the scope of the minimum). The minimum in complete inference (5.27) is over orders of applying the identities, not over choices of starting term: a different term inhabiting the same type has its own length. What 5.13 settles is that once the declaration is posed there is no search over methods left to perform — every way of following the identities takes the same number of steps, so none is cleverer than another, and only the identities remain to follow.

6. Numbers

Definition 6.1 (counting). To count a finite set is to forget which element is which. Any two n-element sets differ only by a relabelling, so all of them are one thing; what the forgetting throws away is exactly the relabellings, the n! permutations of n things. To count is to keep the class and discard Sₙ:

$$ \mathbb{N} \;=\; \{\text{finite sets}\}\,/\,\cong, \qquad \mathrm{Aut}(\text{an } n\text{-element set}) \;=\; S_n $$

Greek arithmetic states this construction outright. Euclid VII Def. 1–2 define the unit as "that by virtue of which each of the things that exist is called one" and a number as "a multitude composed of units" — so the unit is defined separately and is not itself among the numbers, which is identity's standing here too (0.2): it generates the sequence without being a term of it. And the units are athetos, without position: a monad is a position-less substance where a point is one having position (Aristotle, Metaphysics 1016b; Posterior Analytics 87a36). Position-less is the whole content of this definition. Units with no position have nothing to tell one from another, so a multitude of them carries nothing beyond how many there are, and every relabelling of it is the same multitude. That is Sₙ discarded, given as a definition rather than derived.

Proposition 6.2 (card). card is the bijection between iso-classes of finite sets and ℕ, with inverse n ↦ {1,…,n}.

Being a bijection and not a measurement, the number is the iso-class rather than a label attached to it. Aristotle marks exactly this as the Pythagorean position against the Platonic one (Metaphysics 1090a): number is not separated from the things.

Proposition 6.3 (arithmetic). Addition is disjoint union and multiplication is product:

|A ⊎ B| = |A| + |B|        |A × B| = |A| · |B|

Written in base b, adding two digit strings is this disjoint union done place by place, carrying whatever overflows a place into the next.

Proposition 6.4 (divisibility is a distributive lattice). d ∣ n iff each prime's exponent in d is ≤ its exponent in n. So gcd is the meet (minimum exponents) and lcm the join (maximum), and unique factorization sends n to its exponent vector, making ℕ the product of one chain per prime, where minimum and maximum distribute componentwise.

Theorem 6.5 (number theory and logic are one lattice). The divisor lattice carries the operations of propositional logic: gcd/lcm are ∧/∨, coprimality is disjointness, the divisibility order is entailment, and d ↦ n/d is an order-reversing involution satisfying De Morgan. So divisibility and the propositional connectives are one algebra — the same distributive lattice with involution, whether the elements are divisors or truth values — and 6.6 says when it is the Boolean one.

Proof. The product decomposition of the divisor lattice (6.4) matches the Chinese remainder theorem ℤ/mn ≅ ℤ/m × ℤ/n by x ↦ (x mod m, x mod n): injective, since coprime m, n both dividing x − y force mn ∣ (x − y), hence bijective by count. ∎

Proposition 6.6 (Boolean exactly on the squarefree). Being finite and distributive, the divisor lattice of every n is a Heyting algebra. It is Boolean iff n is squarefree.

Proof. What varies is whether the involution of 6.5 is the Heyting negation. On squarefree n it is: a divisor is a subset of the primes and n/d its complement. A repeated prime breaks it — on n = p² the divisors are the chain 1 < p < p², where the Heyting negation of p is 1 and ¬¬p = p² ≠ p, while the involution sends p to n/p = p. So the lattice is Boolean on squarefree n and properly intuitionistic otherwise. ∎

7. Complex numbers and quantum dynamics — the reversible side of §3

Definition 7.1 (the quarter-turn). σ(x , y) = (−y , x), a length-preserving quarter-turn of the plane. Write i for σ: then σ(x,y) = (−y, x) is i·(x + iy) = −y + ix. It is reversible, so free on the effect axis by the vanishing grading (3.5).

Proposition 7.2 (σ² = −1). σ² = −1.

Proof. σ²(x,y) = σ(−y,x) = (−x,−y) = −(x,y). The identity needs no analysis and holds over any ring; the box checks it on the integer lattice, where it is exact arithmetic. ∎

the checked term
open import Cubical.Foundations.Prelude
open import Cubical.Data.Int using (ℤ ; -_)
open import Cubical.Data.Sigma

-- the quarter-turn of the plane: (x, y) ↦ (−y, x).
σ : ℤ × ℤ → ℤ × ℤ
σ (x , y) = (- y , x)

-- σ² is negation — σ is a square root of −1 — on the nose.
σ²≡neg : (p : ℤ × ℤ) → σ (σ p) ≡ (- fst p , - snd p)
σ²≡neg (x , y) = refl
By refl: σ² = −1 is not proved here but computed, the two sides reducing to the same pair. Verbatim, typechecks under Agda 2.8.0 --safe.

Corollary 7.3 (ℂ, the phases, unitarity). The complex numbers, the four phases and unitarity are generated by this one reversible operation.

Proof. By σ² = −1 (7.2) the powers of σ cycle 1, σ, −1, −σ, the phases {1, i, −1, −i}; adjoining σ to the reals by those same two lines is ℝ[σ]/(σ²+1) = ℂ; and σ, a rotation, preserves length, so it is unitary. Unitary evolution is exactly the reversible side of 3.1; the physics that costs — measurement, erasure — is the irreversible side (3.3, 5.9). ∎

Theorem 7.4 (Riemann–Silberstein). With F = E + iB and units in which c = 1 — otherwise F = E + icB, and a c rides along on the right — Maxwell's two vacuum equations are one Schrödinger equation:

$$ \partial_t E = \nabla\times B,\ \ \partial_t B = -\nabla\times E \;\Longleftrightarrow\; i\,\partial_t F = \nabla\times F $$

Proof. i ∂_t F = i ∂_t E − ∂_t B = i(∇×B) + ∇×E = ∇×(E + iB) = ∇×F, using the two Maxwell equations; splitting real and imaginary parts gives them back. Classical electromagnetism and single-particle quantum mechanics are the same equation. ∎

Lemma 7.5 (curl is self-adjoint). ∫ a·(∇×b) = ∫ (∇×a)·b.

Proof. Integrate ∇·(a×b) = b·(∇×a) − a·(∇×b) over a domain with no boundary — a torus, or fields decaying at infinity — where the left side integrates to zero. ∎

Theorem 7.6 (the flow is unitary). ‖F‖² is conserved, and the generator −i∇× is skew-adjoint.

Proof. ‖F‖² = ⟨E+iB, E+iB⟩ = ‖E‖² + ‖B‖², the Hermitian cross terms ±i⟨E,B⟩ cancelling. From ∂_t F = −i∇×F (7.4),

$$ \tfrac{d}{dt}\,\lVert F\rVert^2 \;=\; 2\,\mathrm{Re}\,\langle F,\ \partial_t F\rangle \;=\; 2\,\mathrm{Re}\,\langle F,\ -i\,\nabla\times F\rangle \;=\; 2\,\mathrm{Im}\,\langle F,\ \nabla\times F\rangle \;=\; 0, $$

since curl is self-adjoint (7.5) at a = b = F makes ⟨F, ∇×F⟩ real, so its imaginary part vanishes. A length-preserving flow is unitary. ∎

8. Search

Definition 8.1 (solutions). For F : assignments → {true, false}, the solutions are the fibre (1.1) at b = true:

$$ \text{solutions of } F \;=\; F^{-1}(\text{true}) \;=\; \{\, w : F(w) = \text{true} \,\} $$

Write S_F for this type, and Q_N for the 2^N assignments.

Theorem 8.2 (the cube splits). Q_N = S_F ⊎ ⋃α V_α, where V_α is the subcube of assignments breaking clause α. Deciding and solving are two observations of this one partition.

Proof. The partition (1.2) at F. For 3-SAT a clause forbids exactly one setting of its three literals, so the assignments that break it fill a subcube V_α — those three bits fixed to the forbidden setting, the other N−3 free, a codimension-3 face. Every assignment either satisfies all clauses, so lies in S_F, or lies in some V_α, and S_F is disjoint from ⋃ V_α. ∎

Theorem 8.3 (the count).

$$ \#\text{solutions} \;=\; \sum_{T \subseteq C} (-1)^{|T|}\, 2^{\,N - r(T)} $$

Proof. Inclusion–exclusion on the cube splits (8.2): #S_F = Σ_{T⊆C} (−1)^{|T|} |⋂_{α∈T} V_α|. When the clauses in T can be violated together, |⋂_{α∈T} V_α| = 2^{N−r(T)} with r(T) the coordinates they jointly fix; when two of them demand opposite values on a shared variable the intersection is empty and contributes 0. Regrouping per assignment by the j clauses it breaks, its weight is Σ_{i≤j} C(j,i)(−1)^i = (1−1)^j, which is 1 only at j = 0: each solution survives once, the rest cancel. ∎

Definition 8.4 (deciding, solving). Solving is S_F — a vertex with its membership proof. Deciding is ‖S_F‖, writing ‖·‖ for the proposition that this is inhabited: one bit, and when true a single point, every witness collapsed onto it. The truncation is τ : S_F → ‖S_F‖.

Theorem 8.5 (what the one bit discards). The pre-image of τ is S_F itself, and τ has no left inverse once |S_F| > 1.

Proof. τ sends every witness to the one point, so by the fibre (1.1) its pre-image is Σ[ w ∈ S_F ] (τ w ≡ pt). Since ‖S_F‖ has any two of its points equal, the equality component carries nothing, and the pre-image is S_F. The one-bit decision therefore discards exactly the which-witness pre-image. ∎

Theorem 8.6 (deciding and verifying are one equivalence). For the machine's step f, decide(a) = (f a , (a , refl)) and verify reads the witness's pre-image back out; the round trip is refl.

Proof. Deciding an input a completes it to an answer with a witness, and by the partition (1.2) that completion is the equivalence A ≃ Σ[ b ] f⁻¹(b), unique by uniqueness of the partition (1.4). The two directions are decide and verify. The decided witness carries its own acceptance as refl, so the lossless run produces the witness with the answer in one forward pass, and verifying is that pass reversed: no operation sits between them for a gap to live in. ∎

the checked term
open import Cubical.Foundations.Prelude
open import Cubical.Foundations.Equiv using (fiber)
private variable ℓ : Level ; A B : Type ℓ

decide : (f : A → B) → A → Σ[ b ∈ B ] fiber f b
decide f a = f a , a , refl

verify : (f : A → B) → (Σ[ b ∈ B ] fiber f b) → A
verify f (b , a , _) = a

-- verify inverts decide on the nose -- nothing searched between answer and proof.
verify-inverts-decide : (f : A → B) (a : A) → verify f (decide f a) ≡ a
verify-inverts-decide f a = refl

-- the decided witness carries its own acceptance as refl.
witness-self-certifies : (f : A → B) (a : A) → snd (snd (decide f a)) ≡ refl
witness-self-certifies f a = refl
8.6 as a term: verify-inverts-decide is the round trip, witness-self-certifies the refl the decided witness carries. Both hold by refl, so neither is proved here — each reduces to the other side. Verbatim, typechecks under Agda 2.8.0 --safe.

Remark 8.7 (what the bit throws away). ‖S_F‖ is the lossy projection that throws the witness away (8.5); the lossless machine never does. What is left to ask of a problem is how many steps the output it asks for forces, and Bellman (5.15) fixed the form any answer to that must take.

Proposition 8.8 (the moment tower). #SAT = Σ_{T compatible} (−1)^{|T|} 2^{N−r(T)} = Σ_r (−1)^r M_r, the alternating collapse of the clause-intersection (factorial-moment) tower M_r = Σ_{|T|=r} |⋂ V|. The scalar count is the extremely lossy projection (1,−1,1,…)·(M_r), and F is unsatisfiable iff it is 0.

Proof. Regroup the count (8.3) by |T|. ∎

Proposition 8.9 (eight clauses). An unsatisfiable formula whose every clause has exactly three literals needs m ≥ 8 clauses, and eight suffice.

Proof. Write ν(x) for the clauses assignment x violates. Each clause is violated by 2^{N−3} assignments, and unsatisfiability means every x violates at least one, so Σ_x ν(x) = m·2^{N−3} ≥ 2^N, that is m ≥ 8. Sharp: the eight clauses on three variables, one for each sign pattern, forbid all eight settings. ∎

Theorem 8.10 (no count bounds the length). None of the four counts proposed as lower bounds — assignments, satisfying vertices, clause-intersections, and the width of a fixed-order pass — bounds the length of the problem: each can be made small by factoring or a change of coordinates while the problem stays the same, so none can serve as the potential of Bellman (5.15) for the problem itself.

Proof. Each collapses under factoring or a change of coordinates. Disjoint triples: m clauses on disjoint variable-triples each kill 1 of 8 and leave 7, so #SAT = 7^m while the intersections number 2^m. Inner product ⟨x,y⟩ mod 2: read all of x first and the state reached must fix the map y ↦ ⟨x,y⟩ — distinct x ≠ x′ give different maps, disagreeing at y = e_i, the vector with a single 1 in place i, wherever x_i ≠ x′_i — so the 2ⁿ inputs force 2ⁿ distinct states, width 2ⁿ; read the pairs x_i, y_i interleaved and it is a running parity, remembering x_i and folding x_i y_i in, width ≤ 4. ∎

Remark 8.11 (what a lower-bound proof must exhibit). With unit-cost primitive steps, Bellman (5.15)'s inequality reads Φ(u) ≤ 1 + Φ(v), so Φ can fall by at most one per step. An exponential lower bound is therefore a Φ that starts out exponential and still falls by at most one per step — equivalently, an exponentially large supply of obligations of which one step can discharge at most one. Nothing here exhibits one for SAT.

9. Ordering — what counting discards

One problem, taken end to end. Sorting is where a reader is most certain that a method has to be chosen, and it is where the construction says there is nothing to choose. The fibre is §1, the halving is §2, keeping the permutation is §3, the two costs are §5’s, and the number being sorted is §6’s. Nothing below is added to the construction; all of it is used.

Definition 9.1 (sorting). To sort a finite set is to assign it indices matching its order — to compute the ordering, delivered as a sequence. The orderings of n elements number n!, and each comparison restricts which of them survive.

Theorem 9.2 (the fibre is the relabellings). The fibre of sort over a sorted sequence is the n! rearrangements of it: a list is a sorted list together with a permutation, and nothing besides.

Proof. The partition (1.2) at sort, whose fibre (1.1) over a sorted sequence is the inputs landing on it, and forced rather than chosen by 1.4. ∎

Counting (6.1) discards exactly these relabellings to reach the number; sorting recovers the one the order names. The two are one forgetting, run in opposite directions. Keep the permutation and the run destroys nothing (3.6); deliver the sorted sequence alone and the effect-cost (3.3) is log₂ n!, the size of the fibre.

Proposition 9.3 (a comparison is a restriction). A comparison leaves exactly the orderings consistent with its outcome. Comparing two elements about which nothing is known leaves half, since exchanging them is a bijection between the orderings answering one way and those answering the other (2.6). A comparison already implied leaves all of them and is never made: what is held is a partial order, so from a < b, b < c, b < d the relations a < c and a < d are there already, the n² pairs never stored.

Proposition 9.4 (which comparison). Naming any still-unordered pair is not enough: a supply offering (a,b), then (a,c), then (a,d) spends n−1 comparisons to learn only which element is least. The one that excludes most is wanted. Of the twenty-four orderings of four elements, a < b leaves twelve. Comparing c with d halves those to six; comparing a with c instead leaves eight when a wins — a least of three, one of three equally — so its worse outcome is worse than six. Fresh pairs are taken while any remain. With a < b and c < d the six survivors are the C(4,2) interleavings, and comparing the two least leaves three either way, where comparing b with c leaves five in one outcome, b < c forcing abcd alone. The least are compared, and the result is one component with a known least, below everything in both. Five comparisons in all, and ⌈log₂ 24⌉ = 5.

Theorem 9.5 (why the least halve). A comparison between two elements exchanged by a symmetry of what is already known splits the survivors exactly in half.

Proof. The exchange carries orderings consistent with what is known to orderings consistent with it and swaps the two outcomes, so it is a bijection between them (2.6), and two sets in bijection are equal halves of their union. Two runs of equal length are exchanged by the symmetry that interchanges them, which carries least to least. No symmetry of a < b, c < d exchanges b with c, which is why that comparison is lopsided. ∎

Each such comparison establishes a new least for the two components it joins; every relation already established stays, and the loser remains least of its own run. Two fresh elements are always so exchanged, so a fresh pair always yields one.

Definition 9.6 (merge). Sortedness unfolds into one recursion, and merge is that unfolding:

Sorted(x)  =  head x ≤ every element of tail x  and  Sorted(tail x)

merge(x, y)  =  head x ≤ head y  ?  head x ∷ merge(tail x, y)
                                 :  head y ∷ merge(x, tail y)

A single comparison is merge running on two one-element runs. Sorting is the composition of merges and nothing else, beginning from the elements as runs of length one.

Theorem 9.7 (every + is a merge). Writing n as a sum is choosing the merges. Each + is one merge of two runs and costs the sum it produces, so the cost of sorting is the sum of the intermediate sums — equivalently, each element pays once for every + above it.

(1+1)+(1+1)        2, 2, 4              cost  8  =  n log₂ n
1+(1+(1+1))        2, 3, 4              cost  9
n = 8, balanced    2,2,2,2, 4,4, 8      cost 24  =  n log₂ n
n = 8, chained     2,3,4,5,6,7,8        cost 35

Proof. A merge of runs of lengths a and b emits a + b elements, and under a rule set emitting one constructor per step (5.21) that is a + b steps: the sum it produces. Summing over the + signs counts each element once for each + standing above it, which is its depth. ∎

This counts steps, one per element emitted. The comparisons are fewer — a merge of a and b makes at most a + b − 1, since the last run empties without one — and they are bounded separately, below.

the checked term
open import Cubical.Foundations.Prelude
open import Cubical.Data.Nat
open import Cubical.Tactics.NatSolver

-- A merge order is a way of writing n as a sum: every ⊕ is one merge.
data Shape : Type where
  one : Shape
  _⊕_ : Shape → Shape → Shape

size : Shape → ℕ
size one     = 1
size (l ⊕ r) = size l + size r

-- Each merge costs the sum it produces: the total is the sum of the
-- intermediate sums.
cost : Shape → ℕ
cost one     = 0
cost (l ⊕ r) = (size l + size r) + (cost l + cost r)

-- The same number again: each element pays once for every ⊕ above it.
paid : ℕ → Shape → ℕ
paid d one     = d
paid d (l ⊕ r) = paid (suc d) l + paid (suc d) r

paid≡ : (t : Shape) (d : ℕ) → paid d t ≡ cost t + d · size t
paid≡ one d = solveℕ!
paid≡ (l ⊕ r) d =
    cong₂ _+_ (paid≡ l (suc d)) (paid≡ r (suc d))
  ∙ step (cost l) (size l) (cost r) (size r) d
  where
    step : (cl sl cr sr d : ℕ)
         → (cl + (suc d · sl)) + (cr + (suc d · sr))
         ≡ ((sl + sr) + (cl + cr)) + d · (sl + sr)
    step cl sl cr sr d = solveℕ!

-- The sum of the intermediate sums IS the sum over elements of their depth.
cost≡depth : (t : Shape) → cost t ≡ paid 0 t
cost≡depth t = sym (paid≡ t 0 ∙ zero· (cost t) (size t))
  where
    zero· : (c s : ℕ) → c + 0 · s ≡ c
    zero· c s = solveℕ!

-- The balanced sum at every size: cost k · 2ᵏ, which is n log₂ n with the log removed.
bal : ℕ → Shape
bal zero    = one
bal (suc k) = bal k ⊕ bal k

size-bal : (k : ℕ) → size (bal k) ≡ 2 ^ k
size-bal zero    = refl
size-bal (suc k) = cong₂ _+_ (size-bal k) (size-bal k) ∙ double (2 ^ k)
  where
    double : (x : ℕ) → x + x ≡ 2 · x
    double x = solveℕ!

cost-bal : (k : ℕ) → cost (bal k) ≡ k · 2 ^ k
cost-bal zero    = refl
cost-bal (suc k) =
    cong₂ (λ s c → (s + s) + (c + c)) (size-bal k) (cost-bal k)
  ∙ step k (2 ^ k)
  where
    step : (k x : ℕ) → (x + x) + (k · x + k · x) ≡ suc k · (2 · x)
    step k x = solveℕ!

-- The chains, by refl.
chain4 chain8 : Shape
chain4 = one ⊕ (one ⊕ (one ⊕ one))
chain8 = one ⊕ (one ⊕ (one ⊕ (one ⊕ (one ⊕ (one ⊕ (one ⊕ one))))))

_ : cost chain4 ≡ 9
_ = refl
_ : cost chain8 ≡ 35
_ = refl

-- The interleavings of a run of a with a run of b: the first element of
-- the merge comes from one side or the other.
il : ℕ → ℕ → ℕ
il zero    b       = 1
il (suc a) zero    = 1
il (suc a) (suc b) = il a (suc b) + il (suc a) b

-- An ordering of the whole is the interleaving with an ordering of each run.
il-fact : (a b : ℕ) → il a b · ((a !) · (b !)) ≡ (a + b) !
il-fact zero    b       = left (b !)
  where
    left : (x : ℕ) → 1 · (1 · x) ≡ x
    left x = solveℕ!
il-fact (suc a) zero    = right (suc a !) ∙ cong _! (sym (+-zero (suc a)))
  where
    right : (x : ℕ) → 1 · (x · 1) ≡ x
    right x = solveℕ!
il-fact (suc a) (suc b) =
    split (il a (suc b)) (il (suc a) b) (a !) (b !) a b
  ∙ cong₂ (λ x y → suc a · x + suc b · y)
      (il-fact a (suc b))
      (il-fact (suc a) b ∙ cong _! (sym (+-suc a b)))
  ∙ close a b ((a + suc b) !)
  where
    split : (X Y A B a b : ℕ)
          → (X + Y) · ((suc a · A) · (suc b · B))
          ≡ suc a · (X · (A · (suc b · B))) + suc b · (Y · ((suc a · A) · B))
    split X Y A B a b = solveℕ!
    close : (a b K : ℕ) → suc a · K + suc b · K ≡ suc (a + suc b) · K
    close a b K = solveℕ!

-- What every merge settles, multiplied over the sum: n! whatever the shape.
info : Shape → ℕ
info one     = 1
info (l ⊕ r) = il (size l) (size r) · (info l · info r)

info≡ : (t : Shape) → info t ≡ size t !
info≡ one     = refl
info≡ (l ⊕ r) =
    cong₂ (λ x y → il (size l) (size r) · (x · y)) (info≡ l) (info≡ r)
  ∙ il-fact (size l) (size r)
The same number twice: cost sums what each merge produces, paid charges each element its depth, and cost≡depth identifies them. The balanced figures hold for every k by cost-bal, the chained ones by refl. The other axis on the same Shape: il counts the interleavings a merge settles, il-fact is that count times the orderings within each run giving the orderings of the whole, and info≡ multiplies it over any sum to n! — 9.8, whatever the shape. Verbatim, typechecks under Agda 2.8.0 --safe.

Theorem 9.8 (the information is fixed by the endpoints). A merge of runs of lengths a and b settles which of C(a+b, a) interleavings occurred, and along every way of writing n as a sum these binomials multiply to n! exactly.

Proof. An ordering of the whole is an ordering within each run together with the interleaving, so each merge contributes its binomial and the product telescopes to n! — info≡ in the box under 9.7. ∎

What is learned is fixed by where the sorting starts and ends, never by the shape — the pattern of equal length (5.13) on the other axis (5.7), reached here by a counting telescope rather than by the diamond. The shape decides only what each merge pays for what it settles: equal runs pay 2a for nearly 2a bits, a run against one element pays a+1 for log₂(a+1). That is the whole difference between the two sums of 9.7 — one quantity, distributed differently over the + signs.

Remark 9.9 (the shape of the obligation). Write Φ for log₂ of the orderings still consistent. It is zero exactly at the one that survives, but it is not a potential in the sense of Bellman (5.15), which asks Φ(u) ≤ 1 + Φ(v) on every edge: a comparison falling the unlikely way can drop it by much more, and with a < b, c < d the outcome b < c takes it from log₂ 6 to zero. What holds is the weaker, adversarial form — of a comparison’s two outcomes one leaves at least half, so one of them lowers Φ by at most one (9.3). That bounds the deepest route rather than every route, and the bound is log₂ n! comparisons, which some orderings beat. It is the shape 8.11 describes — obligations of which a step discharges at most one — at a scale that is not exponential, and it is met: merging equal runs makes at most n log₂ n − n + 1 comparisons for n = 2ᵏ, each of the n − 1 merges making one fewer than the sum it produces — for n = 4 that is 5 = ⌈log₂ 24⌉, the bound met exactly, and for n = 8 it is 17 against 16. The count it bounds is comparisons, not the steps of 9.7.

Corollary 9.10 (the two smallest). Minimising the sum of the intermediate sums over the ways of writing n as a sum is solved by repeatedly adding the two smallest parts — Huffman 1952 — which for n units gives the balanced sum. This answers 9.4 from the cost side rather than the information side: the cheapest merge available is the one between the two smallest runs, and two fresh elements are the smallest there are.

Theorem 9.11 (the shape is the numeral). The balanced sum is the binary representation of n, and the chain is the tally.

Proof. For n = 2ᵏ each element has a k-bit index, and the path from the root of the sum down to it spells that index: the first layer of merges joins indices differing in the last bit, the next those differing in the second-to-last. Resolving the ordering one layer at a time is resolving it one bit of the index at a time. For general n the runs are the 1-bits: 13 = 8 + 4 + 1. Counting is merging — add elements one at a time, keep runs matching the binary form of the count, and each carry merges two equal runs into one twice the size, which is 6.3's carrying read at its cost. The chain 1+(1+(1+⋯)) is the same number in tally marks: no carries, one growing run. ∎

The gap between the two costs is the gap between a tally and a numeral. Succession gives a line; place value gives a log₂ n-dimensional cube, which is what a base system has always been. A set indexed by the naturals already carries that structure, so there is no reason to prefer succession unless the input arrives as a line.

Proposition 9.12 (the same factorisation from the other end). Read downward, that product of binomials is a partition rather than a composition: at the top, which half of the set lies below and which above — C(n, n/2) ways — then the same within each half, down to single elements. Every element is sent toward its own index, as though searching for its own position one bit at a time. Merge splits by position and builds from the leaves; this splits by value and descends from the root. Splitting by value is partition by output (1.2), the output being where the element lands, so the two directions are that one partition taken at the two ends of the same factorisation, and inverting the permutation exchanges them.

Proposition 9.13 (the space of orderings). Take the orderings as points, joining two when they differ by swapping neighbours in the sequence. For three elements the six close into a hexagon:

            abc
          /     \
       bac       acb
        |         |
       bca       cab
          \     /
            cba

The distance from an ordering to the sorted one is its number of out-of-order pairs, since each swap of an out-of-order neighbouring pair fixes exactly one. Every route that only fixes out-of-order pairs therefore has the same length whatever order the swaps are taken in — not by the diamond (5.11), which fails here, but by Bellman (5.15): the out-of-order count is a potential that every such swap meets with equality — the swap costs one and lowers the count by exactly one — and a potential met with equality on every edge of the reduction makes every route a geodesic. (A swap of an in-order pair raises the count instead; it is not a step of the reduction, and a route using one is longer.) Two swaps at disjoint positions do commute and their routes close a square, the diamond where it holds; three sharing an element close the hexagon above, where it does not — those two reconverge only after two further swaps on each side, not one — and both sides are still the same length. So the picture reaches 5.13’s conclusion through 5.15, and shows the diamond failing on the way. A comparison is a cut through this space, and one already implied is a cut that misses what remains.

Proposition 9.14 (comparisons and swaps). Comparisons count cuts and swaps count distance, and the counts differ: about log₂ n! comparisons are needed (9.9), while the swaps are the out-of-order pairs (9.13), of which there are at most the n(n−1)/2 pairs. One comparison can authorise several swaps, and that is the whole of the gap — the two axes (5.7), with both numbers in hand.

Proof. In the set there are no swaps at all — comparisons add knowledge and the order is learned, not moved; swaps belong to the sequence presentation. At a single pair the two coincide: one comparison, one swap, one edge of 9.13. Above that they part. Merging [a,b] with [c,d] and learning c < a gives c < b free from the a < b already held, so one comparison authorises both swaps. Every swap is backed by a comparison made or inherited, and in a sorting that wastes nothing most are inherited. ∎

Remark 9.15 (the declaration). Nothing above chooses a method. The declaration is Σ[ B ] (B is a rearrangement of A) × Sorted B, and by 9.2 the completion is forced, not searched for. Posing it with the identities available and normalising (5.27) is the sorting: merge is sortedness unfolded (9.6), the shape is the numeral rather than a policy (9.11), the information is fixed by the endpoints (9.8), the cost is the sum of the intermediate sums (9.7). The sums that cost more are not rival methods but the same number written another way (5.23). Sorting is where the choice of method looks least avoidable, and there is none to make: pose the declaration with the identities the object actually has, and what remains is to follow them. What is learned is fixed by where the sorting starts and ends (9.8); what it costs was fixed when the number was written as a sum (9.7); and the sum is part of what was posed, not something chosen along the way.

Every step above is elementary. The boxed terms are verbatim and typecheck under Agda 2.8.0 with --cubical --guardedness --safe --no-import-sorts against agda-cubical v0.9 (--guardedness because the library carries it, and it is infective) — no postulates, no holes, no classical axiom; the untruncated Σ forms keep each claim constructive, exhibiting the escaping witness as a value. A box sits at each computational core — the one fact (0.8), the partition (1.2), every reversible operation is a transport (3.2), the vanishing grading (3.5), Lawvere (4.2), Gödel (4.6–4.9), equal length (5.13), σ² = −1 (7.2), decide = verify (8.6), every + is a merge, and the information fixed (9.7–9.8) — and each, headed by its own import lines, compiles on its own against the library under those flags, so any one can be checked without the rest; what is cumulative is the argument between them, not their imports. Not a citation to be trusted; the thing itself, on the page.