Maintained procedure · manual/workflows/deterministic-workflows.mdMarkdown source at d23f2aea9f24
On this page

Prove deterministic resource bounds

Use plain Turing.MultiTapeTM.ComputableInPolyTime for public polynomial-time claims. Its definition supplies a finite native machine with independently polynomially bounded time and workspace, measured against encoded input length. Build or destructure a certificate with ⟨t, s, ht, hs, h⟩. For a certificate hf, the field hf.exists_bounds gives the underlying existential. To rewrite a goal in those terms, use Turing.MultiTapeTM.computableInPolyTime_def. Each Lean block is a contextual excerpt from the current source, requiring its linked original file; these are not newly compiled standalone examples. The excerpts are by Samuel Schlesinger, under the source repository's Apache 2.0 license. cslib-frontier

Compose a certified function#

The automation reference explains registration and troubleshooting handles failures.

For binary sign-magnitude integers, import CslibFrontier.Computability.Machines.Turing.MultiTape.Complexity.PolyTime.Int.Binary. The plain ComputableInPolyTime.intBin_* rules (sign and magnitude, binary and unary natural casts, ring operations, comparisons, list sums and products, unary powers) compose through fun_prop; intBin_pow' accepts computed base and unary exponent certificates, and intBin_signMagnitude' assembles a computed sign and binary magnitude. The complete IntBinary client checks composed ring operations, products, powers, magnitudes and signs. A binary exponent has a different output-size obligation: do not replace the unary exponent encoding merely to make a goal match.

For rational numbers ℚ encoded as (q.num, q.den) under Turing.MultiTapeTM.encRat (Encodings/Rat.lean), import CslibFrontier.Computability.Machines.Turing.MultiTape.Complexity.PolyTime.Rat for ComputableInPolyTime.rat_num, rat_den, rat_intCast, rat_natCast, rat_divInt, rat_neg, rat_inv, rat_add, rat_sub, rat_mul, rat_div, rat_pow, rat_isZero, rat_eq, rat_lt, rat_le, rat_floor, and their primed fun_prop composition rules (PolyTimeRat client).

For a padded integer dot product, import PolyTime/Int/DotProduct.lean and use ComputableInPolyTime.listDotProduct. It certifies the existing pure public Mathlib.Tactic.Matrix.ListMatrix.dotProduct: the cutoff is unary, coefficients are signed binary, missing entries are zero, and entries beyond the cutoff are ignored. Runtime still charges both complete framed input lists. The operation lives in a Mathlib tactic-support file but is ordinary term-level arithmetic, not a meta program. The pure list identities and residue-matrix bridge require neither crypto nor native imports. The former local Lyubashevsky listDot duplicate has been removed; its verifier, extractor and signer use the same upstream operation. The checked clients cover padding, truncation, signed large coefficients and unchanged verifier outcomes and commitment bytes. This API consolidation adds no cryptographic security claim.

Keep a record's encoded tuple layout at its construction boundary. For example, NativePacket.PacketCtx.mk_polyTime composes certificates for named fields while preserving the existing encoded words; its packet-construction client does not reconstruct the product tree. The BranchEvalInput interface similarly supplies named parameter access and certificates with the original unary/binary choices. Use these boundaries when changing a client, and retain its encoded-length bounds.

For a computed optional value, import CslibFrontier.Computability.Machines.Turing.MultiTape.Complexity.PolyTime.Option. The shared ComputableInPolyTime.optionMapWithInput rule certifies fun x => (value x).map (f x) from certificates for value and the joint callback fun p => f p.1 p.2. The callback is charged against both the original input and the present value; input and output value encodings may differ. The public-import client checks a captured parameter and an encoding change. Boolean measurement search uses this rule for its optional-result codec, and hybrid CCA composition uses it to postprocess successful decapsulation while preserving rejection.

Walk two lists with a collecting fold#

Import CslibFrontier.Computability.Machines.Turing.MultiTape.Complexity.BigO.ZipFold and open Turing.MultiTapeTM. Apply ComputableInO.zipFold or ComputableInSpace.zipFold explicitly. The complete zipFold clients show padding, dropping and a time certificate; subtractSums_inSpace uses the space-only rule for register subtraction.

zipFold f p left right takes one step for every element of left, consuming one position of right even when f returns none and drops that output. After right is exhausted, the callback receives none; it chooses whether to pad or drop. Unused elements of a longer right are ignored, and retained outputs keep their order.

Supply one joint certificate for (p, a, b?) ↦ f p a b?, with the parameter, left element and optional right element encoded together. Both cost rules require Inhabited for the right-element type. They also require a bound on every encoded output prefix: the result of zipFold f p (left.take i) right for every i, not only the final list. Keep the parameter and element encodings explicit when applying the rule.

Let N be the length of the joint encoding of (p, left, right). A callback with linear time and charged space, and prefixes bounded by k * (N + 1) for one constant k, gives time O((left.length + 1) * (N + 1)) and linear charged space. The space-only rule needs a linear-space callback and a prefix bound B (p, left, right); it gives space O(N + B (p, left, right) + 1) and makes no time claim. Both space bounds include the encoded output. A callback certificate for each fixed parameter is insufficient: certify the joint function, and discharge the prefix bound separately.

Certify a loop and its postcondition#

Goal: a plain computation certificate together with a final invariant. Import CslibFrontier.Computability.Machines.Turing.MultiTape.Complexity.PolyTime.Iteration. The public import exposes ComputableInPolyTime.iterate_spec; its current implementation lives in the machine layer.

Supply three computation certificates: the iteration count in unary, the initial state, and the step. Then provide an invariant indexed by original input, iteration number and state. Prove initialization and preservation. Finally, bound the encoded state under that invariant at every index up to the count by a PolyBounded function of original input length. The mathematical bound itself need not be computable.

The result has two projections: polynomial-time computability of the iterated function, and the invariant at termination. Ladner’s shrink-loop client obtains hreduce and hinv this way: its invariant preserves satisfiability and bounds the current formula's encoded length. That use is inside the theorem's stated reduction and growth hypotheses, not an unconditional SAT algorithm.

The same separation applies to list folds: ComputableInPolyTime.foldlWith_spec accepts plain certificates for the input list, initial state and joint step, while a prefix invariant supplies the encoded accumulator bound. The denominator-product and Bareiss-column folds in RationalElimination.lean are representative callers: their numerical invariants justify the size bound directly, without converting the surrounding proof to tidy certificates. For a fold with a direct bound on each reachable prefix state, the binary square-root certificate uses foldlWith instead.

For a step capturing a parameter, use iterateWith_spec and certify the joint (parameter, state) operation. iterateWith_of_bounded_growth handles additive encoded-state growth bounded polynomially in the original input. A separate efficient procedure for each fixed parameter does not provide the required uniform joint certificate. A polynomial number of efficient steps also does not bound a state that doubles each time. The plain loop regression client exercises both positive contracts and a failed constant-state bound. When the size obligation fails, inspect the representation and growth argument before changing tactics.

At the machine layer, the sequential plumbing provides MultiTapeTM.relabel and TransformsTapes.relabel for changing control-state names along an equivalence. This retains each instruction and both resource bounds, including the visited cells; it adds no handoff step. Iterate-while preparation uses this to share clear/copy/clear preparation with the probabilistic round while retaining the deterministic round's nested sum of states. Use this bridge when only the state association differs, rather than rebuilding the tape certificates.

For a space bound on a loop whose number of rounds is not computable, or would cost too much to compute, import CslibFrontier.Computability.Machines.Turing.MultiTape.Complexity.InSpace.IterateUntil and apply ComputableInSpace.iterateUntil. Supply space certificates for the initial state, the step and a Boolean done test, and give the number of rounds n x as a function with no certificate. Show that done holds after n x rounds and fails before. Then bound the space of the step and the test, and the encoded state, at every round up to n x. The loop stops when the test first holds, and its space is that of the start, the rounds and the states, with no counter. ComputableInSpace.iterate instead charges a binary counter, and it needs a certificate for the count. The BitGame client counts down from n in n rounds within O(|encNat n|) space.

Build a course-of-values stage table#

Goal: build [val 0, …, val (n - 1)] or compute val n, where val i = step [val 0, …, val (i - 1)] reads all earlier values. Separate the stage definition from its complexity certificate by importing List.courseOfValues where step and List.courseOfValuesVal are defined (for instance in Ladner.Basic), then import CslibFrontier.Computability.Machines.Turing.MultiTape.Complexity.PolyTime.CourseOfValues (PolyTime.CourseOfValues) for the polynomial-time proof.

For framed-list tables (encList encElem), ComputableInPolyTime.courseOfValues, courseOfValuesVal, courseOfValuesWith and courseOfValuesWithInput require a PolyBounded or PolynomiallyBounded bound on (encElem (List.courseOfValuesVal … i)).length along reachable prefixes (i < count x or i < n), without re-proving length_encList_le or List.courseOfValues_eq_iterate. For raw Boolean stage tables (encBits), bitsCourseOfValues, bitsCourseOfValuesVal and bitsCourseOfValuesWith need no separate element bound because each stage appends one bit. A polynomial number of efficient steps still fails the framed-list bound if val i grows exponentially. The course-of-values regression client exercises pure prefix identities, positive framed-list and raw-bit certificates, and the failing exponential growth check; production clients include Ladner.PolyTime, UniformDiagonalization, Immune.Construction and Immune.RecursiveCore.

Derandomize an averaging argument#

Goal: turn an averaging proof that some choice of bits is good into a deterministic algorithm with the same quantitative guarantee, then certify its running time. Import CslibFrontier.Foundations.Combinatorics.PessimisticEstimator and open Cslib.PessimisticEstimator. Describe one round by a branch function branch : R → Bool → S → S and an estimate Φ : S → M of the final cost, for M such as ℕ or ℝ; greedy branch Φ rounds s takes, in each round, the branch with the smaller estimate, with ties going to true.

Apply greedy_spec with an invariant Inv : List R → S → Prop indexed by the rounds still to come. Prove that it passes along both branches and that, wherever it holds, the smaller branch estimate is at most the current estimate. For an averaging argument, use greedy_spec_of_add_le and prove instead that the two branch estimates sum to at most twice the current estimate. The estimate need not be an exact conditional expectation; a pessimistic upper bound suffices. The conclusion returns the invariant for the final state together with Φ final ≤ Φ initial; use the final invariant to identify the final estimate with the cost of the constructed object. For exact conditional expectations of a real function on the cube, BitString.expect_le_greedy_fixCoord in CslibFrontier.Foundations.BooleanAnalysis.GreedyFixing already does this.

Johnson.lean is the satisfiability client. Its state is the partially set formula and the variables set to true; its estimate is the weight Σ_c 2 ^ (L - |c|). It sets a variable with the resolution module's CNF.restrict. Its invariant records that the remaining variables are those still to be set and that the partial formula falsifies the same number of clauses as the original under any completion. Johnson/PolyTime.lean certifies the running time. Because L is read from the input formula, the rounds form a fold whose step reads the input, certified by foldlWithInput_of_bounded_growth. Its growth premise uses the fact that setting a variable does not lengthen the encoded formula. The complete JohnsonMaxSAT client checks a tight 7 / 8 instance and a formula with an empty clause, where the 1 / 2 bound fails without its hypothesis. Build it with scripts/build.sh CslibFrontierTests.JohnsonMaxSAT.

For a fold with a captured parameter and a known bound on reachable states, use ComputableInPolyTime.foldlWith from PolyTime/Fold.lean. Certify the step jointly on (parameter, accumulator, element) with encoding encPair (encPair encP encB) encA; separate certificates for each fixed parameter do not supply this uniform callback. Then bound the encoded accumulator after every consumed prefix. The size bound may depend on the original input and need only be polynomially bounded, not computable. In computableInPolyTime_naorYungCascade, the accumulator contains a state word and an unconsumed suffix. The state length is at most its initial length plus n + 1, and the suffix never grows. This handles arbitrary initial words, including ones longer than the final width; replacing the prefix bound by the final output length would miss those inputs. The compression and adversary certificates consume this plain fold certificate directly. Existing concrete clients are in Crypto/NaorYungUOWHF.lean; check them with scripts/build.sh CslibFrontierTests.Crypto.NaorYungUOWHF.

