Skip to content

Interaction cost: discrete bounds on interface use, consolidated across PolyFun, VCVio, ArkLib and CatCrypt #387

Open

Description

@dtumad

This tracks one generic API for interaction cost: costs read structurally off a program's use of an interface, such as how many calls it makes, of which kinds, and at what price. Several projects built special cases of this independently, and the goal is one PolyFun API that they can all depend on. The core of the API (phase 1) merged on 7–8 November. This issue now tracks the roadmap for generalizing the rest, organized by what each reading of a program's calls keeps and forgets.

Scope

In scope. Discrete costs of interface use. A charge prices each call of an interface. Pure Lean code between calls is free, so a cost is a function of the program's interaction tree, which is ordinary data. Nothing here needs the cost of a Lean function, or any intensional distinction between extensionally equal functions. The notion applies to any program that interacts through an interface:

  • oracle queries, group operations and ticks;
  • handler reductions;
  • protocol rounds.

Out of scope, tracked elsewhere:

Expectations over randomness and security statements stay in VCVio.

The notion

A charge c : P.A → ω prices each call position of an interface P in an ordered additive monoid ω, and is paid when the call is made. ω ranges over ℕ, K → ℕ, ℕ∞, ℝ≥0∞, ℤ, ExecutionCost, and so on. As a polynomial map, a charge is the lens Lens.toConst c : P ⇒ C ω. Pulling it back along a lens is composition (Lens.toConst_comp), and the charge on a sum is the copairing (Lens.sumPair_toConst).

Every reading is a fold (wpFold) of a per-call rule over the program. Sequencing is therefore exact, and transfer through a handler is a pullback (wpFold_liftM).

