← Back to Research

· Formal Mathematics · orionlabs/deus · Lean 4

Deus on P vs NP

From bare Turing machines to an unconditional 2k black-box counting lower bound, machine-checked end to end in Lean 4 with zero sorry placeholders and only import Std.

0 sorry gaps or
custom axioms
2k Proven lower bound
on exact counting queries
k + 1 Proven upper bound
on witness search
Std Pure Lean 4
from first principles

Machine-Checked Complexity Theory from Scratch

When we published the Orion Deus (27B) System Card, we noted that Deus was actively working on formalizing structural results around P vs NP in Lean. Today we are releasing the complete Lean 4 module it produced.

What makes this artifact extraordinary is not just the breadth of the mathematics, but the sheer engineering discipline of a 27-billion-parameter looped-transformer model writing a completely self-contained formalization from the ground up. With nothing more than import Std, Deus defines deterministic and nondeterministic Turing machines, formalizes InP, InNP, and PEqNP, constructs the Hamiltonian cycle polynomial, isolates exact obstructions between decision and counting, and proves a sharp, unconditional exponential separation between witness search and exact counting in the black-box existential query model.

Every single lemma compiles without a single sorry, without external Mathlib shortcuts, and without hand-waved steps. In formal mathematics, there is nowhere to hide: either the kernel accepts the proof term, or it rejects it.

What Deus Proved in Lean 4

1. Complexity Foundations (p_subset_np)

Defines a full single-tape machine model (Machine, Configuration, PolynomiallyBounded), proves deterministic simulation invariance (Machine.deterministic_run), and establishes InP language → InNP language.

2. Hamiltonian Polynomial & Clock Reduction

Constructs directed Hamiltonian cycles (cycleTails, hasCycle, cycleCount) and their multilinear integer polynomial hamiltonianPolynomial, proving hamiltonianPolynomial_on_bits and reducing ¬ PEqNP cleanly to BeatsEveryPolynomialClock.

3. Decision-to-Counting Obstructions

Proves decision_bit_does_not_determine_count and arithmetic_of_decision_cannot_equal_hamiltonian_on_bits, formally ruling out naive algebraic lifts from the Boolean decision bit to the exact cycle count polynomial.

4. Unconditional 2k Counting Lower Bound

Formalizes adaptive existential query trees (ExistsQueryTree) and proves exists_queries_for_exact_count, yielding both black_box_counting_of_cycle_certificates and exponential_exists_query_lower_bound (at least 2 ^ k queries).

The Sharp Separation: O(k) Search vs. 2k Counting

One of the cleanest structural highlights of Deus's formalization is the direct side-by-side contrast at the end of the file. Under the exact same existential subset-query oracle:

Exact Counting Requires Exponential Queries (exponential_exists_query_lower_bound)

Using an adversary argument over allAccepted vs. allExcept missing, Deus proves that any adaptive existential query tree computing the exact number of accepting k-bit witnesses must isolate every single candidate in a singleton query, forcing at least 2 ^ k queries (and at least (cycleTails n).length queries for Hamiltonian cycle certificates).

Finding a Witness Takes Linear Queries (searchWitness_spec)

Immediately afterward, Deus implements the self-reducible prefix-splitting algorithm searchWitness and proves it always finds a valid k-bit witness (or certifies none exists) in at most k + 1 queries.

Taken together, the module maps out a rock-solid, machine-verified foundation for studying why black-box existential access separates search from counting by an exponential factor, and why any resolution of P vs NP must break out of purely black-box certificate barriers.

Full Lean 4 Formalization

Below is the complete, unedited Lean 4 source file authored by orionlabs/deus under namespace PVersusNP.

PVersusNP.lean · Lean 4 (Std only)
import Std

namespace PVersusNP

abbrev Word := List Bool
abbrev Language := Word → Prop

def PolynomiallyBounded (f : Nat → Nat) : Prop :=
  ∃ coefficient exponent : Nat, ∀ n, f n ≤ coefficient * (n + 1) ^ exponent

inductive Move where
  | left | stay | right
  deriving Inhabited

abbrev Symbol := Fin 3

structure Configuration (states : Nat) where
  state : Fin states
  head : Int
  tape : Int → Symbol

structure Machine where
  states : Nat
  start : Fin states
  accept : Fin states
  reject : Fin states
  distinctHalts : accept ≠ reject
  transition : Fin states → Symbol → Bool → Fin states × Symbol × Move

def Machine.halted (m : Machine) (c : Configuration m.states) : Bool :=
  c.state == m.accept || c.state == m.reject

def Machine.initial (m : Machine) (input : Word) : Configuration m.states where
  state := m.start
  head := 0
  tape i :=
    if i < 0 then 0
    else
      match input[i.toNat]? with
      | none => 0
      | some false => 1
      | some true => 2

def Machine.step (m : Machine) (choice : Bool) (c : Configuration m.states) :
    Configuration m.states :=
  if m.halted c then c
  else
    let (state, symbol, move) := m.transition c.state (c.tape c.head) choice
    { state := state
      head := match move with
        | .left => c.head - 1
        | .stay => c.head
        | .right => c.head + 1
      tape := fun i => if i = c.head then symbol else c.tape i }

def Machine.run (m : Machine) (input : Word) (choices : Nat → Bool) :
    Nat → Configuration m.states
  | 0 => m.initial input
  | t + 1 => m.step (choices t) (m.run input choices t)

def InP (language : Language) : Prop :=
  ∃ (m : Machine) (time : Nat → Nat), PolynomiallyBounded time ∧
    ∀ input, let c := m.run input (fun _ => false) (time input.length)
             m.halted c = true ∧ (c.state = m.accept ↔ language input)

def InNP (language : Language) : Prop :=
  ∃ (m : Machine) (time : Nat → Nat), PolynomiallyBounded time ∧
    ∀ input, (∀ choices, m.halted (m.run input choices (time input.length)) = true) ∧
      ((∃ choices, (m.run input choices (time input.length)).state = m.accept) ↔
        language input)

def PEqNP : Prop := ∀ language, InP language ↔ InNP language

def Machine.deterministic (m : Machine) : Machine :=
  { m with transition := fun state symbol _ => m.transition state symbol false }

theorem Machine.deterministic_run (m : Machine) (input : Word) (choices : Nat → Bool)
    (t : Nat) : m.deterministic.run input choices t = m.run input (fun _ => false) t := by
  induction t with
  | zero => rfl
  | succ t ih =>
    change m.deterministic.step (choices t) (m.deterministic.run input choices t) =
      m.step false (m.run input (fun _ => false) t)
    rw [ih]
    rfl

theorem p_subset_np {language : Language} (h : InP language) : InNP language := by
  obtain ⟨m, time, bound, correct⟩ := h
  refine ⟨m.deterministic, time, bound, fun input => ⟨?_, ?_⟩⟩
  · intro choices
    rw [m.deterministic_run]
    exact (correct input).1
  · constructor
    · rintro ⟨choices, accepts⟩
      rw [m.deterministic_run] at accepts
      exact (correct input).2.mp accepts
    · intro yes
      refine ⟨fun _ => false, ?_⟩
      rw [m.deterministic_run]
      exact (correct input).2.mpr yes

def words {α : Type} (alphabet : List α) : Nat → List (List α)
  | 0 => [[]]
  | k + 1 => alphabet.flatMap fun a => (words alphabet k).map (List.cons a)

theorem mem_words {α : Type} (alphabet : List α) (k : Nat) (w : List α) :
    w ∈ words alphabet k ↔ w.length = k ∧ ∀ a ∈ w, a ∈ alphabet := by
  induction k generalizing w with
  | zero => cases w <;> simp [words]
  | succ k ih =>
    cases w with
    | nil => simp [words, List.mem_flatMap, List.mem_map]
    | cons a t =>
      simp only [words, List.mem_flatMap, List.mem_map, List.cons.injEq,
        List.length_cons, Nat.succ.injEq, List.mem_cons]
      constructor
      · rintro ⟨b, hb, s, hs, rfl, rfl⟩
        obtain ⟨hl, ha⟩ := (ih s).mp hs
        exact ⟨hl, fun x hx => hx.elim (fun e => e ▸ hb) (ha x)⟩
      · rintro ⟨hl, ha⟩
        exact ⟨a, ha a (Or.inl rfl), t,
          (ih t).mpr ⟨hl, fun x hx => ha x (Or.inr hx)⟩, rfl, rfl⟩

