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

Choose a model and state its contract

Start with the claim you need: a function runs in polynomial time, a transducer uses logarithmic workspace, a circuit has bounded depth, or a stateful client makes few operations. These conclusions use different currencies. Select the predicate before implementing the algorithm. The complete model map and resource conventions supply the reference details. cslib-frontier

Choose an entry point#

Module names in this table follow CslibFrontier.; open the linked client for its complete imports and namespace context.

TaskModel and entry importExisting clientResource claim and next bridge
Certify an ordinary functionNative multitape machine; Tactic.PolyTimePolyTimePlainDriverComputableInPolyTime; compose certificates relative to explicit encodings.
Produce a long answer using little workspaceNative transducer; Computability.Machines.Turing.MultiTape.Complexity.LogSpace.WordsLogSpaceWordsComputableInLogSpace; composition replays intermediate output.
Count bounded-word instructionsWord-RAM; Computability.WordRAM.TuringWordRAMTuringInstruction count at a width and basis; supply fitting inputs, an efficient width schedule and native operation certificates to reach Turing polynomial time.
Specify and amortize a data structureStateTransitionSpec; DataStructure.StateTransition.RefinementStateTransitionRefinementBackend-operation charge; a native realization must also implement and charge the client's control computation.
Build a uniformly generated circuit familyCircuit; Computability.Complexity.Problems.CircuitValue.CompilationUniformCircuitsCircuit correctness and a polynomial-time code constructor; inspect size/depth separately when those are the target bounds.
Evaluate an ordered finite-model queryFO(LFP); Computability.Complexity.Classes.P.FirstOrderFOLeastFixedPointPolyTimeNative model-checking over encoded structures; distinguish executable raw syntax from well-formed positive formulas used for least-fixed-point semantics.
Reason about random choices or oracle callsProbComp / OracleComp; Languages.Probabilistic.SimulationProgramsInterpretation proves a distributional law; follow the probabilistic workflow for native efficiency and oracle charges.

Adapt the client's contract to your types. A failed bridge usually means a missing implementation, encoding or resource hypothesis.

Write the contract before the proof#

Record the input and output types; their encodings; the measured input size; the time, workspace, gate or query bound; and what is fixed before the input varies. Model domain objects, problem instances, certificates, configurations, and multi-field algorithm states or contexts as documented structures with named fields rather than tuple abbrevs or bare product sets (Set (A × B × C)), keeping plain Prod (×) for generic binary combinators and uncurried multi-argument inputs such as Instance × List Bool → Bool. For native computation, an encoding has type α ↪ List Bool: injectivity is part of the data. Reuse encBits, encBool, binary encNat, unary encUnary, encPair and encList before defining another representation. Encode a dependent pair Σ i, β i with encSigma encI enc, the framed index followed by the second component under the encoding enc i that the index selects; when that family is uniform, enc i = e ∘ code i, ComputableInPolyTime.sigmaView reads the value as the plain pair (i, code i b) under encPair encI e (dependent pairs). A new embedding needs an injectivity proof and size lemmas suitable for the intended bound. Encoding length lemmas and pair lengths show where framing overhead enters. To read a component back out of an encPair word in a proof, rewrite with unframe_encPair and dropFrame_encPair, or with their encBits forms unframe_encPair_encBits and dropFrame_encPair_encBits (pair projections), rather than proving the step inline.

For fixed finite tables, the plain ComputableInPolyTime.ofFn, .pi, .pi_apply and .pi_update certificates reuse the independent resource rules in BigO/Pi.lean. The index type is fixed independently of the input; the value type need not be inhabited. Construction sums the component bounds, using PolyBounded.sum for finite sums in a common size measure. Computed-index access and update retain the captured original input; see the finite-table regression for empty index/value types and the required callback certificates. Import CslibFrontier.Computability.Machines.Turing.MultiTape.Internal.PolyTimePiPrimitives for this plain API. Its computed-index rules use the captured-input dispatch theorem in PolyTimeFinitePrimitives.lean. The regression rejects imports of the higher tidy calculus; Complexity.PolyTime.Finite re-exports the same plain dispatch theorem. The plain Complexity.Degree.Primitives entry point registers ComputableInDegree for fun_prop; extracted list rules do not require Quantitative to enable automation.