To package the Turing-machine transfer once across rounds, use PolyTimeGreedyInput in Computability/PolyTime/PessimisticEstimator.lean. computableInPolyTime_run, computableInPolyTime_run_nat and run_polyTime_spec discharge foldlWithInput_of_bounded_growth from polynomial-time rounds, init, branch (on encBranchInput), estimate, order comparison on estimator values M (hle, supplied automatically for binary ℕ by computableInPolyTime_run_nat), and an additive per-round encoded-state growth bound; PolyTimeChoiceGreedyInput (computableInPolyTime_run, run_spec, run_polyTime_spec) extends the same transfer to variable-length per-round candidate lists choices x r : List A (encChoiceInput). Weighted MaxCut instantiates the greedy construction in MaxCut/Derandomized.lean, PolyTimeGreedyInput in Problems/MaxCut/Derandomized.lean, and an explicit O(|V| |E| + |V|) word-RAM implementation (maxCutCode_spec, maxCutProgram_spec) in WordRAM/MaxCut.lean, proving the deterministic 1 / 2-approximation cutWeight_le_two_mul_derandomizedCutSide and computableInPolyTime_derandomizedCut; see FairBitRejectionAndCondExp.lean. For conditional expectations over general finite product distributions PMF.pi p, use PMF.condExpect in Product/ConditionalExpectation.lean together with the pure coordinate-fixing combinator ProductDerandomizer (derandomize_spec) in Algorithms/Lean/PessimisticEstimator.lean.

When the averaging argument uses only k-wise independence, you can search a small sample space instead of fixing bits one by one. For satisfiability, KWiseIndependent.lean takes a family h with IsKWiseIndependentHash k h and a labelling e of the variables that is injective on φ.vars. exists_two_pow_mul_countUnsat_le then gives a seed i with 2 ^ k * φ.countUnsat (h i ∘ e) ≤ φ.length whenever every clause has at least k distinct literals. ParitySearch.lean instantiates it for k ≤ 3 with the three-wise parity hash LinearHash.isKWiseIndependentHash_dotProduct_cons_true, labelling each variable by the binary digits of its position. paritySearch folds betterCandidate over the fewer than 4n candidate assignments, and ParitySearch/PolyTime.lean certifies the running time with foldlWithInput_of_bounded_growth. Every candidate is a sublist of the variable list, which bounds the fold's growth. The ParitySearchMaxSAT client evaluates the candidate lists. It also shows that the parity space is not four-wise independent and that the guarantee fails for clauses of four literals. Build it with scripts/build.sh CslibFrontierTests.ParitySearchMaxSAT.

When it fails: if the round inequality holds only on reachable states, strengthen the invariant rather than the estimate. Clauses with complementary literals, for example, make Johnson's weight strictly pessimistic, but the inequality still holds for every partial formula without repeated literals. If the fold's growth premise fails, check that the step does not enlarge the encoded state by more than a polynomial in the input.

Round, solve exactly and certify a pseudo-polynomial table#

Goal: an approximation scheme that rounds numbers, solves the rounded instance exactly by dynamic programming, and runs in polynomial time. Import CslibFrontier.Algorithms.Lean.Knapsack.PolyTime (it re-exports ProfitDP and FPTAS) and open Cslib.Algorithms.Lean.Knapsack Turing.MultiTapeTM ComputableInPolyTime.

First prove the exact program correct. Knapsack/ProfitDP.lean folds a table indexed by profit over the items. Its invariant TableSpec records the table length (total profit plus one), that each entry is a subsequence of the right profit, and that each entry weighs at most every subsequence of that profit. Prove the invariant for the initial table and for one step, then fold it (TableSpec.foldl). Then prove the rounding bound against the exact program on the rounded instance: Knapsack/FPTAS.lean rounds the values to at most n * k, and sub_one_mul_value_le_fptas gives (k - 1) * OPT ≤ k * value.

Then certify the running time, as Knapsack/PolyTime.lean does. Certify one step of the table jointly in the table and the item, and pass it to foldl'. Discharge the fold's states bound at every prefix (l.take i) from the invariant: the table has total-profit-plus-one entries, each a subsequence of the items. That bound is polynomial only when profits are charged in unary, so read them in encUnary. The FPTAS computes its rounded values in unary from k in unary, while weights and the capacity stay in binary. Knapsack/Unary.lean turns the exact program into Knapsack ∈ P for the unary-value encoding.