theorem words_nodup {α : Type} {alphabet : List α} (h : alphabet.Nodup) (k : Nat) :
    (words alphabet k).Nodup := by
  induction k with
  | zero => simp [words]
  | succ k ih =>
    unfold words
    apply List.pairwise_flatMap.mpr
    constructor
    · intro a _
      exact List.pairwise_map.mpr (ih.imp (by
        intro x y hxy e
        exact hxy (List.cons.inj e).2))
    · apply h.imp
      intro a b hab x hx y hy e
      obtain ⟨u, _, rfl⟩ := List.mem_map.mp hx
      obtain ⟨v, _, rfl⟩ := List.mem_map.mp hy
      exact hab (List.cons.inj e).1

abbrev Edge := Nat × Nat

def cycleTails (n : Nat) : List (List Nat) :=
  (words (List.range n) (n - 1)).filter fun tail => decide ((0 :: tail).Nodup)

theorem mem_cycleTails (n : Nat) (tail : List Nat) :
    tail ∈ cycleTails n ↔
      tail.length = n - 1 ∧ (∀ v ∈ tail, v < n) ∧ (0 :: tail).Nodup := by
  simp [cycleTails, mem_words, and_assoc]

theorem cycleTails_nodup (n : Nat) : (cycleTails n).Nodup :=
  List.Nodup.sublist List.filter_sublist (words_nodup List.nodup_range _)

def cycleEdges (current : Nat) : List Nat → List Edge
  | [] => [(current, 0)]
  | next :: tail => (current, next) :: cycleEdges next tail

def cyclePresent (graph : Edge → Bool) (tail : List Nat) : Bool :=
  (cycleEdges 0 tail).all graph

def hasCycle (n : Nat) (graph : Edge → Bool) : Bool :=
  if n = 0 then false else (cycleTails n).any (cyclePresent graph)

def cycleCount (n : Nat) (graph : Edge → Bool) : Nat :=
  if n = 0 then 0 else ((cycleTails n).filter (cyclePresent graph)).length

def monomial (weights : Edge → Int) : List Edge → Int
  | [] => 1
  | edge :: edges => weights edge * monomial weights edges

def hamiltonianPolynomial (n : Nat) (weights : Edge → Int) : Int :=
  if n = 0 then 0 else
    ((cycleTails n).map (fun tail => monomial weights (cycleEdges 0 tail))).sum

def bit (value : Bool) : Int := if value then 1 else 0

theorem monomial_on_bits (graph : Edge → Bool) (edges : List Edge) :
    monomial (bit ∘ graph) edges = bit (edges.all graph) := by
  induction edges with
  | nil => rfl
  | cons edge edges ih =>
    change bit (graph edge) * monomial (bit ∘ graph) edges =
      bit (graph edge && edges.all graph)
    rw [ih]
    cases graph edge <;> cases edges.all graph <;> decide

theorem sum_bits_eq_count {α : Type} (accept : α → Bool) (xs : List α) :
    (xs.map (bit ∘ accept)).sum = Int.ofNat (xs.filter accept).length := by
  induction xs with
  | nil => rfl
  | cons x xs ih =>
    simp only [List.map_cons, List.sum_cons, Function.comp_apply, ih]
    cases h : accept x <;> simp [bit, h, Int.ofNat_add, Int.add_comm]

theorem hamiltonianPolynomial_on_bits (n : Nat) (graph : Edge → Bool) :
    hamiltonianPolynomial n (bit ∘ graph) = Int.ofNat (cycleCount n graph) := by
  unfold hamiltonianPolynomial cycleCount
  split <;> rename_i h
  · rfl
  · simp only [monomial_on_bits, ← sum_bits_eq_count]
    rfl

theorem hasCycle_iff_count_positive (n : Nat) (graph : Edge → Bool) :
    hasCycle n graph = true ↔ 0 < cycleCount n graph := by
  unfold hasCycle cycleCount
  split
  · simp
  · rw [List.any_eq_true]
    rw [Nat.pos_iff_ne_zero, ne_eq, List.length_eq_zero_iff]
    constructor
    · rintro ⟨tail, ht, ha⟩ empty
      have hm := List.mem_filter.mpr ⟨ht, ha⟩
      rw [empty] at hm
      exact List.not_mem_nil hm
    · intro nonempty
      cases h : (cycleTails n).filter (cyclePresent graph) with
      | nil => exact False.elim (nonempty h)
      | cons x xs =>
        have hm : x ∈ (cycleTails n).filter (cyclePresent graph) := by simp [h]
        obtain ⟨hx, ha⟩ := List.mem_filter.mp hm
        exact ⟨x, hx, ha⟩

def ValidCycle (n : Nat) (graph : Edge → Bool) (tail : List Nat) : Prop :=
  0 < n ∧ tail.length = n - 1 ∧ (∀ v ∈ tail, v < n) ∧
    (0 :: tail).Nodup ∧ ∀ edge ∈ cycleEdges 0 tail, graph edge = true

theorem hasCycle_iff_validCycle (n : Nat) (graph : Edge → Bool) :
    hasCycle n graph = true ↔ ∃ tail, ValidCycle n graph tail := by
  unfold hasCycle
  split <;> rename_i hn
  · subst n
    simp [ValidCycle]
  · simp [List.any_eq_true, mem_cycleTails, cyclePresent, List.all_eq_true,
      ValidCycle, Nat.pos_iff_ne_zero, hn, and_assoc]

theorem cycleEdges_length (start : Nat) (tail : List Nat) :
    (cycleEdges start tail).length = tail.length + 1 := by
  induction tail generalizing start with
  | nil => rfl
  | cons next tail ih => simp [cycleEdges, ih, Nat.add_comm]

theorem ValidCycle.edge_count {n : Nat} {graph : Edge → Bool} {tail : List Nat}
    (valid : ValidCycle n graph tail) : (cycleEdges 0 tail).length = n := by
  rw [cycleEdges_length, valid.2.1]
  have := valid.1
  omega

def encodeGraph (n : Nat) (graph : Edge → Bool) : Word :=
  List.replicate n true ++ [false] ++
    (List.range n).flatMap (fun i => (List.range n).map (fun j => graph (i, j)))

def DecidesHamiltonian (language : Language) : Prop :=
  ∀ n graph, language (encodeGraph n graph) ↔ hasCycle n graph = true

def HamiltonianInNP : Prop :=
  ∃ language, InNP language ∧ DecidesHamiltonian language

def BeatsEveryPolynomialClock : Prop :=
  ∀ (m : Machine) (time : Nat → Nat), PolynomiallyBounded time →
    ∃ n graph,
      let input := encodeGraph n graph
      let final := m.run input (fun _ => false) (time input.length)
      m.halted final = false ∨
        ¬ (final.state = m.accept ↔ hasCycle n graph = true)

theorem p_ne_np_of_clock_counterexamples
    (membership : HamiltonianInNP)
    (lowerBound : BeatsEveryPolynomialClock) : ¬ PEqNP := by
  intro equality
  obtain ⟨language, inNP, agrees⟩ := membership
  obtain ⟨m, time, bounded, correct⟩ := (equality language).mpr inNP
  obtain ⟨n, graph, fails⟩ := lowerBound m time bounded
  have h := correct (encodeGraph n graph)
  rcases fails with halted | wrong
  · exact Bool.noConfusion (h.1.symm.trans halted)
  · exact wrong (h.2.trans (agrees n graph))

def oneCycleGraph (edge : Edge) : Bool :=
  edge == (0, 1) || edge == (1, 2) || edge == (2, 0)

def completeThreeGraph (_ : Edge) : Bool := true

theorem oneCycleGraph_decision : hasCycle 3 oneCycleGraph = true := by decide

theorem completeThreeGraph_decision : hasCycle 3 completeThreeGraph = true := by decide

theorem oneCycleGraph_count : cycleCount 3 oneCycleGraph = 1 := by decide