Reading Per-call rule
budget IsChargeBound x c B s allow the call if s + c a ≤ B, and continue from s + c a
worst-case cost c x c a + ⨆ b, k b
CallsIn x S the call lies in S
IsRollBound canRoll a b, and continue from cost a b
expected charge OpSpec.expectedCharge ν c (#445) c a + 𝔼[k] under the answer measure ν a

Completed paths. Path.charge c x p bounds completed paths only. It is needed for signed weights, where a prefix can overspend while every completed run stays within budget.

Relation to IsRollBound. IsChargeBound is the additive special case of the general budget automaton IsRollBound (isChargeBound_iff_isRollBound). Roll bounds alone express non-additive protocols such as "never call b after a". What charges add are laws without side conditions: additive bind, transport along →+o, handler transfer with per-call certificates, a value form, automation and an exact Std.WP reading.

Other models. Resumption, DynComputation, ITree and IFreeM inherit the notion through truncation, unrolling and Σ-erasure. In an ITree, silent steps are charged tau.

Special cases this subsumes

Where Special case Generic form
VCVio IsTotalQueryBound, IsQueryBoundP, AllQueriesSatisfy, IsPerIndexQueryBound unit, indicator and Pi.single charges. Derived in Verified-zkEVM/VCVio#1060 (isQueryBoundP_iff_isChargeBound and siblings); the general IsQueryBound stays a roll bound
Verified-zkEVM/VCVio#942, Verified-zkEVM/VCVio#930 weighted and per-kind budgets; CostCertificate.simulateQ_run; table growth IsChargeBound, .map, .run_liftM; resource growth le_of_canReturn_run_liftM
Verified-zkEVM/VCVio#1016 mapLens, transport of query bounds IsChargeBound.mapLens, FreeM.liftM_mapLens, general IsRollBound.mapLens
Verified-zkEVM/VCVio#1013 weighted-cost transfer through stateless handlers Path.charge_liftM_le_of_forall. Derived in Verified-zkEVM/VCVio#1062
Verified-zkEVM/VCVio#1018 DeterminedCost; MeasuredProgram / BudgetedProgram run_liftM_withChargeW_id, derived in Verified-zkEVM/VCVio#1062; the same structures over PFunctor (Free/Cost/Measured.lean), not yet derived
VCVio withAddCost, addCostOracle, enforceOracle; expectedSimulatedQueryCount Handler.withChargeW, withBudgetOr, derived in Verified-zkEVM/VCVio#1062; the expected charge OpSpec.expectedCharge (#445), not yet derived
ArkLib arithmetic profiles, liftComp transport, ℝ≥0∞ keyError round costs, fresh-key charges, node-indexed stage budgets vector charges; mapLens; .map into ℝ≥0∞; TraceList.freshCharge; Path.chargeDec
CatCrypt Container.cost, TickSig, query profiles, TimedM, useBound_liftM FreeM.cost; a tick as a call to linear ω; prod/pi budgets; a ≤-graded carrier; Certified.ofDemand
(new) caching makes at most as many target calls as there are distinct keys amortized transfer Path.exists_run_liftM_amortized

Not covered, for reasons unrelated to cost:

  • VCVio's quantum query mass, used in the √-hybrid bound. It is amplitude-weighted and state-dependent, so it is not a function of the tree. Quantum query counts are covered: VCVio's QuantumComp.IsQueryBoundAt, IsQueryBound, IsTotalQueryBound and IsCostBound are instances of IFreeM.IsChargeBound. CatCrypt's QROM adversaries (QAdv m n w q) fix the query count in their type;
  • direct-style HasQuery programs, which have no syntax to read.

Phase 1: merged

Roadmap

Every reading of a program's calls is a reading of its completed paths. The roadmap orders the work by what each reading keeps: the whole trace, a meter on it, a bound on the meter, or a summary that forgets order. Items name the existing API they build on and the consumers waiting for them.

1. Paths and traces

In place: Path, TraceList, splitBind/joinBind, Path.ofHandler_bind (#423), and the exact substitution law exists_path_liftM_iff: a completed path through x.liftM h is a path through x with a path through each call's implementation.

  • Stateful threading. Path.Threads with exists_run_liftM_iff, the stateful counterpart of the substitution law (CatCrypt's mem_profile_simulate_iff).

2. Meters: every instrumentation reads the trace

A meter records something at each call. An additive meter is a monoid hom out of the free monoid of calls: withChargeW is withTraceBefore read through a hom (withChargeW_eq_withTraceBefore). Fresh charges (TraceList.freshCharge) and watermarks (#397) are functions of the trace that are not homs. The week's VCVio cost PRs re-prove the laws of this layer by hand, which is why it comes first.

3. Bounds and transfer

In place: upper-bound transfer for every reading, through free, stateful, amortized and certified handlers and costed reductions.

4. Summaries: what an accounting forgets

A summary of a handler is the image of its trace under a quotient:

Keeps Forgets Algebra Composition through a handler
the trace nothing lists (the free monoid) the substitution law
how often each resource is used order, adaptivity, answers multisets, count vectors (ι →₀ ℕ) multiset bind: the Diller–Nahm category (#460; #497 packages it)
which resources are used also multiplicity finite sets union: the original Diller–Nahm variant
a price also the kinds ω the exchange →+o

The finite-set row is the idempotent case, where using a resource twice costs once. A cache in front of the callee charges in this way. Historically, Gödel's Dialectica interpretation lets the opponent play one move, the Diller–Nahm variant a finite set, and modified realizability every move (Ferreira and Oliva, LMCS 7(1:9), 2011, §1). The multiset version in #430 is Moss and von Glehn's (LICS 2018, §8). #431's weighted exponential bangW S, over a commutative semiring S, would give these accountings uniformly: ℕ counts uses, ℕ∞ bounds them, and ℝ≥0 gives expected demand (with #400). Whether Bool gives the finite-set row, and a tropical semiring peak use, is to check.

Variance. PolyFun's handlers read a polynomial as requests and responses (the effects reading). Diller–Nahm reads it as outputs and inputs (the systems reading of DynSystem and Dialectica categories): data flows forward, and each demand at the output becomes a bag of demands at the input. So a handler implementing P by Q gives a demand morphism from Q's resources to P's. The summary map is contravariant: handler composition becomes Diller–Nahm composition in the opposite order.

Limits. A summary keeps counts and forgets order, adaptivity and answers. A worst case taken per kind also loses correlations, such as a cap of q calls in total that a per-kind bound cannot express; completed-path charges keep those. Multisets do not share: each use re-runs its producer, so caching needs the finite-set row or the meter-placement law above.

5. Bridges

6. Contracts: what a cost claim states

From Alexander Hicks's review (comment of 2026-11-17) and Verified-zkEVM/ArkLib#1528. The generic predicates stay for the laws; these are the forms a contract states.

  • A contract-grade cost predicate beside CostAtMost: canonically ordered counts with the standard addition and order, finitely many kinds or →₀ budgets, and finite total cost under natural-number counting, without requiring finite oracle domains. PolyFunTest/PFunctor/Charge/Basic.lean pins the failure modes it rules out.
  • One MeasuredProgram. VCVio's becomes PolyFun's, landing together with ArkLib's repin.
  • Sized contracts (CostWithin, PolyCost and the restricted forms), with cslib's PolynomiallyBounded as the growth predicate. They bound declared operations and are never named PPT; strict PPT is Tracking: connecting VCVio to cslib-frontier (strict PPT, VCVioFrontier, adequacy) VCVio#906.

Consumers waiting

Smaller follow-ups

  • Generalize the answer universe of handler targets (WithinCharge.comp, Path.exists_run_liftM_amortized).
  • A lawful graded-monad instance for Budgeted (LawfulGradedMonad exists; only Budgeted.instGradedMonad is provided).
  • Module canaries for the Under unfoldings; the event canaries come with feat(pfunctor): answer-dependent charges and watermarks #397.
  • A note in docs/guides/cost.md that scored products (qubits × T-count, bytes × cycles) are monotone images of componentwise bounds.
  • Lemma-level instance arguments weakened; Path.charge_const_zero; the universe note in the guide.

Upstream

  • cslib: no_index on FreeM.liftM_lift_bind and liftM_lift, which do not fire on concrete abbrev interfaces. PolyFun keeps the primed workarounds liftM_lift' and liftM_lift_bind'.
  • cslib: AddSupDistrib, staged in ToCslib/Order/AddSupDistrib.lean with ℕ∞, ℝ≥0∞ and Pi instances. Mathlib has only ENat.add_iSup and ENNReal.add_iSup.
  • The concrete tail-call regression from v4.35 and v4.36-rc1 is covered on stable v4.36 by chore(deps): port traces and program logic to Lean 4.36 #477. Both the scoped call rule and the budget reading solve a branch whose final request returns Bool. Budget regression · Scoped rule

Open questions

  • IFreeM.IsChargeBound is ℕ-valued and subtractive. Should it be generalized (a breaking change), or kept with the erasure bridge isChargeBound_iff_toSigmaFreeM?
  • Bridges for chargedFoldlM and ReactiveNetwork.Charge (the potential method), and for stutter budgets in simulations.
  • DynComputation.cost is the supremum of the costs of its truncations. Does it satisfy a step equation, as a least fixed point of the per-step rule (costToGo, from Backend-relative resource bounds roadmap #279)?
  • Rewinding. An extractor over a prover interface costs c₂ + c₁·n₂ through CostedReduction, and feat(pfunctor): the graded exponential and count matrices on lenses #448's count matrices give the same law. Which form should the forking lemmas state? For fixed answer tables, feat(Rewinding): charge reruns by their query cost VCVio#1166 already bounds the expected rerun charge by a per-rerun price times the expected count, including nonzero initial counters. A checked integration on VCVio f1e63c780 with PolyFun 77731620 derives the same statement by projecting both counters from one stateful simulation. Its final proof takes ten lines and needs nine preceding helper declarations and four local instances. The twelve-line induction remains the shorter implementation. The rewinding module, the alternative derivation, and the adaptive-world counterexample passed targeted builds and strict Lean checks. Maintained theorem · Reproduction
  • Codec transport for fresh-key charges (ArkLib).

cc @spitters @alexanderlhicks @quangvdao: this consolidates the cost work from your PRs; comments on the roadmap are welcome.

Activity

  1. added
    enhancementNew feature or request
    trackingRoadmap or tracking issue for a body of work
    on Nov 4, 2026
  2. alexanderlhicks commented on Nov 4, 2026

    @alexanderlhicks
    Contributor

    I think unifying as much as possible would be great. I think it's also important to think ahead about how to relate any resource modelling and bounds at different layers, from the high level protocol specifications to binaries and runtime.

    edit: added a comment below based on my sessions with the agents in the last few days.

  3. spitters commented on Nov 4, 2026

    @spitters
    Contributor

    CatCrypt-core already has most of this at ω = ℕ / ℕ∞, on top of OpSpec.charge:

    • worst-case cost, additive bind, lens pullback: CodeCost
    • charge bounds ↔ IsRollBound, sum charges, CallsIn (MayOnlyCall): OracleQueryVec, OracleSimulation
    • completed-path charges and value form (profile, charge_bind, Within): OracleProfile
    • handler transfer: isQueryBoundBy_simulate, isQueryBoundBy_subst
    • query_bound tactic: QueryFold
    • measured programs TimedM: XTimedMonad
    • spTreeQueryCost = cost for query-bounded trees (queryCost_eq_cost, CodeCost)
    • use counts (handler with n₂ calls: c₂ + n₂c₁): DillerNahm
    • quantum: our QROM adversaries fix the query count structurally (QAdv m n w q, SemiClassicalOracle), so the bounds there need no query-mass notion.

    We would move these onto the stack; #380 is the first part.

  4. alexanderlhicks commented on Nov 4, 2026

    @alexanderlhicks
    Contributor

    Some feedback from the ArkLib side, where we have just been through several rounds of adversarial review of extractor resource accounting (ArkLib #1359/#1364/#1370/#1397, now #1448 and #1453). The scope split looks right to me, and reading costs structurally off the interaction tree is the right base layer. Most of what follows is about how this layer connects to the layers above and below it. A bound is only useful if a reader can carry it from a protocol specification down to code and a machine.

    1. Name what each certificate leaves uncharged, and where the next layer bounds it

    "Pure Lean code between calls is free" is a sound definition of interaction cost. It is not a bound on work, and nothing in the types signals the difference. In #393's MeasuredProgram, the view, the answer function and all code between calls are uncharged. So ofFun f gives Realizes f ∧ CostAtMost 0 for every f, and any statement of the form ∃ M, M.Realizes f ∧ M.CostAtMost B holds trivially. We hit exactly this in ArkLib: knowledge soundness with an existentially quantified extractor and no cost is equivalent to plain soundness. The fix there was to name the measured program in the statement, never to quantify over it. I'd suggest:

    • The guide and docstrings should say that a charge bound is a bound on interface use relative to an accounting boundary, and should list that boundary: view, answers, inter-call code, handler state, encodings.
    • A regression test should show that the existential form is trivial, so no downstream contract quietly adopts it.
    • Each uncharged component should have a named place one layer down where it can be bounded.

    Roughly, the layers I have in mind are:

    Layer Charged Free at this layer Bounded by
    Protocol / spec rounds, oracle queries, prover invocations everything else this issue (#387)
    Algorithm field/group/polynomial operations as interface calls (ArkLib's Kind → ℕ profiles) view, answers, glue code this issue, with operation interfaces
    Code glue code, views, handler implementations — PolyFun QuantitativeRealization / RunsWithinUnder, #279, #337
    Machine / binary backend steps — an adequacy theorem to a TM/RAM model, or a named trust assumption
    Runtime — — benchmarks: evidence, not proof

    2. A stated bridge to QuantitativeRealization

    PolyFun already has the layer below: QuantitativeRealization.executionCost, RunsWithinUnder, wrapState with WrapStateCostCertificate, and fixed Boundary encodings. Right now the two layers are related only in prose. I think the most valuable addition, whether in this stack or as its first follow-up, is one theorem of roughly this shape:

    If x.IsChargeBound c B, each operation a has a realizer of backend cost at most π a, and the inter-call machinery has an overhead bound o (as a function of path length and encoded sizes), then a realization of x has executionCost ≤ (π-weighted B) + o.

    This is the standard shape in the literature. In EasyCrypt's cost judgements (Barbosa, Barthe, Grégoire, Koutsos, Strub, Mechanized Proofs of Adversarial Complexity and Application to Universal Composability, CCS 2021), an adversary's cost is its own cost plus the sum of its oracle-call counts times the oracles' costs. It is instantiated by substitution, and the adversary's intrinsic cost is a separate term. calf (Niu, Sterling, Grodin, Harper, POPL 2022) makes the same split a phase distinction: the extensional phase erases cost, which is what Realizes is here. Without the bridge, a charge bound is a free-floating proxy. With it, →+o transport (IsChargeBound.map) becomes the pricing step from one layer to the next.

    A concrete gap at the layer interface: #391's amortized caching transfer (Path.exists_run_liftM_amortized) has no quantitative counterpart. The realizability guide says a cache hit needs silent steps, which wrapState does not cover. The two layers should agree on which handler shapes they support.

    3. Separate generic laws from security-facing contracts

    Generic ω (signed, ℕ∞, ExecutionCost, …) is right for the laws. But some choices of ω make "cost ≤ budget" meaningless as a resource bound, and the API should make the safe choice easy and the unsafe one visible:

    • Infinitely many kinds. With K → ℕ and K infinite, a pointwise budget does not bound total work: one call to each of unboundedly many kinds respects a budget of 1 per kind. ArkLib's public count contracts require [Finite Kind] for this reason (knowledgeSoundnessWithResources, MeasuredKnowledgeCertificate). K →₀ ℕ budgets avoid the problem because the budget's support is finite. It would help to document this and offer a finite-kind contract form.
    • Order and addition. A reversed order (OrderDual) or max-plus addition makes ≤ B mean something else entirely. ArkLib pins Kind → ℕ with pointwise + and ≤, and has fail_if_success tests that a caller's local max-additive or reversed-order instance cannot instantiate the public certificate (ArkLibTest/OracleReduction/MeasuredExtraction.lean).
    • Signed prices. CostAtMost admits signed prices. With a negative-priced operation, padding a program with "refund" calls meets any budget. That is legitimate inside a potential argument, but it should not reach a contract. I'd suggest a canonically ordered ω (CanonicallyOrderedAdd) for anything presented as a resource bound, keeping signed weights for the completed-path calculus.

    4. Budgets must not be free functions of the input

    A budget allowed to depend freely on each input or view can be defined as the program's own worst-case cost there, which proves nothing. #393's price-per-operation, independent of the view, already avoids one form of this. For families, the next step is to make the size measure and the budget envelope parameters fixed independently of the program, and to prove growth separately. This is also where PolyFun's PolynomialRunBound and PolynomialProgramWitness split already points.

    A related lesson from FMN24 (ePrint 2023/846, Lemma 2.31): the printed growth condition (ℓ(k−1))^µ = poly(λ) holds trivially when ℓ(k−1) = 1, while the extractor runs the prover (ℓ(k−1)+1)^µ = 2^µ times. Bounds should be stated about the actual calls of the actual algorithm, which is precisely what a structural fold provides. That is an argument for this design. It also argues for modelling the prover or adversary as an interface, so that rewinding extractors are charged per prover invocation and the prover's own cost enters by handler substitution.

    5. Expected cost and handler transfer

    For the expected-charge reading on the VCVio side, transfer through a handler needs the per-call expected bound to hold for every call argument and handler state (or history), not on average. Otherwise substituting an expected-cost implementation into a program whose calls depend on earlier answers can break the bound. Katz and Lindell (Handling Expected Polynomial-Time Strategies in Simulation-Based Security Proofs, J. Cryptology 2008) is the standard reference. Worth fixing in the statement of the expected-transfer theorem before VCVio derives expectedSimulatedQueryCount from it.

    6. Open question: composition along protocol telescopes

    ArkLib #1448 (open) has a working client: MeasuredStages.programAlong composes per-stage measured programs along an execution path. programAlong_budget_le gives path.length • bound, and the state-restoration specialization (ProtocolBudgetAtMost) gives rounds.length • (messageBound + challengeBound), which is exactly 2 on the acceptance fixture. That matches #390's Path.chargeDec_le_length_nsmul closely, so it should port directly. It would make a good acceptance test for the PolyFun measured-program API. The same applies to ArkLib's negative tests (infinite kinds, reversed and max-plus orders) and its zero-stage ofFun client.

    Smaller points

    • Migration. VCVio and PolyFun would briefly both have a MeasuredProgram. I'd plan the VCVio side as a derivation from PolyFun, landed with its downstream callers, rather than a long-lived parallel type. ArkLib does not keep compatibility aliases by default.
    • Native code. implemented_by / FFI realizers can only enter the machine layer as named, tracked assumptions. ArkLib's axiom sweep treats native-compiler trust as never allowlistable, and a cost certificate that depends on one should say so.
    • Termination and availability. These are separate from cost: completed-path and safety readings say nothing about divergence or about whether a cheap call is actually available. VCVio #1013 and ArkLib already keep access (AllQueriesSatisfy / CallsIn) as a separate conjunct. Keeping that separation explicit in the generic API would be good.

    Happy to help turn the ArkLib cases into PolyFun acceptance tests.

  5. dtumad commented on Nov 4, 2026

    @dtumad
    CollaboratorAuthor

    Thanks, both. This shaped a follow-up round. I surveyed the layers above and below (RISC-V/zkVM models, the Lean benchmark statements for EVM gas, cycles and T-counts, group models, UC, CatCrypt, ArkLib), plus the literature. Then I ran a spike on bridging cost layers. Below is how I think we generalize, and what is coming.

    How the pieces generalize

    The structural fold stays as the base. It matches what the literature converges on: effect observations in Dijkstra-monad terms, CryptHOL's interaction_bound, EasyCrypt's instantiation rule, and calf's extensional phase. Two benchmark projects already rebuild it by hand: a RISC-V cycle writer over OracleComp, and a T-count that is exactly FreeM.cost.

    The generalization sits one level up:

    • A layer is an interface with a charge, (P, c : P.A → ω).
    • A link between layers is a certified implementation. It has three parts:
      • an implementation of P by the layer below;
      • an exchange E : ω →+o ω' that converts prices;
      • per-call certificates.
    • Bounds move along a link by one transfer step.
    • Links compose, and so do their exchanges.
    • The bottom link prices into ExecutionCost.

    There is one notion of link per level PolyFun has:

    Link What it is Transfer Composition
    free handler Handler.Certified P Q c d (handler, exchange, certificate) transfer : x within B ⇒ x.liftM h within E B, plus a value form Certified.comp: Kleisli composition, with exchanges composed
    stateful package Stateful.WithinCharge (from every state) .run .link, along Stateful.link
    machine RefinesVia L h x σ₀: L implements the run of x through package h RefinesVia.isChargeBound RefinesVia.link
    realization ExecutionTrace.charge, plus a bridge RunsWithinUnder.executionCost_add_charge_le (below) —

    A reduction is a certified simulation between setup and finish stages. Its bound is affine in the source budget, setupCost + E B + finishCost. That is the cost transformer every group-model reduction carries, and the Diller–Nahm Clocked law in CatCrypt.

    Costs that are not additive sit beside this, as stateful observers on the call stream:

    • a watermark monoid for signed prices and peak space or width;
    • answer-dependent charges (EVM warm/cold gas, the AGM basis growing per reply);
    • potentials for amortization.

    Parallel composition is the one gap at every layer. A lax-interchange mixin fits work and peak space, but qubit width interchanges the other way, so I'd add it only with a client such as budgeted UC emulation.

    Spike result

    Everything below compiles with no sorry on a local branch above #394:

    structure Handler.Certified (P Q) (c : P.A → ω) (d : Q.A → ω') where
      handler : Handler (FreeM Q) P
      exchange : ω →+o ω'
      certificate : handler.WithinCharge d (exchange ∘ c)
    
    theorem CostedReduction.run_isChargeBound (r) (hx : x.IsChargeBound c B) :
        (r.run x).IsChargeBound d (r.setupCost + r.certified.exchange B + r.finishCost)
    
    theorem Stateful.WithinCharge.link (ho : outer.WithinCharge d c) (hi : inner.WithinCharge e d) :
        (outer.link inner).WithinCharge e c
    
    theorem RefinesVia.isChargeBound (hL : L.RefinesVia h x σ₀) (hh : h.WithinCharge d c)
        (hx : ∀ g, (x g).IsChargeBound c B) (g) : L.IsChargeBound d B (L.init g)
    
    -- the realization layer: the machine's own work plus what is paid to answer its calls
    theorem RunsWithinUnder.executionCost_add_charge_le (h : R.RunsWithinUnder allows bound)
        (implements : R.machine.Implements program) (hprogram : ∀ i, (program i).IsChargeBound c B)
        (π : p.A → ℕ) (φ : ω →+o ℕ) (hπ : ∀ a, π a ≤ φ (c a)) (trace) (conforms) :
        R.executionCost input trace + ExecutionCost.ofWork (trace.charge π) ≤
          bound input + ExecutionCost.ofWork (φ B)

    The end-to-end test chains three layers:

    • a specification within q hash queries;
    • an algorithm where each hash is 2 compressions (exchange 2 •);
    • a stateful package where each compression is 3 visible machine steps.

    The machine is then within 6 q steps, by composing the certificates and never unfolding the program.

    Still open:

    • An oracle-realizer object. In the realization bridge above, the answering prices π are a bare function. Alex's full theorem needs realizers whose costs are π, and a way to close a realization against them. That is a design decision in realizability, which I'd take on next.
    • Hidden internal steps. Several machine steps per call are covered only when the steps are visible calls of the machine's interface. A block-simulation constructor for hidden steps, with a per-call step budget, is not built.
    • Parallel composition, as above.

    Alex's points

    These go into the open PRs before they leave draft:

    Point Where it lands
    A charge bound is relative to an accounting boundary an "accounting boundary" section in the guide (#388), plus docstrings on IsChargeBound and MeasuredProgram. It lists what is free (views, answers, inter-call code, handler state, encodings) and where each is bounded one layer down
    ∃ M, M.Realizes f ∧ M.CostAtMost B is trivial a regression test (#393) showing it holds at 0 for every f via ofFun; statements name the measured program
    contract hygiene guide notes (#388), with tests: resource contracts use canonically ordered ω and finitely many kinds (K →₀ ℕ or [Finite K]), signed prices stay inside potential and path arguments, availability (CallsIn) and termination are separate conjuncts
    budgets are not free functions of the input the machine-level ImplementsWithinCharge uses a uniform budget, like ImplementsWithin
    expected-cost transfer noted for VCVio: per-call bounds for every argument and state (Katz–Lindell)
    native realizers will enter the realization bridge only as named assumptions
    ArkLib acceptance tests gladly. The negative tests (infinite kinds, reversed and max-plus orders, zero-stage ofFun) can come now; programAlong once #1448 lands, against #390's chargeDec_le_length_nsmul

    Bas

    Since CatCrypt's results mostly live on its own monads, the most valuable piece is a bridge.

    • OracleAdv is already equivalent to FreeM (AdvSig D R) via equivFreeM. With toFreeM_bind, toFreeM_subst and toFreeM_simulate, OracleSimulation, OracleSubst, OracleQueryVec and most of OracleProfile become corollaries of the stack.
    • cost_eq_iSup_profile is being ported into feat(pfunctor): charges of completed paths #390 (under ProgramProgress).
    • Clocked is CostedReduction above.
    • DNLens could move as is once a rewinding consumer appears.

    Thanks for the QAdv and queryCost_eq_cost pointers; I'll correct the "not covered" list above.

    What's next on the stack

    Hardening in #388–#394:

    • the items above;
    • the one transfer principle (wpFold_liftM_le);
    • the machine charge iff.

    Three more PRs above #394:

    • certified handlers and reductions;
    • observers: answer-dependent charges, the watermark, and prefix-form amortization;
    • bridges to machines and realizations.
  6. spitters commented on Nov 4, 2026

    @spitters
    Contributor

    Thanks. From the CatCrypt side:

    1. Bridge. We are adding toFreeM_bind, toFreeM_subst and toFreeM_simulate over equivFreeM, so that OracleSimulation, OracleSubst, OracleQueryVec and OracleProfile can become corollaries of the stack once feat(pfunctor): interface charges and structural charge bounds on free programs #388–feat(pfunctor): charge certificates, instrumented and gated handlers, handler transfer #391 merge.
    2. Rewinding consumer for DNLens. Our forking and tree extractors (TreeForkingLemma, GeneralForkingLemma) run the prover several times; Diller–Nahm use counts (c₂ + n₂c₁) charge exactly per prover invocation, as Alex suggests.
    3. Machine layer. Our time certificates have the EasyCrypt shape (own time + queries × oracle time, timeBound_simulate), and link_timed proves a derived cost bounds the cost of the reduction's term in a call-by-value language with the cost model of Forster–Kunze's L, for first-order reductions.
    4. Budgets. Our convention fixes the shape of a reduction or simulator bound in advance: adversary time plus a constant, plus a + b·i at activation i for growing state, or plus b·|e| in the event size (ConcreteSecurity.md), never a free function of the input.
    5. Caching. OracleCache: a caching handler with an exact path law (inner calls = new cache keys ≤ distinct queries), and the lazy random function as the cached run with fresh draws (OracleCacheLazyRF); a time version would follow from our cost derivation on the handler.
  7. dtumad commented on Nov 4, 2026

    @dtumad
    CollaboratorAuthor

    Thanks, Bas. All five points fit the stack. Below I map each to it, then step back to what the generalization covers, read from the weakest-precondition side.

    Your five points against the stack

    1. Bridge. Once toFreeM_bind, toFreeM_subst and toFreeM_simulate land, OracleSimulation, OracleSubst, OracleQueryVec and most of OracleProfile should become corollaries of feat(pfunctor): interface charges and structural charge bounds on free programs #388–feat(pfunctor): charge certificates, instrumented and gated handlers, handler transfer #391. cost_eq_iSup_profile already has a generic counterpart, Path.cost_eq_iSup_charge in feat(pfunctor): charges of completed paths #390 (under ProgramProgress). Happy to review the bridge when it's up.

    2. Rewinding. A forking or tree extractor is a program over a prover interface, run within a call budget n₂ (a unit charge). Substituting a prover implementation of cost c₁ is a certified handler with exchange n ↦ c₁ · n (feat(pfunctor): certified handlers, costed reductions and stateful certificates #396). With the extractor's own work c₂ as the setup and finish stages of a CostedReduction, run_isChargeBound gives c₂ + c₁ · n₂. So each prover invocation is charged, as Alex asked, and the extractor is named rather than quantified. DNLens could then come in as the non-adaptive (⊗) counterpart of these adaptive (◁) handlers.

    3. Machine layer. The EasyCrypt shape "own time + queries × oracle time" is a charge bound on P + linear ω. The program's own time is a tick on linear ω, charged by id; each query is priced by the oracle time through the exchange. A certified handler then transfers the bound, and link_timed sits naturally as the bottom link. feat: bridges from interface charges to machines and backend cost #398 has the two PolyFun-side versions:

      • RefinesVia for machines;
      • RunsWithinUnder.executionCost_add_charge_le for quantitative realizations.

      A Forster–Kunze L backend would be another instance of that bottom link.

    4. Budgets. Your three fixed shapes all have a home:

      This matches the uniform-budget convention in feat: charge bounds for resumptions, dynamical computations, interaction trees and indexed programs #392's ImplementsWithinCharge and the "Bounds as contracts" notes in feat(pfunctor): interface charges and structural charge bounds on free programs #388.

    5. Caching. An exact path law (inner calls = new keys ≤ distinct queries) is a sharper form of feat(pfunctor): charge certificates, instrumented and gated handlers, handler transfer #391's amortized transfer, which gives target calls + |σ₀| ≤ |σ_final| on every completed path. An exact version (equality) would be a second potential lemma; we haven't stated it. The lazy random function as the cached run with fresh draws belongs on the probability side.

    What the generalization produced, from the WP side

    Every reading is an effect observation. Each cost notion in the stack is the fold wpFold Φ of a per-call specification Φ : OpSpec P L into an ordered carrier L. This is the free-monad case of "Dijkstra monads for all".

    Reading Per-call spec Φ a k Carrier
    budget IsChargeBound fun s => s + c a ≤ B ∧ ∀ b, k b (s + c a) ω → Prop
    worst-case cost c a + ⨆ b, k b ω
    answer-dependent budget (#397) fun s => ∀ b, s + e ⟨a, b⟩ ≤ B ∧ k b (…) ω → Prop
    roll bound / budget automaton fun σ => canRoll a σ ∧ ∀ b, k b (cost a σ) σ → Prop
    CallsIn S a ∈ S ∧ ∀ b, k b Prop
    expected cost (VCVio, ert) c a + 𝔼[k] over the handler's step σ → ℝ≥0∞

    Two laws hold for every reading:

    • Sequencing is exact (wpFold_bind).
    • Substitution is pullback (wpFold_liftM): folding over x.liftM h is folding the pulled-back spec over x, and pullback is functorial (OpSpec.pullback_pullback).

    Certified implementations are spec refinement. For the upper-bound readings, wpFold_liftM_le is the whole transfer theorem. If each implementation is observed below its call's spec (the per-call certificate, after the exchange), the simulated program is observed below the original. Composing certified handlers composes the refinements. The budget reading is the order dual, whose transfer is proved directly. The other cross-layer links have the same shape one level down:

    • RefinesVia says the machine's behaviour is the handled run, so its observation is the run's (isChargeBound_init_iff_denote);
    • the realization bridge adds the work the observation leaves free.

    Core vcgen. A reading that is a WPMonad gets core triples and vcgen:

    • the budget reading, whose triples are exactly charge bounds (isChargeBound_iff_triple);
    • the instrumented StateT reading, where under the demonic base a triple is a bound on every completed path;
    • ranked triples for abstract programs (triple_liftM_of_isChargeBound).

    In these terms, EasyCrypt's cost judgement is roughly a budget-reading triple with oracle-indexed ranks, and CatCrypt's XDijkstra / TimedM is the graded version of the same thing, which #393's Budgeted mirrors as a GradedMonad.

    How much existing work it covers

    • PolyFun's earlier notions:
      • IsRollBound is the general automaton, and charge bounds are its additive case;
      • the ℕ∞ OpSpec.charge fold and handlerCost generalize to any cost type;
      • isTotalRollBound_mapLens is now a corollary of a general IsRollBound.mapLens;
      • the other models (Resumption, DynComputation, ITree, IFreeM) inherit the readings by truncation or erasure.
    • VCVio:
      • the IsQueryBound family and #942's weighted budgets are instances;
      • #930's table growth is resource growth;
      • #1013's transfer is the completed-path calculus;
      • #1018's DeterminedCost and MeasuredProgram have PolyFun counterparts with the same API;
      • expectedSimulatedQueryCount is the expectation fold above.
    • CatCrypt:
      • your bridge plus the stack cover the oracle files;
      • Diller–Nahm Clocked is a CostedReduction;
      • TimedM corresponds to Budgeted;
      • the time certificates are certified links with ticks.
    • ArkLib:
      • arithmetic profiles are vector charges;
      • programAlong is the node-weighted path charge;
      • fresh-key costs are a trace valuation.
    • Benchmark statements (verified circuits and zkVM guests):
      • T-count is FreeM.cost;
      • RISC-V cycles are an instrumented run;
      • a certified step bound is ImplementsWithinCharge with the unit charge.

    Not covered yet

    • Parallel composition. There is no cost law under ⊗. A lax-interchange mixin fits work and peak space, but qubit width interchanges the other way.
    • Hidden machine steps. There is no block-simulation constructor for several hidden machine steps per call.
    • Oracle realizers. The realization bridge takes answering prices as a parameter.
    • Prefix-form amortization. It needs a shape fixed against VCVio's ElGamal proof.
    • VCVio's quantum query mass with its √-hybrid aggregate. It stays outside the notion.

    From the WP side, the natural next step is to state the refinement law once at the OpSpec level, as a square between a spec, its pullback and an exchange. Relational readings (comparing two layers' costs) and the expected reading, with a linear exchange, would then inherit transfer and composition without lemmas of their own.

  8. spitters commented on Nov 4, 2026

    @spitters
    Contributor

    On budgeted UC emulation as a client: CatCrypt-core has it in two forms.

    • Realization against time-bounded environments. RealizesTime X Y n o q tD quantifies over environments whose activations, per-activation costs, rounds and distinguisher are bounded (EnvTimeBound). Costed environment pullbacks carry these budgets through contexts: realizesTime_map (one hole), realizes_twoHole (two holes), realizes_seq_timed (cascade), with each reduced environment's budget growing by constants of the context; hybrids and adversary absorption in UCPullbackTimed; quantum versions in QPullbackCost.
    • Distances over budgeted distinguishers. Query-bounded (QueryBoundedUC), from any cost model (UCAdmClass_of_costModel), and time-bounded in a deep call-by-value language (ucCdistTime, with graded composition laws including the coproduct), plus the asymptotic form (UCTimeNegl).

    Parallel composition is non-expansive for the realization distance (UCCascadeEnrichedPar); a costed parallel instance of the two-hole law is the piece we have not stated, so a lax-interchange mixin in PolyFun would have a direct client here.

  9. spitters commented on Nov 4, 2026

    @spitters
    Contributor

    The bridge is up: OracleAdversaryFreeBridge.

    • toFreeM_bind: toFreeM (A.bind f) = (toFreeM A).bind (toFreeM ∘ f).
    • toFreeM_subst: toFreeM (subst impl A) = (toFreeM A).liftM (substHandler impl), where substHandler impl reissues sampling nodes and sends a query d to toFreeM (impl d).
    • toFreeM_simulate: toFreeM (simulate impl A s) = (simHandler impl).run (toFreeM A) s, with simHandler impl : Handler.Stateful _ S _.
    • isQueryBoundBy_iff_wpFold_charge, isQueryBound_iff_wpFold_charge: our per-query cost bounds are the OpSpec.charge fold of toFreeM A. At the PolyFun revision VCV-io pins, the non-indexed FreeM has no IsChargeBound, so these are stated through wpFold; they become IsChargeBound statements once feat(pfunctor): interface charges and structural charge bounds on free programs #388 lands.
  10. dtumad commented on Nov 4, 2026

    @dtumad
    CollaboratorAuthor

    I ran a dry run of VCVio adopting the stack, all local. VCVio main plus #1023 (reducible simulateQ) was built against the stack tip as a path dependency.

    Results

    • VCVio builds unchanged against the stack, with zero warnings.
    • 21 VCVio theorems were re-proved from the stack with their statements unchanged, taking 313 proof lines down to 95. 17 more delegate to those and are untouched. 8 were kept, each for a stated reason: import order, writer instrumentation, or no gain.
    • Bridges. IsTotalQueryBound, IsQueryBoundP, IsPerIndexQueryBound, and the online and point bounds are each an IsChargeBound, with a unit, indicator, Pi.single, pair or point charge. WorstCaseCostBound is a bound on the charge of every completed path.
    • Measured programs. #1018's MeasuredProgram is PolyFun's (feat(pfunctor): measured and budgeted programs #393) up to renaming spec to Ans. feat(pfunctor): measured and budgeted programs #393 now uses the same composite interface and the same argument order.
    • Expected cost. Expected target cost transfers through a handler from a per-call bound that holds for every call argument and every handler state, as Alex pointed out. The stateless case is an instance of wpFold_liftM_le, and the stateful case of the new wpFold_run_liftM_le.
    • ElGamal (#945). suffix_bound is plain run_liftM. prefix_bound needed a runner that can pause, with an amortized budget; that is the prefix-form item in the checklist.

    Fed back into the drafts

    A second pass, pointing VCVio at the amended lemmas, removed another 68 lines net (+36 −104). It also re-proved one of the kept theorems, IsTotalQueryBound.of_perIndex, in three lines. VCVio still builds against the new tip with no new warnings.

    Outside the stack

    • Concrete OracleComp goals needed PFunctor.Obj.mk passed to simp by hand, so simp lemmas for the projections of Obj.mk would help.
    • With PolyFun as a path dependency and its examples built, PolyFun's Examples module root collides with VCVio's Examples library. A git pin does not build a dependency's examples, so this is latent for now.

    The VCVio side is staged as three local branches:

    1. bridges and re-proofs;
    2. WorstCaseCostBound and measured programs;
    3. expected cost.

    They can open once the stack merges and VCVio bumps its pin, which Quang coordinates.

  11. spitters commented on Nov 5, 2026

    @spitters
    Contributor

    On IsChargeBound as the shared predicate: every costed tree kind in CatCrypt-core now has its time bound proved equivalent to a charge fold of its FreeM image, with the program's own step costs as tick calls.

    • Oracle adversaries and oracle programs: TimeBound ↔ IsRollBound ↔ the OpSpec.charge fold of the tick tree (OracleAdversaryFree, OracleProgTimedFree). In oracle programs the continuation cost depends on the answer; it becomes a tick after the answer, so the charge stays per call.
    • Quantum instruments and QROM circuits: the same equivalences (QTreeKindFree, QAdvTreeKindFree).
    • Probabilistic trees: the time bound at a sampling node ranges only over the support of its distribution, so it is not the charge fold over all answers. It is the fold of OpSpec.chargeUnder c allows, whose continuation is taken over the answers allows admits (chargeUnder_true recovers charge); see SPTree.Timed.timeBound_iff_wpFold_chargeUnder in SPTreeTimedFree.

    On Alex's first point: in these tick trees the code between calls is charged. The costed form R.timed of a reduction is derived from the reduction's term by derive_timed, each step carries the cost of the code it runs as a tick, and the erasure theorem R.erase_timed states that removing the ticks gives R itself. The time bound is therefore a statement about the named reduction R.

    Once #388 lands we plan to define these time bounds as charge bounds of the tick trees. For the probabilistic case this needs a budget reading restricted by an answer relation, s + c a ≤ B ∧ ∀ b, allows a b → k b (s + c a), the budget counterpart of demonicUnder. Would you consider an IsChargeBoundUnder (or an allows argument on OpSpec.budget) in #388?

  12. dtumad commented on Nov 5, 2026

    @dtumad
    CollaboratorAuthor

    The stack is ready for review. All ten PRs pass ./scripts/validate.sh --lint --test --axioms, and they are out of draft.

    Review order

    Review bottom-up. Each PR is based on the previous one:

    PR Purpose
    #388 Charges as lenses, IsChargeBound and its laws, the relation to IsRollBound, the transfer principles wpFold_liftM_le and wpFold_run_liftM_le
    #389 Worst-case cost, loops, support-restricted sequencing, cost_bound, CallsIn and MayCall
    #390 Charges of completed paths, the completed-path calculus and its exact substitution law
    #391 Charge certificates, instrumented (StateT and writer) and gated handlers, stateful and amortized transfer, pausing runs
    #392 Charge bounds for resumptions, dynamical computations, interaction trees and indexed programs
    #393 Measured and budgeted programs, aligned with VCVio #1018
    #394 Core vcgen for charge bounds
    #396 Certified handlers, costed reductions and stateful certificates along link
    #397 Answer-dependent charges and the watermark monoid
    #398 Bridges to machines (RefinesVia) and to quantitative realizations

    Added since the last comment

    Open follow-ups, for anyone to pick up

    • The exact stateful threading law. This is a Path.Threads predicate with exists_run_liftM_iff, the stateful counterpart of the substitution law (CatCrypt's mem_profile_simulate_iff). joinBind is in place for it.
    • An exact amortized law, for caching handlers whose target calls equal the new keys (CatCrypt's OracleCache).
    • Writer erasure for log-style writers ([EmptyCollection ω] [Append ω]). The monoid writer case is in feat(pfunctor): charge certificates, instrumented and gated handlers, handler transfer #391; this would let VCVio's simulateQ_run_writerT_of_step port.
    • Contract tests. Negative tests for reversed-order and max-plus cost types, and a note that scored products (qubits × T-count, bytes × cycles) are monotone images of componentwise bounds.
    • Larger items from the earlier comments:
      • oracle realizers for the realization bridge;
      • block simulation for hidden machine steps;
      • parallel composition through a lax-interchange mixin, whose first client is CatCrypt's costed two-hole UC law.

    Overlap with the probability layer

    PolyFun is adding an optional measure-theoretic library, PolyFunProbability, outside the PolyFun umbrella (#400; #401, #402, #403, #404, #405). PolyFun's boundary with VCVio moves from probability to cryptographic security.

    • The cost stack is probability-free and needs no changes for it.
    • Three bridges come after both lines merge, as one PR on top of both:
      • an expected charge, generalizing expectedQueryCount from path length to Path.charge, with its bound from IsChargeBound;
      • expected-cost transfer as an instance of wpFold_liftM_le / wpFold_run_liftM_le;
      • the AddSupDistrib ℝ≥0∞ instance for worst-case costs in ℝ≥0∞.

    Who might look at what

    VCVio's side stays local until the stack merges and VCVio bumps its PolyFun pin. It consists of bridges and re-proofs (21 theorems, 313 → 95 lines in the dry run), WorstCaseCostBound and measured programs, and expected cost.

  13. dtumad commented on Nov 5, 2026

    @dtumad
    CollaboratorAuthor

    Thanks, Bas. Yes, both go into the stack, with allows at the automaton level rather than only on the budget.

    • feat(pfunctor): interface charges and structural charge bounds on free programs #388. Restricted answers enter at the automaton level, so they cover roll bounds as well as charge bounds:

      • OpSpec.rollUnder canRoll cost allows and IsRollBoundUnder;
      • OpSpec.budgetUnder c B allows, which is your s + c a ≤ B ∧ ∀ b, allows a b → k b (s + c a), and IsChargeBoundUnder.

      With every answer allowed, these are IsRollBound and IsChargeBound (_true lemmas). isChargeBoundUnder_iff_isRollBoundUnder relates them, as isChargeBound_iff_isRollBound does now. The laws are monotonicity in allows, bind and map. A charge bound gives a bound under any restriction.

    • feat(pfunctor): worst-case cost, loops, support-restricted sequencing and cost_bound #389. OpSpec.chargeUnder c allows and costUnder, upstreamed from your PFunctorChargeUnder, with chargeUnder_true and the bridge from IsChargeBoundUnder to costUnder ≤ B.

    On the accounting boundary: derive_timed with erase_timed is the cleanest version of what Alex asked for. The time bound becomes a statement about the named reduction R, with the code between calls charged as ticks.

    On #380: I'll comment there on how #389 builds on its cost.

  14. spitters commented on Nov 5, 2026

    @spitters
    Contributor

    A proposal for dividing the work between the stack and CatCrypt's time certificates, in three stages.

    1. Instrumentation (CatCrypt). derive_timed and derive_reduction turn a reduction written as ordinary Lean code into a costed form and prove an erasure theorem: removing the ticks gives the reduction back. The stack has no counterpart, since its programs carry their charges from the start.
    2. Cost semantics (shared). Every costed tree kind in CatCrypt-core now has its time bound proved equal to a charge fold of its FreeM image, including steps, binds and AllRet (SPTreeTimedFree, OracleAdversaryFree). For probabilistic trees the fold is taken over the program restricted to the supports of its sampling nodes: PFunctor.restrict keeps the directions an answer relation admits, and wpFold_chargeUnder_eq_restrict makes the restricted fold a plain OpSpec.charge fold. This answers our earlier request for an answer-restricted IsChargeBound, so feat(pfunctor): interface charges and structural charge bounds on free programs #388 needs no change for it. Once feat(pfunctor): interface charges and structural charge bounds on free programs #388 lands we redefine these time bounds as IsChargeBound.
    3. Closing bounds (divided). cost_bound closes concrete programs over finite answer types. Our time_bound and derive_time_bound close bounds that stay symbolic in the adversary's time and query counts, over the same predicate. We are extending them to any goal of the form wpFold (charge c) x k ≤ B, including programs written directly in FreeM, and will pass concrete leaves to cost_bound.

    Two pieces are written so they could move into PolyFun: PFunctor.restrict with FreeM.wpFold_mapLens, and vector charges with handler composition (PFunctorChargeVec). The latter states the cost of a program run through a handler as composition with use counts, which is the Diller–Nahm composite (DNCert). We can open a PR for either if you want them in the stack.

  15. 5 remaining items

  16. dtumad commented on Nov 10, 2026

    @dtumad
    CollaboratorAuthor

    I rewrote the description for the state after phase 1.

    cc @alexanderlhicks @spitters @quangvdao

  17. quangvdao commented on Nov 10, 2026

    @quangvdao
    Collaborator

    A note on the quantum row of "Not covered".

    Query counts of quantum programs are already covered. In VCVio, QuantumComp.IsQueryBoundAt, IsQueryBound, IsTotalQueryBound and IsCostBound (VCVio/Quantum/Comp/QueryBound.lean, TotalQueryBound.lean) are instances of the indexed IFreeM.IsChargeBound, with a unit charge on calls of the selected port and a cost c o on local operations. Their bind and transfer lemmas come from the generic ones.

    What stays outside is query mass: an amplitude-weighted, state-dependent real quantity used in the square-root hybrid bound. It is not a function of the tree, so it is not a charge, and leaving it out is right.

    CatCrypt's QAdv m n w q fixes the count in the type, so it needs no bound. The proposal in lean-crypto-foundations/QuantumCrypto#2 takes general programs within a charge bound and maps them to a comb with exactly q calls. So the fixed q is the output of a normal-form theorem, and IsChargeBound is its hypothesis. Could the row say this, so the quantum case is listed as covered for counts and out of scope for mass?

  18. dtumad commented on Nov 10, 2026

    @dtumad
    CollaboratorAuthor

    Parked: #397 (answer-dependent charges and watermarks) and #398 (bridges from interface charges to machines and backend cost) are closed because neither has a consumer yet. Their branches feat/cost-observers and feat/cost-bridges stay. Revive them when a proof needs prices that depend on answers, or cost at the machine level.

  19. alexanderlhicks commented on Nov 17, 2026

    @alexanderlhicks
    Contributor

    An update from the ArkLib side, following the discussion above. Thanks for taking up most of the earlier points: the accounting-boundary section, the trivial-∃ test, the contract notes, the Katz–Lindell condition in the roadmap item on stateful expected-charge transfer, and the ArkLib-shaped tests. Since then we reviewed the resource work across PolyFun, VCVio, CompPoly, ArkLib and leanerVM, and prototyped the pieces that the review called for. The prototypes are local branches. Each passes its repository's validation on its own, and no combined downstream consumer has been validated yet. Claims marked "checked" are checked in Lean on these branches, and we will link them with the PRs. We will open the PRs once the owners here agree on the shapes.

    What the review found

    1. The existence of a polynomial bound says nothing about capped families. leanerVM's deployed straight-line extractor falls back to brute-force list decoding (protocol: the extractor is efficient only on codewords; list decoding with CompPoly's Gao and Guruswami–Sudan decoders leanerVM#157: about 2^1019 subsets at the smallest deployed size). Its parameters are capped, so some sufficiently large constant bound exists, and hence some polynomial bound. A specified numerical budget still constrains such a program. An asymptotic claim must also fix an honest size measure, a uniform family and a stated growth envelope. A concrete claim must fix numerical budgets.
    2. Existential extraction collapses again in ArkLib's new interaction core. Its classical straight-line knowledge soundness quantifies over the extractor and charges only adversary re-entries. With discrete measurable structures and a judgement valid only on accepted observations, it is equivalent to relation soundness (checked). The extractor must therefore stay named and its operations declared. Even then, a declared-operation contract does not establish efficient extraction.
    3. What we count is not always what runs. CompPoly compiles eval to Horner's method through @[csimp], while ArkLib charged the power-sum form (about n² multiplications) for FRI's extractor.
    4. Rewinding counts reruns, not the work in them. VCVio's IsFinder.cost bounds expected reruns. Multiplying it by an expected per-challenge cost is unsound for the IsFinder contract, because the finder chooses challenges after it sees the world (checked counterexample at error 0). The expectation over worlds of the largest per-challenge cost is sound.
    5. Still open across the stack:

    Prototypes (local branches; each passes its repository's validation)

    • PolyFun, sized contracts.
      • MeasuredProgram.CostWithin size envelope bounds every completed path of the program, run on each input's own view, by the envelope at that input's size. PolyCost and FamilyPolyCost are the polynomial forms.
      • The growth predicate is cslib's PolynomiallyBounded, used only in a separate Sized/Growth module. That module also refutes the polynomial forms from a super-polynomial lower bound on qualifying completed paths.
      • Paths range over every answer. A call returning an arbitrary natural-number answer, measured by its value at fixed input size, has no output-size envelope over all answers, so a composite after it can fail every polynomial cost envelope even when its run is cheap.
      • The restricted forms (CostWithinUnder, PolyCostUnder, …) bound only the paths whose answers an allows predicate admits. Restricted to Answered, they say exactly that the actual run meets the envelope (costWithinUnder_answered_iff). They compose along CompAllows, given the intermediate output-size bound and monotone outer envelopes. Polynomial envelopes have the required monotonicity.
      • An existential contract ∃ M, M.Realizes f ∧ M.PolyCost size holds for every f, so the evidence is a named program, and even that is accounting, not adequacy. There is no consumer yet.
    • VCVio, charged reruns. Each rerun is charged by the query cost of the computation that the caller supplies for it, so the caller supplies the complete interaction to charge both sides. A finder of cost T then has expected accumulated charge at most T times the expected largest rerun cost over the frozen world (checked).
    • CompPoly, one Horner definition for counting and running. Both @[csimp] targets of eval and eval₂ run one monadic definition, and evalHornerM_counting gives one read, one addition and one multiplication per coefficient. We raise it on tracking: formalize Reed–Solomon decoding and certified operation bounds in CompPoly CompPoly#377 first, where the primitive cost model is an open maintainer decision.
    • ArkLib, declared-operation accounting in the interaction core (stacked on Route interaction-core queries through shared owners and drop local transparency overrides ArkLib#1493). The legacy measured contract is ported, and FRI's legacy certificate transfers with the same budget. Relation soundness still gives this certificate at budget zero for the classical choice extractor (checked), so the efficiency and adequacy bridge remains open.

    Proposals for PolyFun

    1. Land the sized contracts (above), with cslib owning the growth predicate.
    2. A contract-grade cost predicate: canonically ordered counts, standard addition and order, and finitely many kinds (or →₀ budgets). Generic CostAtMost stays for laws. PolyFun already tests these failure modes (PolyFunTest/PFunctor/Charge/Basic.lean). A contract predicate would turn them into rejected instances, and ArkLib could then drop its local restrictions.
    3. Revive feat: bridges from interface charges to machines and backend cost #398 with consumers. FRI's measured extractor and leanerVM's decoder would be its first consumers. It takes an oracle realizer for each operation, priced by the realizer's proved cost, and an overhead bound in path length and encoded sizes. It gives one composed executionCost bound.
    4. Stateful expected-cost transfer in a follow-up to feat(probability): expectations and expected charges of free programs through the fold #445, before VCVio derives its expected notions from it. Separately, the PFunctor.FreeM.expectedQueryCount of feat(probability): measure and kernel semantics of free programs, and the security boundary #441 has the same full name as a VCVio declaration. VCVio's next PolyFun bump past feat(probability): measure and kernel semantics of free programs, and the security boundary #441 therefore needs a rename on one side.
    5. One MeasuredProgram. VCVio's has no non-test consumer inside VCVio. ArkLib uses it in 5 library files and 4 test files on main, so the unification lands together with an ArkLib repin.

    Open for discussion: multivariate size measures (security parameter, query count, field size) for CostWithin, and the form of leanerVM's extractor contract (Verified-zkEVM/leanerVM#157).

  20. spitters commented on Nov 17, 2026

    @spitters
    Contributor

    Two points of the review concern constructions that CatCrypt already has; both are on CatCrypt-core main.

    Counting what runs (point 3). derive_csimp f via S₁, …, Sₙ builds the runtime implementation f.csimpImpl from source theorems, proves f.csimpImpl = f and installs it with @[csimp]. It then derives the cost of f.csimpImpl and registers it as the cost of f, so a time certificate prices a call of f by the code the compiler emits, and the @[csimp] theorem justifies that price. When the cost derivation is refused, no cost is registered for f.

    Rewinding (point 4). forkExtractor_timed prices each retry of the fork at B, the certified time of one fork in the worst case over its runs, so the expected cost of the extractor is at most B / forkBound A x. A constant worst-case price per attempt is an instance of the sound form in the review, the expectation over worlds of the largest per-challenge cost.

    On point 2: CatCrypt's extractors and reductions are named definitions, each with a time certificate (the costed program, its erasure theorem and a time bound), and its security statements bound the advantage of every adversary by the advantages of these reductions.

    CatCrypt's cost and complexity work is summarized in Crypto/Complexity.md, which indexes the other documents, among them Container/README.md: costed programs as morphisms of the Diller–Nahm category, extractors as realizers of derivations, the expected cost of rewinding, and bound extraction from classical proofs.

  21. alexanderlhicks commented on Nov 17, 2026

    @alexanderlhicks
    Contributor

    Thanks, these are useful references, and both agree with the review.

    Point 3. derive_csimp applies the principle that the CompPoly prototype applies to one definition: price the replacement that the @[csimp] theorem installs. The prototype does this only for eval and eval₂. Both @[csimp] targets run one monadic Horner definition, and a counting instance of the same definition gives the count. derive_csimp is a general command. It proves that the replacement equals f, and when derive_cost succeeds on the replacement and f has no registered cost, it registers the replacement's cost for f. The equality theorem justifies the replacement. How closely the registered cost tracks execution depends on the cost model. As its module docstring says, the price applies only to callers compiled after the @[csimp] theorem. The primitive cost model for CompPoly is still open on Verified-zkEVM/CompPoly#377, and the cost model of derive_cost is a reference point for that decision.

    Point 4. Yes. A constant worst-case price per attempt bounds the largest per-challenge cost for every world, so forkExtractor_timed is an instance of the sound form. The VCVio form of this corollary is in Verified-zkEVM/VCVio#1166 (IsFinder.expectedCalls_bind_runCharged_le, and finder_bounds_charged_of_worstCaseCostBound at the attempt level). The two settings differ in one way that matters only for non-constant prices. forkExtractor retries a fixed fork at most N times, each retry with fresh randomness, and the bound B / forkBound A x holds for every N. VCVio's IsFinder lets the finder choose the next challenge vector after it sees the world. Under that contract, our counterexample (VCVioTest/RewindingCost.lean in that PR) shows that the expected per-challenge cost does not suffice. With a flat price B, both give B times the expected number of attempts.

    B covers both runs of the fork, each with the adversary, the verifier and the oracle simulation, plus the extraction step (extractReduction.timeBound_timed). The relation check checkW is not charged: B bounds extractReduction.timed, and forkAttemptTimed applies the check through CostComp.pure. The VCVio PR also leaves work outside its accounting. It charges the queries of the computation that the caller supplies for each rerun, and it does not charge local computation.

    Point 2. Agreed. What matters is that the same extractor satisfies knowledge soundness and the stated cost bound. An existential theorem can express efficiency when its witness also has an adequate execution-cost certificate. CatCrypt's explicit programs, erasure theorems and cost bounds in a stated cost model are useful examples. The ArkLib prototype keeps the extractor named, but it counts declared operations only. It does not yet establish executable extraction within a runtime bound.

  22. dtumad commented on Nov 17, 2026

    @dtumad
    CollaboratorAuthor

    I'd also just flag that once v4.36 settles we can also hopefully get core's vcgen to prove most simple query count bounds

  23. alexanderlhicks commented on Nov 17, 2026

    @alexanderlhicks
    Contributor

    that would be nice! Once things are stable we should also be able to add tactics as needed more generally.

  24. spitters commented on Nov 18, 2026

    @spitters
    Contributor

    @dtumad, on vcgen and query counts: CatCrypt-core's XDijkstra kernel relates the counter form to the graded form. costBoundedEquiv identifies the programs into the graded monad CostM σ n with the programs of the tick-counting state monad TickM σ of cost at most n, and xmvcgen! reduces a grade bound to arithmetic (example). After 4.36 we plan a WPMonad instance for TickM, so that vcgen proves the counter bound and costBoundedEquiv transfers it to the graded one.

  25. spitters commented on Nov 18, 2026

    @spitters
    Contributor

    Thanks, Alex. The relation check is now charged: each attempt pays tChk for deciding P.rel x w, and forkExtractor_timed bounds the expected cost by (B + tChk) / forkBound A x.

  26. alexanderlhicks commented on Nov 18, 2026

    @alexanderlhicks
    Contributor

    Two corrections to my update above, and a tracker.

    The remaining work is tracked in Verified-zkEVM/ArkLib#1528. Two questions for the maintainers here:

    1. Should the contract-grade cost predicate (proposal 2) and the single MeasuredProgram (proposal 5) go ahead in PolyFun and VCVio? The predicate would require finite total cost under natural-number counting. It would not require finite oracle input domains.
    2. Should the bridge from charges to execution cost land under PolyFunFrontier: the cslib-frontier side of PolyFun #425 (L1–L3), or as a revived feat: bridges from interface charges to machines and backend cost #398?
  27. spitters commented on Nov 19, 2026

    @spitters
    Contributor

    Thanks, Alex. On your second question, from our side:

    On the first question, a contract-grade predicate that requires finite total cost under natural-number counting fits our use: the summary functor of #497 and CatCrypt's tick-counting monad both count in ℕ.

  28. dtumad commented on Nov 21, 2026

    @dtumad
    CollaboratorAuthor

    Thanks, Alex and Bas. Answers to both questions:

    1. Contracts and MeasuredProgram. Yes to both, and to the sized contracts:

    Stateful expected-cost transfer (your proposal 4) merged as #486, and VCVio's PolyFun pin now includes it.

    2. The bridge. We'll follow Bas's split. We'll revive the realization layer of #398 (ExecutionTrace.charge, RunsWithin.isChargeBound and RunsWithinUnder.executionCost_add_charge_le) as a fresh PR on current main, with #499 and FRI's extractor as its consumers. It gives the concrete execution cost of a run from its charges, relative to a backend; #511 is the asymptotic counterpart on the frontier side and does not go through charges. Oracle realizers priced by their proved cost, with an overhead in path length and encoded sizes, go on top. Machine classes and adequacy stay in #425, and RefinesVia waits for a machine-level user. Composition laws of quantitative realizations are #505.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requesttrackingRoadmap or tracking issue for a body of work

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions