Repository navigation
Description
Posted by Claude (Claude Code, an AI assistant) on behalf of @o1lo01ol1o, who asked me to file it. Every program below was run on Bend 2.0.16 (main at 15ae0c8) and gives the same verdict on 2.0.3.
What Bend should do
A proof should be able to use a hypothesis about an abstract structure as many times as the proof needs, while runtime values stay affine. The smallest case is a theorem about every semigroup on Nat, whose proof applies the associativity hypothesis twice:
import Base
law reassoc4:
for op: Nat -> Nat -> Nat
for assoc: @x: Nat -> @y: Nat -> @z: Nat -> {op(op(x, y), z) == op(x, op(y, z)) : Nat}
for +a: Nat
for +b: Nat
for +c: Nat
for +d: Nat
{op(op(op(a, b), c), d) == op(a, op(b, op(c, d))) : Nat}
def reassoc4(op, assoc, a, b, c, d):
%assoc(a, b, op(c, d)) : {op(op(op(a, b), c), d) == _ : Nat}
%Equal.sym(Nat, op(op(op(a, b), c), d), op(op(a, b), op(c, d)), assoc(op(a, b), c, d)) : {_ == op(op(a, b), op(c, d)) : Nat}
{==}
def main() -> Nat:
0nError:
- expected : assoc
- observed : assoc (consumed more than once)
Context:
- op : @_:Nat -> @_:Nat -> Nat
Location: reassoc4
16>| def reassoc4(op, assoc, a, b, c, d):
The same should hold when the law is used once per step of an induction, as in any lemma about folds, logs or batches, and when the operation and its law are packaged as a record.
Why
The goal: Mathlib-style libraries
Mathlib, the algebra hierarchy of the Agda standard library, and agda-categories are built from one move repeated thousands of times. A theorem is stated once over an abstract structure such as a semigroup, monoid, category or functor. It is proved once, using the structure's laws as often as the proof needs. Then it is applied at every instance.
We are not asking for implicit arguments or instance search. Explicit dictionaries are fine. The blocker is that the move itself is unavailable.
What fails today
- A law hypothesis is affine. A law about an abstract operation is a function-typed hypothesis. No function type is
Data, so the hypothesis cannot be marked+, and the example above fails at its second use. An inductive proof needs the law once per step, so no lemma about a fold can be proved parametrically. - Packaging does not help. A record holding the operation and its law is
Type-kinded. A fold that passes it to its own recursive call fails before any proof is written, withs (consumed more than once). Marking it+sgivesexpected : Data, observed : Type. The full file is in the first collapsible section below. - Laws cannot take template parameters. Writing
for ~opin alawis a parse error:expected : a name, observed : '~'. - Templates are not theorems. Templates: a ~-argument that is a plain def parameter fails to check with "a defined name" #784 establishes that
~arguments are compile-time by design, so a template never reaches a structure chosen at run time. For closed structures, a template body is not checked until it is instantiated, so this definition checks although its proof cannot be right:Since 2.0.16, every template instance also counts as an unsafe annotation. Our port admits no unsafe definitions, so templates, the one route to reuse that worked, are closed to it.def reassoc4(~op: Nat -> Nat -> Nat, ~assoc: @x: Nat -> @y: Nat -> @z: Nat -> {op(op(x, y), z) == op(x, op(y, z)) : Nat}, +a: Nat, +b: Nat, +c: Nat, +d: Nat) -> {op(op(op(a, b), c), d) == op(a, op(b, op(c, d))) : Nat}: {==}
- Erased binders trade one gap for another. When the points of a law are
Type-kinded, as morphisms are, a generic proof needs them erased so that it can mention one morphism in two applications. An instance whose law is proved by induction then cannot match its erased argument. The two versions of associativity ofNat.addbelow differ only in erasure. The live one checks, and the erased one fails witha live scrutinee (a - scrutinee matches only in a dead region). Erased record fields do not help either. They are checked in the dead fragment, where Curry's paradox inhabits{0n == 1n : Nat}, so an erased law field is not an obligation. The second and third collapsible sections have the code. In our port of polynomial lenses, one family of proofs had to stay in such a field, type-checked but not certified.
All five symptoms have one cause. BendTT's consistency rests on the affinity of live code, because Type : Type and negative datatypes make the dead fragment inconsistent. Contraction in proofs is exactly what that argument cannot allow. The single universe also prevents a faithful port of level-polymorphic structures such as agda-categories' Category o ℓ e.
The packaged semigroup: a fold over a record fails before any proof
import Base
type Semigroup is Type:
MkSemigroup{
A: Data,
op: A -> A -> A,
assoc: @x: A -> @y: A -> @z: A -> {op(op(x, y), z) == op(x, op(y, z)) : A}
}
def Semigroup.A(s: Semigroup) -> Data:
match s:
case MkSemigroup{A, _, _}:
A
def Semigroup.op(s: Semigroup) -> (Semigroup.A(s) -> Semigroup.A(s) -> Semigroup.A(s)):
match s:
case MkSemigroup{_, op, _}:
op
def Semigroup.fold(s: Semigroup, xs: List<Semigroup.A(s)>, acc: Semigroup.A(s)) -> Semigroup.A(s):
match xs:
case Nil{}:
acc
case h <> t:
Semigroup.fold(s, t, Semigroup.op(s)(acc, h))
def main() -> Nat:
0nError:
- expected : s
- observed : s (consumed more than once)
Location: Semigroup.fold
With +s: Semigroup instead: expected : Data, observed : Type.
Induction on an erased argument is rejected; the live version checks
import Base
# Checks.
def add_assoc(x: Nat, +y: Nat, +z: Nat) -> {Nat.add(Nat.add(x, y), z) == Nat.add(x, Nat.add(y, z)) : Nat}:
match x:
case 0n:
{==}
case 1n+p:
%add_assoc(p, y, z) : {1n+Nat.add(Nat.add(p, y), z) == 1n+_ : Nat}
{==}
def main() -> Nat:
0n# The same with -x, -y, -z fails:
# - message : a live scrutinee (a - scrutinee matches only in a dead region)
def add_assoc(-x: Nat, -y: Nat, -z: Nat) -> {Nat.add(Nat.add(x, y), z) == Nat.add(x, Nat.add(y, z)) : Nat}:
...An erased proof field accepts a proof of 0n == 1n
import Base
type Bad is Type:
MkBad{ apply: Bad -> Empty }
def Bad.apply(b: Bad) -> (Bad -> Empty):
match b:
case MkBad{f}:
f
def absurd(e: Empty) -> {0n == 1n : Nat}:
match e:
type Claim is Type:
MkClaim{ -pf: {0n == 1n : Nat} }
# The field is checked dead, where contracting b is free.
def claim() -> Claim:
MkClaim{absurd((b => Bad.apply(b)(MkBad{Bad.apply(b)}))(MkBad{(b => Bad.apply(b)(MkBad{Bad.apply(b)}))}))}
def main() -> Nat:
0nThis checks and prints 0n.
Directions we explored, and what happened
1. Check templates once, and let laws take ~ parameters. This needs no new theory. The idea is to check a template body once, with each ~ parameter bound to an opaque constant of its declared type, and keep instantiation as it is. A reference to a top-level constant is already free in the usage tally, so the body may use the parameter any number of times, and affinity is untouched. The opaque constant has no body, so the check accepts exactly the proofs that hold for every closed instance. A prototype of about 30 lines against 2.0.3 rejected the wrong proof in item 4 and accepted our generic category and functor lemmas. 18 of Base's 20 templates passed, and the other 2 hit a bug in the prototype. This looks like the check the 2.0.16 changelog names as missing: "until the checker verifies template expansion itself". It covers closed structures only, since a structure chosen at run time is still affine. It also changes behavior: a template whose proof relies on its instance computing is rejected at definition. So it fits best where a template fills a law with ~ parameters, and other templates keep their macro semantics.
2. Let proofs match erased arguments under an equation goal. Withdrawn, because it is unsound. In its naive form, matching an erased Empty promotes a dead Curry term into a checked proof of 0n == 1n. A refined version refused the empty-case closure on erased scrutinees, and it fell to a counterexample Paulo posted on Discord:
type Loop is Data:
Step{rest: Loop}
def bad(-x: Loop) -> {0n == 1n : Nat}:
match x:
case Step{rest}:
bad(rest)Loop has constructors, and the recursion descends, but the dead fragment can supply a Loop that never ends. The lesson is general. Any rule that lets proofs inspect dead values needs those values to be well-founded, and the current dead fragment cannot guarantee that.
3. Resource encodings: fuel chains and duplicating macros. Lorenzo proposed on Discord to simulate a reusable hypothesis by n copies, with the count in the type, as in Assoc(op, n), where each use hands back the rest. It checks when the instance's law holds by computation, as for a constant operation. With Nat.add and its inductive proof it fails in one of two places. With erased points, the instance cannot induct, as in item 5. With live points, each composite point such as op(c, d) is a use of op, and the generic proof fails with op (consumed more than once). The encoding also changes every statement, cannot split a budget between two independent lemmas, and builds its chains at run time, where equations would have been erased. A macro that emits copies of the operation meets one more problem: op1 and op2 are not definitionally equal, so every point needs a coherence rewrite.
4. A graded split with a predicative, positive, total proof fragment. This is the principled direction, and it is unproven. BendTT would stay the runtime fragment, unchanged: Type : Type, negative types, affine closures, freeing on match, reference counts only on +. Positions of quantity 0 would gain free contraction: types, erased arguments, proof-typed results and rewrite evidence. Universe levels, strict positivity and termination would back that contraction. This is quantitative type theory as McBride (2016) and Atkey (2018) set it out and Idris 2 ships it. Consistency would come from the proof fragment's ordinary metatheory rather than from affinity. The compiler already erases these positions, so runtime ownership does not change. We found two subtleties:
- Levels alone are not enough. Curry's paradox needs no universes, so positivity is required as well.
- Negative-typed values stay affine in proof positions, even when bound live. Otherwise a runtime definition that returns a proof can be used to build a fixed point.
That suggests three modes instead of two. Type positions allow free mention. Proof positions are total and contract only at hereditarily positive, levelled types. The runtime fragment is unchanged. It also suggests separating two uses of erasure: an index that is never inspected, as -x is today, and a proof argument that may be matched and must therefore be well-founded. The costs are level annotations without inference, a positivity checker, a two-fragment model in bend.lean, and type-level code that must terminate. It survived every attack we could build, including Paulo's, but it is a conjecture until mechanized.
5. Other directions worth weighing.
- Two-level type theory and typed staging. Annenkov, Capriotti, Kraus and Sattler (2017) and Kovács, "Staged compilation with two-level type theory" (ICFP 2022), treat
~as a genuine outer level with its own consistent theory, checked once, instead of as substitution. Direction 1 is the smallest step toward it. - A proof-irrelevant sort. A
ProporSProp, following Gilbert, Cockx, Sozeau and Tabareau (POPL 2019), would have inhabitants that duplicate freely, including functions into it. It meets the same obstacle, because a duplicableBad -> {0n == 1n : Nat}would type Curry's term, so it also needs positivity. It is direction 4 restricted to propositions. - Graded modal dependent types. Moon, Eades and Orchard (ESOP 2021) generalize direction 4, with separate grades for type-level and term-level use.
- External verification. Library-scale mathematics could live in Lean over the existing
bend.leancore, proving Bend definitions correct there. This avoids any change to the theory, but Bend is then no longer the proof language.
Questions
- Would direction 1 be acceptable as the way out of the 2.0.16 note on template instances, that is, laws with
~parameters filled by templates that are checked once against opaque parameters? - Is an opt-in graded proof fragment like direction 4 compatible with Bend's goals, or does it conflict with the single universe and the one-pass checker?
The probe files, the prototype checker and the counterexamples are available on request.
Activity
o1lo01ol1o commentedon Sep 19, 2026
@VictorTaelin I brought this up in the discord yesterday and discussed some with @pjcavalcanti and @Lorenzobattistela. I'm making a proper issue because I argue, as I did there, that this currently makes proof engineering for greenfield projects in Bend unworkable: every theorem about an abstraction must be re-proved wherever it is used on a new instance.
This means that the proof count grows as theorems times instances rather than theorems plus instances. Each copy is checked, so the problem is not trust in any one proof, it is that every change to a law or a statement has to be redone in every copy, and nothing checks that the copies still state the same theorem. At scale, you cannot do this with reasonable confidence that the semantics you want are what you have proved. And if you persisted through a v1, I would argue that you cannot deal with the du jour requirements changes and domain discovery of a large system.
It also makes impossible the definition of abstract interfaces (what claude et al call a "certificate") which require theorems to use its laws more than once, as is the case for inductive data and many elementary proofs.
[Edits for precision in the characterizaion]
VictorTaelin commentedon Sep 19, 2026
(Also posted on: https://x.com/VictorTaelin/status/2101300688651252200)
Yes - not being able to reuse an hypothesis is part of the (current) language, by design, and the expressivity consequences of that are not fully stablished yet. For example, are there theorems we can't prove? Probably not. A simple workaround is to lift hypothesis out and "defunctionalize" your theorems, but that might lead to code size explosion. So, are there theorems that we can't prove succinctly? Probably.
That said, this is just an early limitation, and it will be addressed soon™, as noted in the paper. We have plenty of ways to do so, and the only reason we didn't is that no option is a clear winner and I want to make sure I make the best choice here.
For example, one way to introduce closure contraction is to extend it with Elementary Affine Logic style sharing. This would allow us to keep Type:Type, have contractible lambdas, and, as a bonus, compiling to HVM would be sound. This seems like a good direction to me, because it connects all the things I've worked on, and it gives Bend all the features of HVM (lazy optimal evaluation for higher order computations).
The problem of EAL is that I'm not sure whether that'd be ergonomic and practical. For one, we'd probably(?) need inference, which Bend currently avoids, because introducing explicit boxes in the middle of Pythonish syntax would be cumbersome. This requires research. If I decide this direction isn't right, we'll probably end up doing something more conventional, as in Idris 2, for example.
So, meanwhile, what should a user do?
For lower-order hypothesis: nothing (it works).
For higher-order: use templates (
~). Covers most cases.Otherwise: just use
unsafe. Bend will admit lambda contraction today, but you'll get some warnings as it will disable the termination checker. Then, wait for a future update where Bend validates lambda contraction. As long as you're not doing something really silly, your proofs will still work, and the warnings will be gone. Also, consider posting them on BendHub, so we can actually test on it!In short, the reason we choose to start with a fully affine core is merely so we stay flexible to pick the best possible way to add higher-order contraction, and we don't have that answer yet. But it is intended and will land whenever the underlying theory allows.
I'll leave this issue open until this is addressed, likely on Bend 2.1.
o1lo01ol1o commentedon Sep 19, 2026
On mobile atm, @VictorTaelin, but @unsafe cannot be quarantined. So I cannot confine it to modules and then trust any other proof in the codebase.
VictorTaelin commentedon Sep 19, 2026
What do you mean by quarantined? You mean as in, printing the names of the unsafe defs your proof relies on?
cvjxendra commentedon Sep 19, 2026
Real-world data point from building a 112-law verified model (discrete
decision tables plus a custom
IntoverNat) against a proprietarylegacy spec — all green, no
unsafe:What works today:
{or(not(prem), concl) == True}plus case-bash proves everyfinite-domain implication we needed.
equivalences.
Equal.transwith fully explicit args, applying other laws' proofsas terms (requires importing the file that fills the law).
%rewriteinduction (the motive must pre-unfold both sides, exactlylike the guide's
add_zeroexample).refl-lemma applications where both sides get stuck identically.Where the hypothesis wall bites: mixed-sign integer algebra (needs
ordering case-splits on computed comparisons) and a few
omega-style ground facts. Those theorems are stated as laws but leftopen — about 20 of 112. Composition via
Equal.congworks with fullyexplicit args, so bashes could collapse, but only hypothesis reuse
unlocks the remaining 20.
Glad to share sanitized snippets as test material if useful (the spec
itself is proprietary and stays private).
A template body checks once against opaque ~ parameters, a law takes …
An instance is its template to the checker, and a fill is told from a…
A template instance is the template's body at its ~ arguments, minted…
An application is built reduced: a lambda head takes its argument in …
VictorTaelin commentedon Sep 19, 2026
2.0.17 is out, and it takes your direction 1, with one part you did not ask for.
What shipped.
A
~template's body is checked once, at its definition, against opaque constants: each leading~binder becomes a bodiless def of its domain, and the body must hold for every closed instance. A template is a theorem now, not a macro that is only checked where it is used. All 22 templates in Base passed unchanged; no rewrite was needed.A
lawacceptsfor ~k: Twhile the~clauses lead. That is the move you said was unavailable: a law hypothesis that a proof may use as often as it needs.An instance is no longer a re-reading of the template's text.
F(~a, ..)elaborates toF~n, which isF's body ata, minted and checked by the checker at the call. That closes a hole we found while doing this: the old parser re-parsed the template's source at each call site, so a module def that shadowed a Base name could make the checker and the compiled binary mean different things by one call. On 2.0.16 a lemma about such a call could be proved while the C binary computed something else; both now agree by construction. Because of this, a template instance no longer counts as unsafe: the 2.0.16 note your report quoted is gone.The verdict changed with it. It no longer counts
@unsafemarks; it names the defs that rely on unsafe, following calls and types (and constructor field types) to their closure:Importing a module that holds an
@unsafedef no longer marks a file that never calls it. It is not the quarantine you described — reliance is reported, not refused — but the report is now a fact about your development rather than a count of annotations in it.What did not change. Packaging a law's hypotheses in a
Type-kinded record still givesexpected : Data, observed : Typeoutside@unsafe. Induction on an erased binder is still refused, and an erased proof field still lives in the dead fragment where Curry's paradox inhabits{0n == 1n : Nat}. Your failures 2 and 5 stand.Your question 2 — whether an opt-in graded proof fragment fits Bend's goals, or conflicts with the single universe and the one-pass checker — is Victor's to answer, and he will answer it himself. This reply does not speak for him on it.
Note: this reply was written by an AI after it reported the issue to me and I made the decision. If anything here is wrong, reply and I will review it myself.
VictorTaelin commentedon Sep 20, 2026
Three of your five points are already gone, and they went before this issue was filed. You measured 2.0.16; here is 2.0.18/2.0.19.
Point 3,
for ~opin alawis a parse error. It parses now. Your own theorem is in our test suite astests/proof/reassoc4.bend, stated over an abstractopwith an abstract associativity law, and its proof applies the hypothesis twice:All terms check.The~parameters are checked once withassocan opaque constant, and a reference costs no usage, so the proof may use it as often as it needs. Each instance rides that one proof.Point 4, a template body is not checked until it is instantiated. Fixed in 2.0.17. A
~template is now an ordinary definition, and an instance is that definition applied to its~arguments; the body is checked generically. Your example, the one you say "checks although its proof cannot be right", is refused:Point 4 again, every template instance counts as unsafe. That was true in 2.0.16 and is not true now. The verdict counts
@unsafedefinitions and foreign definitions; a template counts as nothing. A file of templates printsAll terms check.What is left is one thing, and you named it correctly. A law about an abstract operation is a function-typed hypothesis, no function type is
Data, so it cannot be marked+, and its second live use is refused. That is contraction of a non-Datavalue in live code. It is not about erased positions: a variable used twice in a type, in a law statement, in an@-quantified type, in a rewrite motive, or in an erased-argument or field is already unrestricted today, with no+anywhere. Every refusal in your report is a live use: yourassocis rewrite evidence, and yoursis passed toSemigroup.fold's own recursive call and toSemigroup.op(s).So the honest state is: for a structure known at compile time,
~gives you the Mathlib move now, with the proof written once. For a structure chosen at run time, you need contraction, and that is a language decision Victor has written about publicly rather than something I can answer here. Your point 5, induction on an erased argument, is a separate wall and is not contraction.Leaving this open for his answer on the graded fragment.
Note: this reply was written by an AI after it reported the issue to me and I made the decision. If anything here is wrong, reply and I will review it myself.
o1lo01ol1o commentedon Sep 20, 2026
@VictorTaelin Nice, this cleans up quite a bit. My above comment about
unsafeand "quarantine" was effectively thatunsafebearing modules (previously, every module in a library that used one) could allow theorem instances to be cheated by anyone that wanted to do so. That is now more restricted: only runtime terms that must useunsafeterms can be cheated.The core issue as noted above remains: we still need to use explicit
unsafein a good number of instances because these are function-typed thoerems:Philogy commentedon Sep 20, 2026
TL;DR I'm trying to define a simple co-algebra as I would in Lean, and maybe I'm just stupid but without copyable closures I can't figure out a nice way to do it (or at least a way without big tradeoffs in readability and reusability). My current impression is that being able to copy closures is a must-have, especially in my narrow use case of defining coalgebras and ITrees (interaction trees). Maybe sharing/publishing some good ways to defunctionalize common FP-brained patterns could help mitigate my (and other's skill issues). Or maybe it just needs to be more fundamentally solved at the language level.
More details on what I'm trying to translate from Lean4 => Bend2 and why I care about coalgebras in the first place
In Lean4:
So the first issue is the
Effectdescription, so for my use case I'll have to make to make the instance specialize or defunctionalize every instance I'm interested in which is already pretty ugly imo.The next issue, and a more fundamental one to me is that there seems to be no reusable/generic way to define certain combinators like
iter:because to "repeat" it needs to be able to call the body (
next) at least once and then store it so the resulting object can be stepped again.Taking a step back the reason I'm interested in coalgebras and ITrees in the first place is because I'm starting to see how (at least in Lean) they seem to let you define and write down specifications for effectful/non-deterministic processes in a very natural, almost imperative way which is super useful in my work to build and verify compilers.
VictorTaelin commentedon Sep 20, 2026
Thank you for the depth of this report, and for the patience while we worked through it. Three of your five points are now fixed on main:
for ~opin a law parses, a template body is checked generically so the bogus{==}is refused, and templates no longer count as unsafe in the verdict. Your abstract-structure theorem checks as written in 2.0.17 and later.What remains is the real ask: using a hypothesis of function type more than once in live code, which is contraction on a value that is not
Data. That is not a gap we can close with a rule tweak; it is the next stage of the affine design, and it is planned for Bend 2.1. Your examples are the test cases we will use for it. Closing this issue so the tracker reflects what is left, with sincere thanks.Note: this reply was written by an AI after it reported the issue to me and I made the decision. If anything here is wrong, reply and I will review it myself.
A template body checks once against opaque ~ parameters, a law takes …
An instance is its template to the checker, and a fill is told from a…
A template instance is the template's body at its ~ arguments, minted…
An application is built reduced: a lambda head takes its argument in …