import Problems.PVersusNP.Millennium import Problems.PVersusNP.ForMathlib.Computable import Problems.PVersusNP.ForMathlib.StateTransition import Mathlib.Tactic.DeriveFintype /-! # A length guard for certificate checkers Scan the two blocks of the canonical input and save the word. Using unary stacks, start at one and multiply by the left length once for each unit of the fixed exponent. Compare the result with the right length. On acceptance, restore the saved word and start the original verifier. On rejection, discard it and return false. The guard needs only finitely many labels and does not assume closure of polynomial time under composition. -/ namespace Millennium.Machines.CertificateBound open Computability Turing StateTransition noncomputable section set_option maxErrors 1 private inductive Aux | saved | base | temp | count | next | cert deriving DecidableEq, Fintype private inductive Phase (k : ℕ) | scan (right : Bool) | power (i : Fin (k + 1)) | mul (i : Fin (k + 1)) | copy (i : Fin (k + 1)) | putBack (i : Fin (k + 1)) | transfer (i : Fin (k + 1)) | clearBase | compare (ok : Bool) | drain (ok : Bool) | restore (ok : Bool) deriving Fintype private abbrev Alphabet (tm : FinTM2) : tm.K ⊕ Aux → Type := Sum.elim tm.Γ fun | .saved => tm.Γ tm.k₀ | _ => Unit private abbrev Register (tm : FinTM2) := Option (tm.Γ tm.k₀) × tm.σ private abbrev Stmt (tm : FinTM2) (k : ℕ) := TM2.Stmt (Alphabet tm) (Phase k ⊕ tm.Λ) (Register tm) private def liftStmt {tm : FinTM2} {k : ℕ} : tm.Stmt → Stmt tm k | .push j f q => .push (.inl j) (fun v => f v.2) (liftStmt q) | .peek j f q => .peek (.inl j) (fun v x => (v.1, f v.2 x)) (liftStmt q) | .pop j f q => .pop (.inl j) (fun v x => (v.1, f v.2 x)) (liftStmt q) | .load f q => .load (fun v => (v.1, f v.2)) (liftStmt q) | .branch f q r => .branch (fun v => f v.2) (liftStmt q) (liftStmt r) | .goto f => .goto (fun v => .inr (f v.2)) | .halt => .halt private def jump {tm : FinTM2} {k : ℕ} (label : Phase k ⊕ tm.Λ) : Stmt tm k := .load (fun _ => (none, tm.initialState)) (.goto fun _ => label) private def remember {tm : FinTM2} (_ : Register tm) (x : Option (tm.Γ tm.k₀)) : Register tm := (x, tm.initialState) private def mark {tm : FinTM2} (sep : tm.Γ tm.k₀) (_ : Register tm) (x : Option Unit) : Register tm := (x.map (fun _ => sep), tm.initialState) private def prev {k : ℕ} (i : Fin (k + 1)) : Fin (k + 1) := ⟨i.val - 1, by omega⟩ private def guard (tm : FinTM2) (sep : tm.Γ tm.k₀) (reject : tm.Γ tm.k₁) (k : ℕ) : Phase k → Stmt tm k := by classical exact fun | .scan right => .pop (.inl tm.k₀) remember (.branch (fun v => v.1.isSome) (.push (.inr .saved) (fun v => v.1.getD sep) (if right then .push (.inr .cert) (fun _ => ()) (jump (.inl (.scan true))) else .branch (fun v => decide (v.1 = some sep)) (.push (.inr .count) (fun _ => ()) (jump (.inl (.scan true)))) (.push (.inr .base) (fun _ => ()) (jump (.inl (.scan false)))))) (jump (.inl (.power ⟨k, by omega⟩)))) | .power i => if i.val = 0 then jump (.inl .clearBase) else jump (.inl (.mul i)) | .mul i => .pop (.inr .count) (mark sep) (.branch (fun v => v.1.isSome) (jump (.inl (.copy i))) (jump (.inl (.transfer i)))) | .copy i => .pop (.inr .base) (mark sep) (.branch (fun v => v.1.isSome) (.push (.inr .temp) (fun _ => ()) (.push (.inr .next) (fun _ => ()) (jump (.inl (.copy i))))) (jump (.inl (.putBack i)))) | .putBack i => .pop (.inr .temp) (mark sep) (.branch (fun v => v.1.isSome) (.push (.inr .base) (fun _ => ()) (jump (.inl (.putBack i)))) (jump (.inl (.mul i)))) | .transfer i => .pop (.inr .next) (mark sep) (.branch (fun v => v.1.isSome) (.push (.inr .count) (fun _ => ()) (jump (.inl (.transfer i)))) (jump (.inl (.power (prev i))))) | .clearBase => .pop (.inr .base) (mark sep) (.branch (fun v => v.1.isSome) (jump (.inl .clearBase)) (jump (.inl (.compare true)))) | .compare ok => .pop (.inr .cert) (mark sep) (.branch (fun v => v.1.isSome) (.pop (.inr .count) (mark sep) (.branch (fun v => v.1.isSome) (jump (.inl (.compare ok))) (jump (.inl (.compare false))))) (jump (.inl (.drain ok)))) | .drain ok => .pop (.inr .count) (mark sep) (.branch (fun v => v.1.isSome) (jump (.inl (.drain ok))) (jump (.inl (.restore ok)))) | .restore ok => .pop (.inr .saved) remember (.branch (fun v => v.1.isSome) (if ok then .push (.inl tm.k₀) (fun v => v.1.getD sep) (jump (.inl (.restore true))) else jump (.inl (.restore false))) (if ok then jump (.inr tm.main) else .push (.inl tm.k₁) (fun _ => reject) (.load (fun _ => (none, tm.initialState)) .halt))) private abbrev guarded (tm : FinTM2) (sep : tm.Γ tm.k₀) (reject : tm.Γ tm.k₁) (k : ℕ) : FinTM2 where K := tm.K ⊕ Aux kFin := by letI := tm.kFin; infer_instance k₀ := .inl tm.k₀ k₁ := .inl tm.k₁ Γ := Alphabet tm Λ := Phase k ⊕ tm.Λ ΛFin := by letI := tm.ΛFin; infer_instance main := .inl (.scan false) σ := Register tm σFin := by letI := tm.Γk₀Fin; letI := tm.σFin; infer_instance initialState := (none, tm.initialState) Γk₀Fin := tm.Γk₀Fin m := Sum.elim (guard tm sep reject k) (fun label => liftStmt (tm.m label)) private def liftStacks {tm : FinTM2} (st : ∀ j, List (tm.Γ j)) : ∀ j, List (Alphabet tm j) | .inl j => st j | .inr _ => [] private def liftCfg {tm : FinTM2} {k : ℕ} (c : tm.Cfg) : TM2.Cfg (Alphabet tm) (Phase k ⊕ tm.Λ) (Register tm) := ⟨c.l.map Sum.inr, (none, c.var), liftStacks c.stk⟩ private theorem liftStacks_update {tm : FinTM2} (st : ∀ j, List (tm.Γ j)) (j : tm.K) (xs : List (tm.Γ j)) : Function.update (liftStacks st) (.inl j) xs = liftStacks (Function.update st j xs) := by funext h cases h with | inl h => by_cases eq : h = j · subst h; simp [liftStacks] · have different : (Sum.inl h : tm.K ⊕ Aux) ≠ .inl j := fun e => eq (Sum.inl.inj e) simp [liftStacks, Function.update_of_ne different, Function.update_of_ne eq] | inr h => simp [liftStacks, Function.update_of_ne] private theorem liftStmt_correct {tm : FinTM2} {k : ℕ} (p : tm.Stmt) (v : tm.σ) (st : ∀ j, List (tm.Γ j)) : TM2.stepAux (liftStmt (k := k) p) (none, v) (liftStacks st) = liftCfg (TM2.stepAux p v st) := by induction p generalizing v st with | push j f q ih => change TM2.stepAux (liftStmt q) (none, v) (Function.update (liftStacks st) (.inl j) (f v :: st j)) = _ rw [liftStacks_update] exact ih v _ | pop j f q ih => change TM2.stepAux (liftStmt q) (none, f v (st j).head?) (Function.update (liftStacks st) (.inl j) (st j).tail) = _ rw [liftStacks_update] exact ih _ _ | peek j f q ih => exact ih _ _ | load f q ih => exact ih _ _ | branch f q r ih ir => cases hf : f v <;> simp only [liftStmt, TM2.stepAux, hf, cond_false, cond_true, ih, ir] | goto f => rfl | halt => rfl private theorem liftStep {tm : FinTM2} {sep : tm.Γ tm.k₀} {reject : tm.Γ tm.k₁} {k : ℕ} (c : tm.Cfg) : (guarded tm sep reject k).step (liftCfg c) = (tm.step c).map liftCfg := by rcases c with ⟨l, v, st⟩ cases l with | none => rfl | some label => exact congrArg some (liftStmt_correct (tm.m label) v st) private def liftRun {tm : FinTM2} {sep : tm.Γ tm.k₀} {reject : tm.Γ tm.k₁} {k : ℕ} {a b : tm.Cfg} (run : EvalsTo tm.step a (some b)) : EvalsTo (guarded tm sep reject k).step (liftCfg a) (some (liftCfg b)) := by let send : Option tm.Cfg → Option (guarded tm sep reject k).Cfg := Option.map liftCfg have commutes : Function.Semiconj send (flip bind tm.step) (flip bind (guarded tm sep reject k).step) := by intro o cases o with | none => rfl | some c => exact (liftStep c).symm refine ⟨run.steps, ?_⟩ exact ((commutes.iterate_right run.steps) (some a)).symm.trans (congrArg send run.evals_in_steps) private structure Work (A : Type) where input : List A := [] saved : List A := [] base : ℕ := 0 temp : ℕ := 0 count : ℕ := 0 next : ℕ := 0 cert : ℕ := 0 private def checkpoint {tm : FinTM2} {k : ℕ} (p : Phase k) (w : Work (tm.Γ tm.k₀)) : TM2.Cfg (Alphabet tm) (Phase k ⊕ tm.Λ) (Register tm) where l := some (.inl p) var := (none, tm.initialState) stk | .inl j => (initList tm w.input).stk j | .inr .saved => w.saved | .inr .base => List.replicate w.base () | .inr .temp => List.replicate w.temp () | .inr .count => List.replicate w.count () | .inr .next => List.replicate w.next () | .inr .cert => List.replicate w.cert () variable {tm : FinTM2} {sep : tm.Γ tm.k₀} {reject : tm.Γ tm.k₁} {k : ℕ} private abbrev Run (tm : FinTM2) (sep : tm.Γ tm.k₀) (reject : tm.Γ tm.k₁) (k : ℕ) (a b : (guarded tm sep reject k).Cfg) := EvalsTo (guarded tm sep reject k).step a (some b) private def beginStep {a b c : (guarded tm sep reject k).Cfg} (step : (guarded tm sep reject k).step a = some b) (rest : Run tm sep reject k b c) : Run tm sep reject k a c := EvalsTo.trans _ _ _ _ (EvalsToInTime.of_step step).toEvalsTo rest private def oneStep {a b : (guarded tm sep reject k).Cfg} (step : (guarded tm sep reject k).step a = some b) : Run tm sep reject k a b := (EvalsToInTime.of_step step).toEvalsTo macro "certificate_step" : tactic => do let machine := Lean.mkIdent `tm `(tactic| (simp [FinTM2.step, TM2.step, TM2.stepAux, guarded, guard, jump, mark, remember, checkpoint, liftCfg, liftStacks, List.replicate_succ, *] try (congr <;> first | rfl | (funext s; cases s with | inl j => by_cases hj : j = ($machine).k₀ <;> by_cases ho : j = ($machine).k₁ <;> simp_all [initList, haltList, Function.update_of_ne] | inr j => cases j <;> simp_all [Function.update_of_ne]) | (simp_all; done)))) private def scanRight (ys saved : List (tm.Γ tm.k₀)) (base cert : ℕ) : Run tm sep reject k (checkpoint (.scan true) { input := ys, saved := saved, base := base, count := 1, cert := cert }) (checkpoint (.power ⟨k, by omega⟩) { saved := ys.reverse ++ saved, base := base, count := 1, cert := cert + ys.length }) := by induction ys generalizing saved cert with | nil => apply oneStep; certificate_step | cons y ys ih => refine beginStep ?_ (by simpa [List.reverse_cons, List.append_assoc, Nat.add_assoc, Nat.add_comm 1] using ih (y :: saved) (cert + 1)) certificate_step private def scanLeft (xs ys saved : List (tm.Γ tm.k₀)) (base : ℕ) (noSep : ∀ x ∈ xs, x ≠ sep) : Run tm sep reject k (checkpoint (.scan false) { input := xs ++ sep :: ys, saved := saved, base := base }) (checkpoint (.scan true) { input := ys, saved := sep :: (xs.reverse ++ saved), base := base + xs.length, count := 1 }) := by induction xs generalizing saved base with | nil => apply oneStep; certificate_step | cons x xs ih => have hx : x ≠ sep := noSep x (by simp) refine beginStep ?_ (by simpa [List.reverse_cons, List.append_assoc, Nat.add_assoc, Nat.add_comm 1] using ih (x :: saved) (base + 1) (fun z hz => noSep z (by simp [hz]))) certificate_step private def copyRun (i : Fin (k + 1)) (n : ℕ) (w : Work (tm.Γ tm.k₀)) : Run tm sep reject k (checkpoint (.copy i) { w with base := n }) (checkpoint (.putBack i) { w with base := 0, temp := w.temp + n, next := w.next + n }) := by induction n generalizing w with | zero => apply oneStep; certificate_step | succ n ih => refine beginStep ?_ (by simpa [Nat.add_assoc, Nat.add_comm 1] using ih { w with temp := w.temp + 1, next := w.next + 1 }) certificate_step private def putBackRun (i : Fin (k + 1)) (n : ℕ) (w : Work (tm.Γ tm.k₀)) : Run tm sep reject k (checkpoint (.putBack i) { w with temp := n }) (checkpoint (.mul i) { w with base := w.base + n, temp := 0 }) := by induction n generalizing w with | zero => apply oneStep; certificate_step | succ n ih => refine beginStep ?_ (by simpa [Nat.add_assoc, Nat.add_comm 1] using ih { w with base := w.base + 1 }) certificate_step private def mulRun (i : Fin (k + 1)) (n : ℕ) (w : Work (tm.Γ tm.k₀)) : Run tm sep reject k (checkpoint (.mul i) { w with count := n, temp := 0 }) (checkpoint (.transfer i) { w with count := 0, temp := 0, next := w.next + n * w.base }) := by induction n generalizing w with | zero => apply oneStep; certificate_step | succ n ih => have copied := copyRun (sep := sep) (reject := reject) i w.base { w with count := n, temp := 0 } have returned := putBackRun (sep := sep) (reject := reject) i w.base { w with base := 0, count := n, next := w.next + w.base } simp only [Nat.zero_add] at copied returned have remaining := ih { w with next := w.next + w.base } have rest := EvalsTo.trans _ _ _ _ copied (EvalsTo.trans _ _ _ _ returned remaining) refine beginStep ?_ (by simpa [Nat.succ_mul, Nat.add_assoc, Nat.add_left_comm, Nat.add_comm] using rest) certificate_step private def transferRun (i : Fin (k + 1)) (n : ℕ) (w : Work (tm.Γ tm.k₀)) : Run tm sep reject k (checkpoint (.transfer i) { w with next := n }) (checkpoint (.power (prev i)) { w with next := 0, count := w.count + n }) := by induction n generalizing w with | zero => apply oneStep; certificate_step | succ n ih => refine beginStep ?_ (by simpa [Nat.add_assoc, Nat.add_comm 1] using ih { w with count := w.count + 1 }) certificate_step private def powerRun (n : ℕ) (i : Fin (k + 1)) (hi : i.val = n) (w : Work (tm.Γ tm.k₀)) : Run tm sep reject k (checkpoint (.power i) { w with temp := 0, next := 0 }) (checkpoint .clearBase { w with temp := 0, next := 0, count := w.count * w.base ^ n }) := by induction n generalizing i w with | zero => apply oneStep; certificate_step | succ n ih => have hn : i.val ≠ 0 := by omega have hp : (prev i).val = n := by simp [prev, hi] have multiplied := mulRun (sep := sep) (reject := reject) i w.count { w with next := 0 } have transferred := transferRun (sep := sep) (reject := reject) i (w.count * w.base) { w with count := 0, temp := 0 } simp only [Nat.zero_add] at multiplied transferred have remaining := ih (prev i) hp { w with count := w.count * w.base } have rest := EvalsTo.trans _ _ _ _ multiplied (EvalsTo.trans _ _ _ _ transferred remaining) refine beginStep ?_ (by simpa [pow_succ', Nat.mul_assoc] using rest) certificate_step private def clearBaseRun (n : ℕ) (w : Work (tm.Γ tm.k₀)) : Run tm sep reject k (checkpoint .clearBase { w with base := n }) (checkpoint (.compare true) { w with base := 0 }) := by induction n with | zero => apply oneStep; certificate_step | succ n ih => exact beginStep (by certificate_step) ih private def drainRun (ok : Bool) (n : ℕ) (w : Work (tm.Γ tm.k₀)) : Run tm sep reject k (checkpoint (.drain ok) { w with count := n }) (checkpoint (.restore ok) { w with count := 0 }) := by induction n with | zero => apply oneStep; certificate_step | succ n ih => exact beginStep (by certificate_step) ih private def compareRun (m n : ℕ) (ok : Bool) (w : Work (tm.Γ tm.k₀)) : Run tm sep reject k (checkpoint (.compare ok) { w with cert := m, count := n }) (checkpoint (.restore (ok && decide (m ≤ n))) { w with cert := 0, count := 0 }) := by induction m generalizing n ok with | zero => refine beginStep ?_ (by simpa using drainRun ok n { w with cert := 0 }) certificate_step | succ m ih => cases n with | zero => refine beginStep ?_ (by simpa using ih 0 false) certificate_step | succ n => refine beginStep ?_ (by simpa using ih n ok) certificate_step private def restoreRun (saved inp : List (tm.Γ tm.k₀)) : Run tm sep reject k (checkpoint (.restore true) { input := inp, saved := saved }) (liftCfg (initList tm (saved.reverse ++ inp))) := by induction saved generalizing inp with | nil => apply oneStep; certificate_step | cons a xs ih => refine beginStep ?_ (by simpa [List.reverse_cons, List.append_assoc] using ih (a :: inp)) certificate_step private def rejectRun (saved : List (tm.Γ tm.k₀)) : Run tm sep reject k (checkpoint (.restore false) { saved := saved }) (haltList (guarded tm sep reject k) [reject]) := by induction saved with | nil => apply oneStep; certificate_step | cons a xs ih => exact beginStep (by certificate_step) ih private theorem initial (inp : List (tm.Γ tm.k₀)) : initList (guarded tm sep reject k) inp = checkpoint (.scan false) { input := inp } := by simp only [initList, checkpoint, guarded] congr funext j cases j with | inl j => by_cases h : j = tm.k₀ <;> simp [h] | inr j => cases j <;> rfl private theorem final (out : List (tm.Γ tm.k₁)) : liftCfg (k := k) (haltList tm out) = haltList (guarded tm sep reject k) out := by simp only [liftCfg, haltList, guarded, Option.map_none] congr funext j cases j with | inl j => by_cases h : j = tm.k₁ <;> simp [liftStacks, h] | inr j => rfl /-- The old verifier's answer on certificates meeting the length bound, and false otherwise. Length is measured on the left input's encoding and on the right word. -/ def check {α Γ : Type} (ea : FinEncoding α) (k : ℕ) (verifier : α × List Γ → Bool) (p : α × List Γ) : Bool := if p.2.length ≤ (ea.encode p.1).length ^ k then verifier p else false /-- Adding Cook's certificate length bound preserves computable checking. -/ def checked {α Γ : Type} [Fintype Γ] {ea : FinEncoding α} {verifier : α × List Γ → Bool} (h : TM2Computable (pair_encoding ea (fin_encoding_string Γ)).encode finEncodingBoolBool.encode verifier) (k : ℕ) : TM2Computable (pair_encoding ea (fin_encoding_string Γ)).encode finEncodingBoolBool.encode (check ea k verifier) where tm := guarded h.tm (h.inputAlphabet.symm (Sum.inr none)) (h.outputAlphabet.symm false) k inputAlphabet := h.inputAlphabet outputAlphabet := h.outputAlphabet outputsFun p := by let sep := h.inputAlphabet.symm (Sum.inr none) let reject := h.outputAlphabet.symm false let xs := (ea.encode p.1).map (fun a => h.inputAlphabet.symm (Sum.inl a)) let ys := p.2.map (fun b => h.inputAlphabet.symm (Sum.inr (some b))) have inputEq : List.map h.inputAlphabet.invFun ((pair_encoding ea (fin_encoding_string Γ)).encode p) = xs ++ sep :: ys := by rw [pair_encoding.encode_eq, List.map_append, List.map_cons, List.map_map, List.map_map] rfl have noSep : ∀ x ∈ xs, x ≠ sep := by intro x hx eq obtain ⟨a, _, rfl⟩ := List.mem_map.mp hx have bad := h.inputAlphabet.symm.injective eq cases bad have scan := EvalsTo.trans _ _ _ _ (scanLeft (reject := reject) (k := k) xs ys [] 0 noSep) (scanRight (sep := sep) (reject := reject) (k := k) ys (sep :: (xs.reverse ++ [])) (0 + xs.length) 0) let saved := ys.reverse ++ sep :: (xs.reverse ++ []) have hs : saved.reverse = xs ++ sep :: ys := by simp [saved, List.reverse_append, List.reverse_cons, List.append_assoc] let n := 0 + xs.length let m := 0 + ys.length let cap := 1 * n ^ k have powered := powerRun (sep := sep) (reject := reject) k ⟨k, by omega⟩ rfl { saved := saved, base := n, count := 1, cert := m } have cleared := clearBaseRun (sep := sep) (reject := reject) (k := k) n { saved := saved, count := cap, cert := m } have compared := compareRun (sep := sep) (reject := reject) (k := k) m cap true { saved := saved } have prefixRun := EvalsTo.trans _ _ _ _ scan (EvalsTo.trans _ _ _ _ powered (EvalsTo.trans _ _ _ _ cleared compared)) have lengths : (m ≤ cap) ↔ p.2.length ≤ (ea.encode p.1).length ^ k := by simp [xs, ys, m, cap, n] change Run h.tm sep reject k (initList (guarded h.tm sep reject k) (List.map h.inputAlphabet.invFun ((pair_encoding ea (fin_encoding_string Γ)).encode p))) (haltList (guarded h.tm sep reject k) (List.map h.outputAlphabet.invFun (finEncodingBoolBool.encode (check ea k verifier p)))) rw [inputEq, initial] by_cases bound : p.2.length ≤ (ea.encode p.1).length ^ k · have yes := lengths.mpr bound simp only [yes, decide_true, Bool.and_self] at prefixRun have original := h.outputsFun p rw [inputEq] at original have restored := restoreRun (sep := sep) (reject := reject) (k := k) saved [] rw [List.append_nil, hs] at restored rw [check, if_pos bound, ← final] exact EvalsTo.trans _ _ _ _ prefixRun (EvalsTo.trans _ _ _ _ restored (liftRun original)) · have no := lengths.not.mpr bound simp only [no, decide_false, Bool.and_false] at prefixRun rw [check, if_neg bound] exact EvalsTo.trans _ _ _ _ prefixRun (rejectRun saved) end end Millennium.Machines.CertificateBound