theorem completeThreeGraph_count : cycleCount 3 completeThreeGraph = 2 := by decide

theorem decision_bit_does_not_determine_count :
    ¬ ∃ recover : Nat → Bool → Nat,
      ∀ n graph, recover n (hasCycle n graph) = cycleCount n graph := by
  rintro ⟨recover, h⟩
  have one := h 3 oneCycleGraph
  have two := h 3 completeThreeGraph
  rw [oneCycleGraph_decision, oneCycleGraph_count] at one
  rw [completeThreeGraph_decision, completeThreeGraph_count] at two
  omega

theorem arithmetic_of_decision_cannot_equal_hamiltonian_on_bits :
    ¬ ∃ evaluate : (Edge → Int) → Int,
      (∀ graph, evaluate (bit ∘ graph) = bit (hasCycle 3 graph)) ∧
      (∀ weights, evaluate weights = hamiltonianPolynomial 3 weights) := by
  rintro ⟨evaluate, decision, exactEval⟩
  have h := decision completeThreeGraph
  rw [exactEval, hamiltonianPolynomial_on_bits, completeThreeGraph_count,
    completeThreeGraph_decision] at h
  contradiction

inductive ExistsQueryTree (α : Type) where
  | answer (count : Nat)
  | ask (subset : List α) (no yes : ExistsQueryTree α)

def ExistsQueryTree.run {α : Type} (accept : α → Bool) :
    ExistsQueryTree α → Nat
  | .answer count => count
  | .ask subset no yes =>
    if subset.any accept then yes.run accept else no.run accept

def ExistsQueryTree.trace {α : Type} (accept : α → Bool) :
    ExistsQueryTree α → List (List α)
  | .answer _ => []
  | .ask subset no yes =>
    subset :: (if subset.any accept then yes.trace accept else no.trace accept)

def allAccepted {α : Type} (_ : α) : Bool := true

def allExcept {α : Type} [DecidableEq α] (missing : α) (a : α) : Bool :=
  decide (a ≠ missing)

def singleCandidate {α : Type} [DecidableEq α] : List α → Option α
  | [] => none
  | a :: others => if others.all (fun b => decide (b = a)) then some a else none

theorem exists_query_changes_iff {α : Type} [DecidableEq α]
    (missing : α) (subset : List α) :
    subset.any allAccepted ≠ subset.any (allExcept missing) ↔
      singleCandidate subset = some missing := by
  cases subset with
  | nil => simp [singleCandidate]
  | cons a others =>
    constructor
    · intro different
      have hnone : (a :: others).any (allExcept missing) = false := by
        cases hv : (a :: others).any (allExcept missing)
        · rfl
        · exact False.elim (different (by simp [allAccepted, hv]))
      have heq : ∀ b ∈ a :: others, b = missing := by
        intro b hb
        apply Classical.byContradiction
        intro hn
        have htrue : (a :: others).any (allExcept missing) = true :=
          List.any_eq_true.mpr ⟨b, hb, by simpa [allExcept] using hn⟩
        simp [hnone] at htrue
      have ha := heq a (by simp)
      have ho : others.all (fun b => decide (b = a)) = true := by
        apply List.all_eq_true.mpr
        intro b hb
        simp [ha, heq b (by simp [hb])]
      simp only [singleCandidate, ho, if_true, Option.some.injEq]
      exact ha
    · intro hs heq
      have hall : others.all (fun b => decide (b = a)) = true := by
        cases h : others.all (fun b => decide (b = a)) <;>
          simp_all [singleCandidate]
      have ha : a = missing := by simpa [singleCandidate, hall] using hs
      have htrue : (a :: others).any (allExcept missing) = true := by
        simpa [allAccepted] using heq.symm
      obtain ⟨b, hb, hne⟩ := List.any_eq_true.mp htrue
      have hba : b = a := by
        rcases List.mem_cons.mp hb with rfl | hb
        · rfl
        · simpa using List.all_eq_true.mp hall b hb
      simp [allExcept, hba, ha] at hne