For independent time and charged-space bounds, import CslibFrontier.Computability.Machines.Turing.MultiTape.Complexity.BigO.FunProp. It exposes the plain ComputableInO composition rules and the plain option degree provider, including the registered ComputableInDegree.optionGetD rule, without importing Quantitative or the higher tidy calculus. With inferred bounds, fun_prop assembles the resource expression; use ComputableInO.mono once to compare it with the desired bound. The ordinary-import automation regression checks projections, option defaults, conditional branches and nonlinear composition. The tuple and option client checks captured inputs and independent callback bounds. Both reject higher tidy predicates while permitting the machine-level normalization kernel.

To encode a structure as the tuple of its fields, import CslibFrontier.Computability.Machines.Turing.MultiTape.Encodings.Structure and, inside a namespace, write enc_structure eS : S where f₁ : e₁, …, fₙ : eₙ. List every field of S once, in declaration order, and parenthesize compound encodings such as (encList encUnary). List a parent structure either as the single field toParent, as in S's constructor, encoded as one word, or as its own fields in place of toParent, which flattens them into the tuple; listing both is an error. To make a flattened parent projection available to automation, declare its encoding before where: enc_structure eChild : Child flattened toParent : eParent where …. The command checks that toParent is a parent field and is actually flattened. The generated proof also requires eParent to have exactly the selected word layout, so the annotation cannot silently change the encoding. S must be a structure, not a class. The command checks the list before declaring anything: an unknown, repeated or misplaced field, or any missing ones, is an error that names them and lists the fields of S in declaration order. That order fixes the encoded words: the simp lemma eS_apply unfolds eS a to eSFields (a.f₁, …, a.fₙ), where eSFields is the right-nested encPair e₁ (encPair e₂ … eₙ), so every field but the last is framed.

Generated field and flattened-parent polynomial-time rules lift their degree certificate with ComputableInDegree.computableInPolyTime, then compose with the caller’s certificate. They share the degree proof rather than deriving the projection again in the polynomial-time calculus.

For a record in Type, import CslibFrontier.Computability.Machines.Turing.MultiTape.Complexity.LogSpace.Words and write enc_structure eS : S logspace where … to also generate logarithmic-workspace rules for reading the record. Write logspace after any flattened annotations. Each field rule eS_f_logSpace participates in fun_prop, which then proves a rearrangement such as fun p => (p.1.f, p.2) of stored registers and an input; eS_fields_logSpace supplies the raw tuple view. The option adds no constructor rule and no rule for a flattened parent: build a record from the certificates of its fields with ComputableInLogSpace.pair and .congr. The encoded words are unchanged, and the output tape is not charged to the workspace. The option is explicit because logspace composition itself depends on records encoded by the base command.

For each field f, the command also generates eS_f_length_le, stating that the field's encoded word is no longer than the record word. Use this bound before combining arithmetic with omega, without unfolding the record's framed tuple. For dependent fields it bounds the encoded word supplied by the field's encoding function. Single-field records and flattened fields use the same rule names. The structure encoding client exercises ordinary, single-field and dependent flattened records. The production Arborescence storage proof uses these bounds for all four TableAuxInput fields in its iteration and expansion fold: normalize unary word lengths for fuel and root, and compose the adjacency field bound with SizedListEncoding.length_le for the number of rows. No tuple-length identity is needed for these component comparisons; state-growth estimates remain separate.

The optional visibility prefix applies to the encoding, its tuple abbreviation and every constructor/field rule. enc_structure and public enc_structure generate public declarations, even outside a public section; use private enc_structure for an implementation record and keep its generated names inside the defining module. Public fun_prop rules are scoped to the namespace; private rules use local fun_prop in the defining scope and do not export. The visibility fixture uses both forms on the existing parameterized table and on a private, explicitly parameterized record with a dependent field; the importing client rebuilds the public table through both explicit rules and fun_prop, and checks that private generated names are unavailable.

For parameterized records, give explicit parameters before the colon and apply the record in the type: enc_structure eS (Desc : Type) (encDesc : Desc ↪ List Bool) : S (Desc := Desc) where description : encDesc, payload : encBits. Only explicit (p : T) binders are accepted there; implicit and instance parameters come from variable, as below. Every generated declaration takes the explicit parameters in the same order, including eS_apply Desc encDesc and eS_payload_polyTime Desc encDesc. Generated binders keep plain names, such as a in eS_apply and x0, h0, γ and encIn in the constructor rules, so that callers can pass them by name; a name that the command's own terms use is replaced by a fresh one. The parameterized DescribedPair examples in StructureEncoding check the unchanged tuple bytes, construction and projection, workspace-budget preservation, and parameters named like generated binders. The DH challenge encodings use a family parameter to choose the description encoding.

Alternatively, declare the parameters implicitly, as in variable {k : ℕ}, and supply its applied type: enc_structure encWords : Words k where .... Give a field encoding its index explicitly when its type cannot be inferred in isolation, such as (encPi (Index := Fin k) encNat). The generated encoding and rules infer k from their typed input or output, including when a field's own type does not mention k.

A field whose type depends on an earlier field, such as elt : F.Carrier desc, is encoded as a word by an injective function of the earlier fields: write elt : (F.encode desc) using (F.encode_injective desc), where the term after using proves Function.Injective (F.encode desc). The field occupies an encBits slot holding F.encode x.desc x.elt; its generated rules read that word, and the constructor rules take the argument as a dependent function with a certificate for its word. Such a structure has no eS_mk_deg. An explicit parameter that only these terms mention, such as encode in the Sized example in StructureEncoding, does not occur in eSFields, which still takes it. The command then marks eSFields nolint unusedArguments, so clients need no attribute of their own. It does so only when these terms use every parameter that eSFields does not, so the linter still reports a parameter that nothing uses. Both sides are decided on the elaborated terms, as by the linter, so a local binder that shares a parameter's name is not a use. Both terms name earlier fields directly, or through a listed parent field as in toElement.desc. A binder in them must not reuse an earlier field's name, and an explicit parameter that they mention must not share its name with an earlier field; the command reports the latter. A flattened toElement : eElement annotation generates _deg, _inO, _budget and _polyTime rules for that parent projection from the selected word slots; these follow the encoding's public/scoped or private/local visibility. F.encCDHInput, F.encDDHInput and F.encKDFInput use this form, the DDH and key-derivation inputs flattening their CDH parent so that each remains one framed tuple of the security parameter, the group parameters and the element and key words.

The block interpolation caller uses a named seven-field context in place of positional metadata. The assignment label reader similarly names its binary limit, counter, stride and width, and returns a Words k record with previous and providers fields. Both retain their former tuple field order and framing. Native-space clients use generated projection rules and encArgs_mk_budget / encWords_mk_budget to preserve the caller's workspace budget; the assignment label regressions check exact encoding equality alongside actual extracted words.

Migrating a tuple to a record must keep its encoded words, since machine predicates such as IsPPTOn read them. enc_structure produces the right-nested layout encPair e₁ (encPair e₂ … eₙ), so it reproduces a right-nested tuple but not a left-grouped one such as encPair (encPair a b) (encPair c d). For a left-grouped tuple, either nest sub-records whose generated layout matches the old grouping, or define the encoding with encOfEquiv into the former tuple encoding and keep named projection and constructor certificates; encCompState shows the encOfEquiv pattern. A record in a Word-RAM program uses WordEncoding.ofEquiv the same way (realized records). Every migration, including a right-nested one, adds a test that checks encX r = <former tuple encoding> (…) for a general record r (usually by rfl) and states "encoded words unchanged" in the pull request. If the equality cannot be proved, the layout changed: restore it. A changed layout is acceptable only with a coordinator's scope decision and a checked transport of efficiency and security in both directions.

The command also generates the linear field map eS_fields_deg; for each field f and each declared flattened parent toParent, the linear projection rules eS_f_deg / eS_toParent_deg and _inO, the budget-preserving _budget rule (from h : ComputableInSpace g encIn eS S to the projection within budget S), and the _polyTime rule (from h : ComputableInPolyTime g encIn eS to the projection, including a bare projection via id'); and the constructor rules eS_mk_deg from eSFields, eS_mk_inO adding up the field time and space bounds, eS_mk_budget assembling fields sharing a workspace budget, and eS_mk_polyTime assembling polynomial-time fields. For public encodings, the degree, ComputableInO, budget and polynomial-time projection/constructor rules are scoped fun_prop rules (picked up by fun_prop, polytime and space). These public rules are active inside the declaring namespace, including when it is reopened, and after open or open scoped of it; importing the module or opening a parent namespace leaves them inactive. Private encodings register these rules locally until the defining scope ends. Reopening the namespace, open scoped or importing the module does not restore private rule registrations. The complete StructureEncoding client checks unfolding, injectivity, fun_prop and polytime compositions, budget-preserving projection for mixed field encodings, single-field and parent structures, and each field-list error. The universal machine declares its keys, actions, descriptions, tapes and configurations this way.

Option elimination uses one native arbitrary-resource certificate in OOptionPrimitives. The polynomial-time rule lifts it with polynomial envelopes for the selected handler; the callback is certified on the pair of original input and payload. Runtime-default reading and optional mapping use that elimination rule, including empty payload types. Existing clients can keep importing BigO.Option or PolyTime.Option.

For explicit workspace bounds, import Tactic.Space and use space on a ComputableInSpace f encIn encOut S goal. It composes existing arithmetic, pairs, options, conditionals and the generated structure rules without changing S. Use space [f] to unfold a program definition; supply local routine certificates and any nontrivial input-length allowance first. See the complete SpaceTactic client for a record update under an arbitrary budget, composition with a linear-space routine, and rejection of a missing allowance or a binary-to-unary cost substitution.

space also handles a function of a value of a finite type (budget_finite), a conditional on a decidable proposition (budget_iteProp) or its negation (budget_decideNot, which covers ≠), an equality of two values with a common encoding (budget_decideEq, which compares the encoded words) and Boolean connectives (budget_boolNot, budget_boolAnd, budget_boolOr). These rules are in InSpace.FunPropFinite. They reach fun_prop only where that module is imported, directly or through Tactic.Space, so a direct fun_prop client imports the module. When a first search fails, space retries with conditions built from ∧, ∨ and ≤ (budget_decideAnd, budget_decideOr, budget_natLe) and with equalities through the canonical finite encoding (budget_decideEq_encFinite). These rules are not registered, because each would be tried, and fail, on every decidable condition; a certificate that needs them pays for the failed first search. budget_finite cannot determine the encoding of the finite value from the goal. A finite function of a finite value, such as (r x).opp for hr : ComputableInSpace r enc (encFinEnum Dir) S, passes through the canonical encoding encFinite. When such a value is itself a component of the argument of another finite function, as in g ((r x).opp, b x), its encoding is undetermined and the attempt fails with Failed to infer `?encB` . State the value's certificate first, for example have := budget_finite (encC := encFinEnum Dir) Dir.opp hr, then call space. To make a private certificate available to later proofs in the same file, use attribute [local fun_prop] foo_inSpace. If the certificate is proved inside a section, place the attribute after the end. A simp only [foo_eq] that rewrites a program into an if-chain may come first. Tableau.Space and the SpaceTacticFinite client show both steps.

For a computed finite tag whose branches retain the original input, import InSpace.Finite and apply ComputableInSpace.finite_cases htag hbranches. Both certificates use workspace fun a => (input a).length. The tag type and branch machines must be fixed independently of runtime input; runtime-sized windows are not finite dispatch tables. Arbitrary tag and output encodings are supported, including an empty tag type. The finite-dispatch client selects an unbounded word and exercises empty tags. Replay storage bounds share QueryReplay.length_encCells_le, which charges both framing layers for the explicit cells without changing the runtime-width layout.

The tactic does not infer loop invariants or a logarithmic bound in the original input, and it has two further limits. First, fun_prop does not see through a match, so a machine step defined by cases on its control state still needs a hand-written certificate, or a lemma that rewrites it as an if-chain. Second, space matches encodings without unfolding a primitive encoding such as encPair, encList or encFinEnum, so certificates must agree on encodings up to named aliases such as encTuple := encPair …. A component (.1, .2) of a value encoded as one finite value, such as encFinEnum (A × B), therefore goes through budget_finite rather than the pair rule. A direct fun_prop call unfolds encodings and can stop at maximum recursion depth on the same goal.

For a loop that reads its input, import InSpace.QueryLoop and apply ComputableInSpace.queryLoop instead of declaring a QueryMachine. Give the state a structure with an enc_structure encoding; write the position to read as query : σ → ℕ, the round as next : σ × Option Bool → σ (the bit read is none past the end of the input) and the stopping test as done : σ → Bool, and certify each with space at the budget of its encoded argument. The remaining obligations are yours: the start state within the budget S, the number of rounds n a at which done first holds, and a bound c * (S a + log₂ n + 1) on the encoded states up to that round, which usually follows from a closed form of the iterate. The conclusion is the final state within the budget S a + log₂ n; project the answer with the generated _budget rule. ComputableInSpace.computableInLogSpace turns a budget log₂ n into ComputableInLogSpace, and Cslib.Complexity.setOf_mem_DSPACE_of_computableInSpace turns a Boolean function within the budget s n into membership in DSPACE enc s. The SpaceQueryLoop client counts the ones of a word and decides majority this way. space proves a constant under any budget, also a sublinear one, since ComputableInSpace.budget_const asks for no input-length allowance; the client relies on this for the factor 2.

When a round needs more than one bit of the input, for example a whole routine over it, import InSpace.StoredLoop and use ComputableInSpace.loopWith. Write the body as a function step : ρ × α → Option ρ of the stored registers and the input, registers first, returning the next registers or none to stop, and certify it on encPair encR encA within a budget T of the pair. The usual budget is the context form fun p => (encR p.1).length + S p.2, which charges the registers and not the input; any other budget is accepted, for example one that grows faster in a stored parameter than the registers do. Certify the body with space, as the next paragraph describes. Then name the registers r a j of every round j ≤ n a, prove that the body maps each to the next and returns none at the last, and bound the budget of the body on them, T (r a j, a) ≤ B a. The budget is not used on registers that the loop does not hold, and the lengths of the registers need no separate bound, because the value of the body is charged to its budget. The conclusion is fun a => r a (n a) within the budget S a + B a + log₂ n, with a constant that does not depend on the number of rounds. The SpaceStoredLoop client computes the binary length of the number of ones of a word by calling the counting routine of the previous client in every round. To call a certified function on rearranged registers or a transformed input, compose it after the logspace map that produces them: hg.comp_logSpace hf gives the budget Sg (f a) + log₂ n, and hg.comp_logSpace_context hf hS hlog keeps a function of registers and input in context form, given that the budget of g at f p is within the new budget (hS) and that the budget of the input covers the logarithm of its length (hlog). The intermediate value is recomputed, never stored. The SpaceContextSubstitution client reuses the previous body on the complemented word this way. The accessor for the input is ComputableInSpace.inputBit encA from InSpace.InputBit: fun p : ℕ × α => (encA p.2)[p.1]? in context form, within the binary length of the index plus log₂ n, none past the end. It is the logspace lookup computableInLogSpace_bitsGetElem? of LogSpace.BitsGetElem put in context form by ComputableInLogSpace.inSpace_context, which is the pattern for any logspace accessor with a short value. In a body, use it through budget_inputBit of the next paragraph, which takes any position computed within the budget; the SpaceInputBit client shows the accessor composed directly after a logspace projection of the registers. To use an intermediate value more than once without recomputing it, import InSpace.StoredBind: ComputableInSpace.bindWith hh hg stores h a and gives fun a => g (h a, a) within Sh a + Sg a + log₂ n, where hg certifies g in context form with the stored value as registers. The SpaceStoredBind client decides majority by storing the number of ones. To count, or decide majority or existence, over the indices i < m a of a predicate p (i, a) in context form, import InSpace.StoredCount and use hm.countWith hp, hm.majorityWith hp or hm.anyWith hp, where hm certifies the bound m within S and hp the predicate within the length of the index plus S; the result is within S a + log₂ n. The SpaceStoredCount client decides the majority of the bits of a word by enumerating positions with inputBit.

To certify such a body, import InSpace.Context and Tactic.Space and call space [step] under a budget that visibly charges the registers and the logarithm of the length of the input, such as fun p => (encR p.1).length + Nat.log2 (encA p.2).length. space finds the registers p.1 itself (budget_registers) and needs no allowance for constants. State what reads the input as local hypotheses first: budget_ofInput hf h hS for a certified function of the input alone, budget_inputLength h for its length, budget_inputBit hi h for its bit at any computed position i p (the position is stored, not recomputed), and budget_subst hg hf h hT for a certified function of other registers and the input; h says that the budget covers the registers and the logarithm, and .refl _ proves it for the budget above. space uses such a certificate wherever the expression it certifies occurs, also when the expression applies a variable to parts of p. For words of bits held in registers, InSpace.BitWord has rules for a test of every bit (budget_bitsAll, with id the test for the word of ones), the counter Cslib.BitString.increment, the word that repeats a bit to a unary width (budget_bitsReplicate), concatenation, ofBits and a unary number in binary; stored values with a common encoding are compared by budget_decideEq. When a rule is applied to stored registers r and an input a itself, so that it asks for a part as a function of (s, (r, a)), certify the part on ((s, r), a) and apply assoc_context. The SpaceContext client certifies a body that steps a counter, compares it with a stored word and reads the input where its value points; the bodies of the SpaceStoredLoop and SpaceRecursion clients are certified the same way.

When the registers of a loop are not known in closed form, use ComputableInSpace.loopWith_of_invariant from the same module: give an invariant Inv a m r of the registers indexed by a variant m, and prove that it holds at the start, that a round keeps it with a smaller variant, that it bounds the budget of the body by B a, and that it determines the registers where the body returns none.

For a recursive procedure, import InSpace.Recursion and use ComputableInSpace.recWith instead of declaring a stack. Give the frames a structure with an enc_structure encoding, and write the body as a function body : (φ × Option β) × α → (φ × φ) ⊕ β of a frame, the value that a call has just returned to it (none when the frame starts) and the input: it answers .inl (saved, child) to call child and resume saved with the value of the call, or .inr v to return v. Certify it within a budget T as for loopWith, building the two answers with budget_sumInl and budget_sumInr. Then state four things about every input a: the frames that occur (Reach a, which holds of (init a, none)), the value val a c that a reachable frame returns, a rank a that decreases from a calling frame to its callee and to its resumption, and a potential need a. The potential is at least T on a reachable frame; for a calling frame it is at least the encoded length of saved, one more unit and the need of the callee, and at least the need of its resumption. With frames of at most F bits and a depth that decreases by one per call, need a c = (depth c + 1) * F works; when the frames shrink along a chain of calls, let need be the sum of the sizes still to come. The conclusion is fun a => val a (init a, none) within the budget S a + B a + log₂ n, where B a bounds the need of the first frame and the constant does not depend on the depth. The SpaceRecursion client evaluates the NAND tree over a word this way, in space O(log² n).

For reachability by Savitch's midpoint recursion Cslib.Reachability.reach, do not write the recursion again: import InSpace.Midpoint and use ComputableInSpace.reach. Give the width in unary, the depth and the two endpoints as functions of the input within a budget S, and the edge test as a function fun q : (List Bool × List Bool) × α => edge q.2 q.1.1 q.1.2 of two stored words and the input within any budget T, with T ((x, y), a) ≤ E a on words of the width. The conclusion is reach (edge a) (w a) (d a) (u a) (v a) within S a + (d a + 1) * (w a + log₂ (d a) + 1) + E a + log₂ n. Pass (S := …) explicitly; the elaborator does not find it. When the rule is applied to stored registers and an input, certify the edge test on ((x, y), r), a and pass it through assoc_context. The SpaceMidpoint client decides reachability in a graph given by its adjacency matrix within O((W + 1)² + log n); Savitch's theorem for general space bounds in LogSpace.Savitch is the library client.

To encode an inductive type whose constructors take explicit, non-recursive fields, import CslibFrontier.Computability.Machines.Turing.MultiTape.Encodings.Inductive and write enc_inductive eT : T where | c₁ : e₁₁, e₁₂ | c₂ | …, listing every constructor once in declaration order with the encodings of its fields; a constructor without fields has no :. The command checks the list before declaring anything. This original bare-type form rejects parameters; a missing, repeated or misplaced constructor is reported at the type, with the expected constructor list; an implicit field or a wrong number of encodings is reported at the constructor, and an encoding of the wrong type at that encoding. A value is sent by eT_toSum to a right-nested sum with one summand per constructor, which eTPayload encodes with encSum. A summand is the framed tuple of the constructor's fields, as for enc_structure, the field encoding itself for one field, and encUnit for none. Constructor i of n is therefore tagged by i leading true bits, then a false bit unless it is the last, and eT_apply unfolds eT x to eTPayload (eT_toSum x).

The command also generates the linear map eT_toSum_deg, a constructor rule eT_c_inO for each constructor c, which adds up the bounds of its arguments, its lifts eT_c_inSpace and eT_c_polyTime, and case analysis eT_elim on the payloads with its rules eT_elim_inO, eT_elim_inSpace and eT_elim_polyTime. The space lifts retain independent branch or field workspace bounds and existentially quantify time. The polynomial constructor lift recovers explicit degree clocks and applies the original constructor rule; it does not rebuild its machine. The case rule takes the input paired with the value, as ComputableInO.sumElimSnd does, and charges only the case taken plus n times the encoded pair. The toSum and constructor rules are scoped fun_prop rules, active as described above. A match on the type is not yet rewritten to eT_elim, and there is no degree-level case rule. Polynomial elimination recovers independent branch clocks and bounds them in the full input size before lifting the original arbitrary-resource case certificate. For each constructor c, eT_c_matches tests its tag, eT_c_payload? extracts its complete payload, and eT_c_fieldJ? extracts zero-based field J; projections return none on other constructors and need no default inhabitant. Each has _deg, _inO, _inSpace and _polyTime rules. All three predicate views reuse the canonical degree certificate. Matchers preserve output degree zero, while payload and field projections have output degree one. For unknown inputs, eT_c_matches_iff states that a tag matches exactly when the value is that constructor applied to some complete payload. eT_c_payload?_eq_some_iff identifies eT_c_payload? v = some a with equality of v to the constructor reconstructed from a (the right-nested tuple of its fields, or () for no fields). eT_c_payload?_range relates payload existence to the matcher; _isSome remains available for every optional projection. The import-side client uses these public facts without unfolding matches and checks scoped automation and all three fields of a constructor after importing a separate ordinary module. The InductiveEncoding client checks the encoded words, injectivity, a constructor composition, the case rule, an enumeration and each of these errors.

For directly recursive families, give uniform parameters before the colon and write _ for each self-recursive field. All other fields name their chosen embeddings, including fields of a previously encoded family. The recursive fixture gives the complete imports and declarations for arithmetic terms, formulas over those terms, and a polymorphic tree with three recursive children interspersed with scalar fields:

enc_inductive encTerm (n : ℕ) : Term n where
  | const : encIntBin
  | var : (encFinEnum (Fin n))
  | add : _, _
  | mul : _, _

enc_inductive encFormula (n : ℕ) : Formula n where
  | false
  | eqZero : (encTerm n)
  | not : _
  | and : _, _

A type parameter and its encoding are explicit, for example (α : Type) and (eα : α ↪ List Bool) before : Tree α. Parameters select the family and scalar encodings; they are not stored in the word. Resource certificates apply for each fixed choice of those parameters and codecs. Here “uniform” means that recursive occurrences keep the same parameter arguments. The encoded value type must currently lie in Type, following the native codec/loop APIs; a higher-universe phantom parameter is allowed when the value type remains small. Genuine indices, dependencies on earlier constructor fields, proof or implicit fields, mutual recursion, nested recursion, and altered recursive parameters are rejected before any encoding declarations are emitted. Constructor arity has no fixed limit.

To omit the constructor list, import CslibFrontier.Computability.Machines.Turing.MultiTape.Encodings.Derive and declare derive_encoding encTerm (n : ℕ) : Term n inside a namespace. This declaration-time frontend selects scalar embeddings, then generates the same public encoding and native APIs as enc_inductive; the target inductive type must be public. The selected terms are fixed at the declaration, so later policy changes do not alter its encoded words. List every type, value and embedding parameter used by the target or selected encodings explicitly before the colon; ambient section parameters are rejected. The core import registers no defaults. A named policy must be imported and activated explicitly:

import CslibFrontier.Computability.Machines.Turing.MultiTape.Encodings.Policy.BinaryIntUnaryFin

namespace Arithmetic
open scoped Turing.MultiTapeTM.EncodingPolicy.BinaryIntUnaryFin

derive_encoding encTerm (n : ℕ) : Term n
derive_encoding encFormula (n : ℕ) : Formula n
end Arithmetic

This policy selects binary encIntBin for integers, unary encFinEnum (Fin n) for finite variable indices, encBool for Booleans and encUnit for unit. It makes no choice for natural numbers. A constructor field that is directly recursive uses the generated encoding. For every other field, a matching embedding supplied as a declaration parameter, such as (eα : α ↪ List Bool), takes precedence over registered rules. Two matching local embeddings are an error. Otherwise exactly one active registered rule must apply: missing and ambiguous choices are errors, rather than a fallback to a different representation. A family's parameters are inferred from the field type, and any embedding arguments it needs are resolved recursively. Thus deriving encTree (α : Type) (eα : α ↪ List Bool) : Tree α lets a later family with a Tree α field reuse encTree α eα.

Register an existing embedding or parameterized encoding with attribute [scoped encoding_rule] encName in the policy's namespace, and activate it with open scoped PolicyNamespace. Scoped rules are active within that namespace and when it is reopened; an importing client must reactivate them. Opening a parent namespace does not activate its children's rules. Use [local encoding_rule] for a section-local choice. Plain global [encoding_rule] registrations are rejected, so imports cannot silently add choices or ambiguity. A successful derive_encoding automatically registers its encoding as a scoped rule in its declaring namespace, so encFormula above reuses encTerm without repeating its parameters or scalar choices. Clients reactivate both with open scoped Arithmetic; importing the module alone does not activate those choices. Local registrations expire at the end of their scope and are not restored by reopening the namespace. Registered embeddings must be public; use local or scoped registration to limit their activation. The frontend rejects unsupported constructors before generating names and inherits the uniform parameter and recursion restrictions above. Use enc_inductive to spell out a particular constructor layout or resolve a deliberate choice explicitly. Neither command supplies scalar decoders. The frontend fixture compares the full arithmetic grammar and parameterized trees with explicit declarations; its importing client exercises scoped reuse, certified construction and projections, and strict decoding.

The recursive representation is a preorder constructor stream. Each token contains its constructor tag and scalar fields in scalar-field order, followed by the child streams in recursive-field order. Tags use the same right-nested sum convention as above. Scalar tuples frame every field except the last, with encUnit for no scalar fields; encList then frames each token once. Whole recursive children are never framed again. eT_c_apply and eT_c_length state each constructor's words and size. eT_length is the exact sum of token frame lengths; eT_length_le gives length ≤ (2 * (c + m) + 1) * nodes + 4 * leafSize, where c is the number of constructors in the type, m the largest scalar-field count, and leafSize sums the chosen scalar word lengths. Depth does not multiply the size.

Constructor assembly preserves independent bounds, adding the argument clocks or workspaces and twice the encoded input length. Matchers and scalar projections have linear native rules; recursive-field and complete-payload projections have native polynomial-time rules from a bounded-arity stream scan. Typed-token decoding needs no scalar decoder. Bit-word decoding uses eT_decoder, with an explicit PartialDecoder for each scalar field, in constructor/field order. Each witness proves strict decoding and native polynomial time, including the charged decoded output, for every bit word. PartialDecoder.ofDecoder can check an existing total decoder; ofOptionDecoder and empty also cover empty scalar types such as Fin 0. The generated bundle accepts exactly the encoding's image, so malformed frames, invalid payloads, missing children, and trailing input are rejected. An arbitrary embedding supplies no decoder or efficiency assumption. Encoding syntax does not certify evaluation or arbitrary recursive functions. The importing client checks the generated constructor, recognition, projection, decoding, and axiom interfaces.

The isolated degree-transition experiment compares named explicit lifts with a locally registered degree-to-polynomial fun_prop transition. Its irreducible test operations have only locally registered degree rules and no direct degree hypotheses in their clients. Separate cost/output indices, Boolean output degree zero, composition and negative controls before registration and after its scope are covered. The checked experiment discovers the degree certificates and lifts them through the local transition. One hosted measurement on 2026-11-15, including profiler overhead, took about 2.5/2.3/3.4 ms for the explicit pack/flag/composition proofs and 7.9/6.5/12.8 ms for local-transition search. These single observations establish neither a stable speed ratio nor a general performance result. The experiment supports retaining explicit lifts and keeping the transition local; it neither changes global automation nor supplies production-caller migration evidence.

The two encoding commands share the degree-certificate proof terms in Internal.DegreeLifts. This does not change their contracts: a structure field's _budget rule composes with a caller's workspace bound; an inductive matcher or optional projection's _inSpace rule uses encoded input length. Matcher output degree remains zero. Constructor and elimination rules with independent argument or branch bounds keep their separate constructions. The ordinary-module structure and inductive visibility clients exercise these distinctions.

Binary and unary naturals are different contracts. A loop count computed into encUnary pays for writing its value; a short binary representation alone does not justify that many iterations. Framed lists charge both elements and delimiters. State bounds must include that representation overhead.

An arbitrary embedding supplies neither a decoder nor a decision procedure for malformed strings. Native correctness on values encoded by enc is a statement about valid inputs. If the application accepts arbitrary bytes, supply the parser, its correctness and its resource bound. Inspect any malformed-input guarantee in the chosen model checker rather than inferring it from injectivity.

To reuse a theorem under different encodings, match its representation first. For a function certified from oldIn to oldOut, supply efficient identity translations from newIn to oldIn and from oldOut to newOut, then compose. If the encoded words are literally equal, ComputableInPolyTime.of_eq gives the copy-machine case. To reuse a certificate h for a different output type with the same encoded words, use h.of_enc_eq and prove that the output words agree on each input. A mathematical bijection by itself is insufficient to preserve complexity.

Check uniformity and implementation#

A native certificate chooses one finite machine before quantifying over inputs. Separate existence proofs for every length need not supply such a machine. Likewise, a circuit for every width does not establish an efficient constructor. UniformCircuits.reverseFamily explicitly provides one code-generating function and its ComputableInPolyTime certificate.

For RAM, read the operation interpretation and cost convention. The generic interpreter permits arbitrary semantic primitives; a generic execution theorem alone does not implement them on bits. The RAM reference describes native primitive certificates; the Word-RAM bridge adds initialization and width obligations. For stateful specifications, refinement and realization separate abstract operation counts from native instructions. Consult the circuit and finite-model references before transporting those theorems.

Continue with the deterministic workflows once you have a Lean goal, a client and explicit bridge hypotheses.