For a hardness-of-approximation statement in this style, state the algorithm as a function with a plain ComputableInPolyTime hypothesis, a validity hypothesis and a ratio hypothesis. Derive P = NP from a known NPComplete problem through NPComplete.P_eq_NP_of_mem_P, as PCP/Approximation/BinPacking.lean does from Partition and PCP/Approximation/KCenter.lean does from DominatingSet.

Check the clients with scripts/build.sh CslibFrontierTests.KnapsackFPTAS CslibFrontierTests.BinPackingApprox. The KnapsackFPTAS client checks an instance where the scheme is not optimal but meets its bound. The BinPackingApprox client shows that an exact, non-polynomial algorithm satisfies the hardness hypotheses other than running time, and that First Fit violates the ratio hypothesis.

For a ratio of a greedy packing that pairing cannot give, use a weighting function, as BinPacking/FirstFitWeight.lean does for First Fit's 17/10. Keep the weights in ℕ by scaling them by 10 * C, so each case of the piecewise weight closes with split_ifs <;> omega. Bound the weight of one bin (sum_map_firstFitWeight_le) and transfer it to a packing with IsPacking.sum_map_le_mul_length. Then lower-bound the algorithm's bins from the invariant of its rule: for First Fit, every item of a later bin overflows every earlier bin (pairwise_forall_lt_sum_add_firstFit), which is stronger than pairwise overfull bins. The result ten_mul_length_firstFit_le gives 10 * FF ≤ 17 * OPT + 8 against every packing, and length_firstFit_le_ceil gives FF ≤ ⌈17/10 * OPT⌉. The absolute bound FF ≤ ⌊17/10 * OPT⌋ of Dósa and Sgall is not formalized. The BinPackingFirstFitWeight client checks a bin attaining the weight bound and an instance with OPT = 9 where First Fit uses 15 bins; check it with scripts/build.sh CslibFrontierTests.BinPackingFirstFitWeight. If a case of the weight bounds does not close under omega, check the scaling and whether each breakpoint of the weight is open or closed as in the source; if the lower bound fails, check that it uses the algorithm's rule, not only pairwise overfull bins.

When it fails: if the foldl' states-bound premise fails, bound the encoded table through the invariant (its length and the subsequence property of every entry), not by the number of steps. Then check that the profits really are read in encUnary; with binary profits the table is exponential in the input and no bound exists. If fun_prop times out on max or on a map whose body mixes unary and binary arithmetic, build that certificate by hand. Use ite with the plain ComputableInPolyTime.binary_le' for max, and mapWithInput with ComputableInPolyTime.unary_to_binary, binary_mul' and ComputableInPolyTime.binary_div for the rounding map.

Preserve independent workspace#

This conclusion is different from ComputableInO, which additionally charges encoded output against its space bound. A long output is compatible with logarithmic workspace. For sharper independent bounds, state ComputableInTimeAndSpace or ComputableInBigO directly and retain both functions. When only polynomial time is needed downstream, use ComputableInLogSpace.computableInPolyTime; the same client demonstrates that transition. See the resource table.

The plain word-transducer facade registers ComputableInTimeAndSpace for fun_prop directly, without a mixed streaming import. It provides ComputableInTimeAndSpace.map_bits, length_bits, dropLast_bits, getLast?_toList_bits and getLast?_bits with time 4 * l.length + 8 and zero workspace. reverse_bits keeps time 2 * l.length + 2 and zero workspace. These reuse the existing machines; the transducer witness includes input rewind. Workspace excludes emitted output: map and reverse therefore need a separate linear output bound for output-charged space, while last-bit extraction has constant output size. The plain-import regression exercises automation and the obstruction to charging arbitrary map output to constant space.

Turn computation into P, NP and hardness#

PolyTimeReducible.mem_P instead transports a target's P algorithm backward to the source. Use the reduction reference when the desired reduction is stronger than polynomial-time many-one reducibility.