theorem ExistsQueryTree.same_run_of_no_singleton {α : Type} [DecidableEq α]
    (tree : ExistsQueryTree α) (missing : α)
    (absent : missing ∉ (tree.trace allAccepted).filterMap singleCandidate) :
    tree.run allAccepted = tree.run (allExcept missing) := by
  induction tree with
  | answer _ => rfl
  | ask subset no yes ihNo ihYes =>
    have same : subset.any allAccepted = subset.any (allExcept missing) := by
      apply Classical.byContradiction
      intro different
      apply absent
      apply List.mem_filterMap.mpr
      exact ⟨subset, by simp [ExistsQueryTree.trace],
        (exists_query_changes_iff missing subset).mp different⟩
    cases h : subset.any allAccepted
    · simp only [ExistsQueryTree.run, h, ← same, Bool.false_eq_true, if_false]
      apply ihNo
      intro hit
      obtain ⟨q, hq, singled⟩ := List.mem_filterMap.mp hit
      apply absent
      exact List.mem_filterMap.mpr ⟨q, by simp [ExistsQueryTree.trace, h, hq], singled⟩
    · simp only [ExistsQueryTree.run, h, ← same, if_true]
      apply ihYes
      intro hit
      obtain ⟨q, hq, singled⟩ := List.mem_filterMap.mp hit
      apply absent
      exact List.mem_filterMap.mpr ⟨q, by simp [ExistsQueryTree.trace, h, hq], singled⟩

theorem length_le_of_nodup_subset {α : Type} [DecidableEq α]
    (xs ys : List α) (unique : xs.Nodup) (included : ∀ a ∈ xs, a ∈ ys) :
    xs.length ≤ ys.length := by
  induction xs generalizing ys with
  | nil => simp
  | cons x xs ih =>
    obtain ⟨notMem, unique⟩ := List.nodup_cons.mp unique
    have hx : x ∈ ys := included x (by simp)
    have sub : ∀ a ∈ xs, a ∈ ys.erase x := by
      intro a ha
      have hne : a ≠ x := by
        intro e
        subst a
        exact notMem ha
      exact (List.mem_erase_of_ne hne).mpr (included a (by simp [ha]))
    have bound := ih (ys.erase x) unique sub
    rw [List.length_erase_of_mem hx] at bound
    have positive : 0 < ys.length := by
      cases ys with
      | nil => simp at hx
      | cons => simp
    simp only [List.length_cons]
    omega

theorem exists_queries_for_exact_count {α : Type} [DecidableEq α]
    (candidates : List α) (unique : candidates.Nodup) (tree : ExistsQueryTree α)
    (correct : ∀ accept, tree.run accept = (candidates.filter accept).length) :
    candidates.length ≤ (tree.trace allAccepted).length := by
  refine Nat.le_trans (length_le_of_nodup_subset candidates
    ((tree.trace allAccepted).filterMap singleCandidate) unique ?_)
    (List.length_filterMap_le _ _)
  intro missing member
  apply Classical.byContradiction
  intro absent
  have same := tree.same_run_of_no_singleton missing absent
  rw [correct, correct] at same
  have all : candidates.filter allAccepted = candidates :=
    List.filter_eq_self.mpr (by simp [allAccepted])
  rw [all] at same
  have strict : (candidates.filter (allExcept missing)).length < candidates.length :=
    List.length_filter_lt_length_iff_exists.mpr ⟨missing, member, by simp [allExcept]⟩
  omega

theorem black_box_counting_of_cycle_certificates {n : Nat} (tree : ExistsQueryTree (List Nat))
    (correctOnArbitraryVerifiers : ∀ accept,
      tree.run accept = ((cycleTails n).filter accept).length) :
    (cycleTails n).length ≤ (tree.trace allAccepted).length :=
  exists_queries_for_exact_count _ (cycleTails_nodup n) tree correctOnArbitraryVerifiers

theorem bit_words_length (k : Nat) : (words [false, true] k).length = 2 ^ k := by
  induction k with
  | zero => rfl
  | succ k ih =>
    simp [words, ih, Nat.pow_succ, Nat.mul_two]

theorem exponential_exists_query_lower_bound (k : Nat)
    (tree : ExistsQueryTree Word)
    (correct : ∀ accept, tree.run accept = ((words [false, true] k).filter accept).length) :
    2 ^ k ≤ (tree.trace allAccepted).length := by
  rw [← bit_words_length]
  exact exists_queries_for_exact_count _ (words_nodup (by decide) _) tree correct

def prefixQuery (accept : Word → Bool) (stem : Word) (remaining : Nat) : Bool :=
  (words [false, true] remaining).any (fun suffix => accept (stem ++ suffix))

theorem prefixQuery_succ (accept : Word → Bool) (stem : Word) (k : Nat) :
    prefixQuery accept stem (k + 1) =
      (prefixQuery accept (stem ++ [false]) k ||
       prefixQuery accept (stem ++ [true]) k) := by
  simp [prefixQuery, words, List.any_append, List.any_map, List.append_assoc, Function.comp_def]

def chooseWitness (accept : Word → Bool) : Nat → Word → Word × Nat
  | 0, stem => (stem, 0)
  | k + 1, stem =>
    let choice := !(prefixQuery accept (stem ++ [false]) k)
    let (answer, queries) := chooseWitness accept k (stem ++ [choice])
    (answer, queries + 1)

theorem chooseWitness_correct (accept : Word → Bool) (k : Nat) (stem : Word)
    (existsWitness : prefixQuery accept stem k = true) :
    let result := chooseWitness accept k stem
    (∃ suffix, suffix.length = k ∧ result.1 = stem ++ suffix ∧ accept result.1 = true)
      ∧ result.2 = k := by
  induction k generalizing stem with
  | zero =>
    refine ⟨⟨[], rfl, by simp [chooseWitness], ?_⟩, rfl⟩
    simpa [prefixQuery, words, chooseWitness] using existsWitness
  | succ k ih =>
    let choice := !(prefixQuery accept (stem ++ [false]) k)
    have next : prefixQuery accept (stem ++ [choice]) k = true := by
      rw [prefixQuery_succ] at existsWitness
      cases h : prefixQuery accept (stem ++ [false]) k
      · simpa [choice, h] using existsWitness
      · simp [choice, h]
    obtain ⟨⟨suffix, length, answer, accepted⟩, count⟩ :=
      ih (stem ++ [choice]) next
    change (∃ suffix, suffix.length = k + 1 ∧
      (chooseWitness accept k (stem ++ [choice])).1 = stem ++ suffix ∧
      accept (chooseWitness accept k (stem ++ [choice])).1 = true) ∧
      (chooseWitness accept k (stem ++ [choice])).2 + 1 = k + 1
    refine ⟨⟨choice :: suffix, by simp [length], ?_, accepted⟩, by rw [count]⟩
    rw [answer, List.append_assoc]
    rfl

def searchWitness (accept : Word → Bool) (k : Nat) : Option Word × Nat :=
  if prefixQuery accept [] k then
    let (answer, queries) := chooseWitness accept k []
    (some answer, queries + 1)
  else (none, 1)

theorem searchWitness_spec (accept : Word → Bool) (k : Nat) :
    let result := searchWitness accept k
    result.2 ≤ k + 1 ∧
      (match result.1 with
       | none => ∀ w, w.length = k → accept w = false
       | some w => w.length = k ∧ accept w = true) := by
  cases h : prefixQuery accept [] k
  · simp only [searchWitness, h, Bool.false_eq_true, if_false]
    refine ⟨by omega, ?_⟩
    intro w length
    cases yes : accept w
    · rfl
    · have mem : w ∈ words [false, true] k :=
        (mem_words _ _ _).mpr ⟨length, by intro a _; cases a <;> simp⟩
      have impossible : prefixQuery accept [] k = true :=
        List.any_eq_true.mpr ⟨w, mem, yes⟩
      simp [h] at impossible
  · obtain ⟨⟨suffix, length, answer, accepted⟩, queries⟩ :=
      chooseWitness_correct accept k [] h
    simp only [List.nil_append] at answer
    change (chooseWitness accept k []).1 = suffix at answer
    have size : (chooseWitness accept k []).1.length = k := by rw [answer, length]
    change accept (chooseWitness accept k []).1 = true at accepted
    simp [searchWitness, h, queries, size, accepted]

end PVersusNP