Repository navigation
Conversion checks syntactic identity before normalizing (#1071) - #1075
Giulio2002 wants to merge 6 commits into
Conversation
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
a good follow-up would be unfolding. this is also in lean-4 so I think it is worth having. lmk if you want a follow-up |
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
I increase the cap |
|
this is kinda a blocker for me. |
The root laws of Transaction, ExecutionPayload, BeaconBlockBody, BeaconBlock and SignedBeaconBlock prove their 2^30-byte limit fact symbolically (big_lim_sym.bend, big_lim_bl.bend) and build the containers' closed facts from symbolic introduction lemmas (okI_*), so every closed comparison is between syntactically identical terms. They live in proofs/obj/big_root_*.bend and check with bendlang/bend#1075 (big_root_all.bend: 332 s, 3.9 GB). codegen/root_laws_b.py --no-big writes no big_* file. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks for this, it fixes two cases I had written down. Measured on this branch (33dba28) against main (11c65a2),
In the first, both sides are the same call, and main normalizes both before comparing. As far as I can tell, the fold's import Base
def pc(~leaf: @+x: U32 -> @+y: U32 -> U32, j: Nat, +i: U32, +seed: U32, acc: U32) -> U32:
match j:
case 0n:
acc
case 1n++p:
pc(~leaf, p, i, seed, U32.max(acc, leaf(U32.add(i, U32.from_nat(p)), seed)))
law r:
for ~leaf: @+x: U32 -> @+y: U32 -> U32
for +i: U32
for +seed: U32
{pc(~leaf, 20n, i, seed, 0) == pc(~leaf, 20n, i, seed, 0) : U32}
def r(leaf, i, seed):
{==}Here in case it's useful as a test. |
term_same only checked its budget on a pair of distinct nodes, so once the counter passed zero on a pointer-identical pair it never stopped: the walk went on unbounded and, since it follows share cells, it unfolded a shared term (a def body instantiated with one argument cell used many times) into a tree exponentially larger than the graph. pcont.pc_00001_mk in bend-ssz walked 50M+ node pairs over ~1600 distinct nodes and never finished. The loop now stops at the budget and answers unknown unless the stack is empty. Co-Authored-By: Claude Opus 5.5 <[email protected]>
e764f45 to
bdb251f
Compare
|
most LoC are benches |
hashes_4 is the use case: four laws under(root(ws), L) == under(root(ws), L), root a 64-round hash over 16 words and L a list limit between 2^20 and 2^30, the shape a proof about hashing code reaches after a rewrite. main evaluates both roots of every law (6.1 s on a Linux server); identity answers at once. shared_4 is the regression the walk's budget guards against: dag(d, z) == wrap(d, z) at the four depths (30, 32, 38, 40) where the first version's walk passed its budget on a shared pair and did not finish. Both sides are one shared graph whose tree has 2^d nodes. Pins: both 0.070s, best of 5 on an Apple M4; the other rows are unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Tested the merge-base Update, Sep 26: We cherry-picked all five commits onto released Bend 2.0.29 ( Reproducers, environment, and traceClosed-bound case: Replacing both Addition regression: The All comparisons use isolated checkouts, the same source and launcher, a 16 MiB JSC stack, and an OS soft stack limit of 32 MiB. FTL is the only disabled tier in the workaround: ulimit -S -s 32768
BEND_NO_TELEMETRY=1 BUN_JSC_maxPerThreadStackUsage=16777216 \
BUN_JSC_useFTLJIT=false bun bend2/main.ts /absolute/path/repro.bendThe first parent/head comparison isolates the PR commits. The later 2.0.29 cherry-pick tests the released base, which diverged from the PR branch. These are limited local checks, not a soundness audit. |
|
I can reproduce similar performance benchmarks. This is a very good addition! |
…lang/bend#1075) Replaces the congruence step of bend-compare-congruence.patch, which compared arguments without a budget and walked shared terms as trees (BEND-061). The BEND-052 regression, the proof gate and a full CLI check pass.
|
Thank you. We decided not to change conversion for this (#1071, closed): the checker recurses on the machine stack, and some large terms will overflow it. WONTFIX.txt: "The checker is not optimal: some terms are exponential or overflow (#993)". Note: an AI wrote this reply after I made the decision. If anything here is wrong, reply and I will review it myself. |
I will reply, if this got closed because it is not a common case, then I'd like to disagree with this. you will encounter this very specific pattern (even with non huge terms) almost everywhere and most of the time, the terms are trivially equal. this does not only 100x that one specific case, that one specific case is for the benchmark and tractability, it is esotheric because it has to be. this PR overall 2-3x pretty much all of the projects i built check-time wise because this is a very common pattern, maybe not at extremely huge terms like the tree hashing library, but it does hurt even when we are talking about moderately big. even #993 was opened not because of the specific example that the user put out, but that specific example, in particular is likely not what he is encountering. it is something to open the issue with, he is likely doing something much less esotheric and more resembling of everyday life Here is another practical example that helps a lot which is not as esotherical: group arithmetic. by definition most of the terms will have to be large so in that usecase it is 2-3x. not 100x. I think that the "these 2 are trivially equal" so they should be merged is very much a common case because it is the case when most proofs actually check. example: I see this pattern in field and group proofs too: generated obligations repeatedly refer to the same arithmetic calls while checking representations, bounds, and proof certificates. The shortcut doesn’t prove the nontrivial algebraic steps. it avoids normalizing identical subterms along the way. On a BLS fp2_fermat proof, with the fast path backported went from 108.4 s / 2.23 GB to 42.5 s / 1.59 GB. bend-collections also proves in 3x less time now with it. |
|
I can mantain this myself by the way, I do not particularly care if this gets merged, but I think this decision is very odd as it is effectivelly just an optimization all-round in practice and not just a patch on an exponential case. (it will be a pain but oh well this is what OSS is for :)), anyways one extra detail is that some proofs are 1:1 ports from their lean counterparts. |
|
sorry, @Giulio2002 called my attention on this as my verdict seems wrong. I'm very busy with a lot of things and there are endless PRs, so it is really hard to give attention to each. sorry about that. I'll re-open this and reserve some time later to address this matter |
|
no problem. i just found it odd |
… call U32.min, U32.max, F32.min, F32.max, F32.lerp, F32.square, F32.hypot, Char.to_upper, Char.to_lower, the divisor of U32.div and U32.mod, and List.sort now match their argument before they copy it. Before, each copied a stuck argument first and unfolded to a term that held it twice (max: Bool.pick(U32, is_lt(a, b), b, a)), so n nested calls became 2^n terms for conversion to walk. Now a stuck argument stops the def at its match, and n nested calls stay n calls. On #1075's fold, a 16-step instance checks in 0.09 s (was 2.37 s); proven by {==}, 0.09 s (was 0.98 s). Nat.mul, Nat.pow and U32.pow keep their shape: their copies are the unfolded value, as in Agda (tests/stuck/mul.bend). The JS lane now folds the rebuild of a value its match opened: a binder takes a U32's or F32's word (u32_to_word) or a Char's code (codePointAt) as written, and the constructor folds it back to the name (VIEW, view_of). On a probe that calls each def, the JS is the same and clang -O2 emits the same machine code as before. WONTFIX's #993 entry now bans conversion layers that make equality quadratic (an identity pass before each reduction) or every check slower (hash-consing, a memo), with the rationale, and points to the representation fix. tests/stuck/max.bend pins the stuck form. Gates: repo 47/47, ping 34/34, test 1498/1498, perf 117/117. ttok: base.bend 27363 -> 27618, comp.ts 63393 -> 63573. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Ok, for what I can tell, my verdict wasn't wrong, but I need to explain myself here, and we also need a solution to the actual issue you observed. First, seems like you're proposing a two-pass equality, which first checks if both terms are identical (without reducing), and only then reduces, in case that fails. This is how Kind worked 5 years ago, and I decided against it. The reason is that this would either make equality quadratic (if you do a nested linear pass), or the entire checker significantly slower by a huge constant (if you hash-cons both sides). Capping the pass, as this PR does at 4096 visits, just trades one problem for the other: every comparison pays up to that cap, and larger terms fall through anyway. And it would not solve the problem in the general / worst case, because large constants would still take a lot of time to check when both sides don't match. For example, F(100000 * 2) == F(100000 + 100000) will still unroll fully (it overflows on both main and this PR). To be very clear: this problem is not solvable in the worst case. Not on Bend, not on any other proof assistant. At best, we can add layers and layers of complexity, all the way to e-graphs, attempting to cover more and more cases, but not all. And each complexity layer you add will make the checker slower. Similar lines of thinking made Lean slow, and I take these as a mistake. Instead, Bend chooses to keep the checker simple and fast. But then, how do you address the issue reported here? In the user-side representation. The root issue, it seems, is that your code copies a value before it inspects it. In aldeni's example, U32.max(acc, x) unfolded to Bool.pick(U32, U32.is_lt(acc, x), x, acc), so a stuck acc appeared twice. After n steps, it was a graph of n shared nodes, which conversion walks as a tree of 2^n. And this PR didn't fix that family: prove the same instance with {==} instead of the generic lemma, and the sides no longer match as text, so it still grew exponentially (at 18 steps: 5.05s on main, 2.0s with the PR). In this specific case, the bad representation was actually our fault: Base's U32.max copied its arguments before it opened them. I fixed that on main (b2111cf): U32.min/max, F32.min/max/lerp/square/hypot, Char.to_upper/to_lower, U32.div/mod and List.sort now match their argument first, so a stuck argument stays one call. aldeni's 20-step case now checks in 0.08s (it was 41s), with no change to the checker. If you still hit a slow check, ask your AI to apply a similar fix on your side: keep large constants and depths abstract in your laws, and write every def that copies an argument to match it first, so a stuck argument stops it. For example, write libs and proofs on Word, NOT for Word<32n>. If that still fails, i.e., if you face some real-world situation where the checker is exponential and there isn't an easy representation fix on your code that addresses it, re-open this issue with a minimal counter-example. That will be very helpful to me. |
Proofs generated by bend-ssz pass evidence for ok_X(s, dv) where the expected type is its body, Bool.and(A, B). The two sides meet as the same calls only one unfold down, and B contains a check over 2^13 roots, so a conversion that asks the identity question only at the top normalizes both copies of it (the BeaconState root overflowed the stack). - Every step of a conversion asks whether both sides are the same term, written the same way, as bendlang#1075 did; variables match by level, and equalities, datatypes, refl and absurd are walked like bendlang#1075's check. - A walk first checks that both calls have the same head and arity (no allocation), then compares the arguments first to last, and records the calls it found different, so a failed walk is never repeated as the conversion descends: no quadratic cost, no cap. - The sharing record, the Nat shortcut and the per-comparison context are unchanged. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…1071, PR #1151 by Giulio2002) Checker (bend2/bend.ts): term_compare first runs the existing comparison (now compare_go) with RIGID, one empty book, so no def unfolds and every call stays stuck; the App case then matches two copies of one call by head and arguments. Only if that pass fails does the comparison run as before. The recursion goes through compare_go, so the pass runs once per conversion: no new walk, no cap, no memo. Giulio2002 found the case (#1071, #1075, #1151 and his Merkle gist): a law proven by induction, agree(d, x), used at a fixed size, agree(32n, x), walked a shared chain of 32 nodes as a tree of 2^32 when both copies of root_loop(32n, x) unfolded. It now checks in 0.09 s (was > 20 s). Tests: conversion_copy_before_unfold (the Merkle law at 32n) and conversion_def_named_like_object_key (a def named toString). Gates: tests 1509/1509, repo 49/49, --verdict parity on tests 969 agree, 0 false rejects, 0 timeouts. bench/checker on the minis: trees -0.4%, compute -18.5%, defs -2.9%, proofs -4.9%, generics -1.6%. bend.ts +104 ttok. CHANGELOG.md and VERSION name 2.0.33; the notes also cover the fixes since 2.0.32. Co-Authored-By: Giulio2002 <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
…check; dead tests removed Audit round 3, items 4 and W10. - docs/TRUST.md: bendlang/bend#1075 was closed without being merged on 2026-09-27; its five commits are not on Bend's main. Says what that means: every result rests on a conversion shortcut upstream did not accept, and "checks" means "checks under 3ddfb036" until the proofs are ported (proof-side rewrites, never checker patches). docs/BUILD.md points there. - tools/verify_frozen.py: the lock's sha256 is not in README; the full-check stamp records it. - codegen/tool_generators.py --check (run by regen_all.py --check and strictcheck): reruns the 62 reproducible tools/generate_*.py in a scratch copy and fails if one writes nothing, exits nonzero or writes a file that differs from the committed one (a planted edit to proofs/root_total.bend is caught). The six others are classified in ONE_SHOT with the reason. - tests/: 13 of the 15 Bun tests imported types/fulu*.bend, which the runtime compiler cannot compile as an entry, so none had run; removed with their helpers (primitive_backend.ts, generic_transport.ts), the dead test_transport.py and probe_backend.py. The live ones (sha256, layout, test_run_evidence) move to tests/; run_runtime_tests.py takes BUN and BEND_RUNTIME and runs every tests/**/*.test.ts by default: 3/3 tests, 2,694 assertions on the ssz server. docs/BUILD.md documents the tests and why types/fulu*.bend check only as imports. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…check; dead tests removed Audit round 3, items 4 and W10. - docs/TRUST.md: bendlang/bend#1075 was closed without being merged on 2026-09-27; its five commits are not on Bend's main. Says what that means: every result rests on a conversion shortcut upstream did not accept, and "checks" means "checks under 3ddfb036" until the proofs are ported (proof-side rewrites, never checker patches). docs/BUILD.md points there. - tools/verify_frozen.py: the lock's sha256 is not in README; the full-check stamp records it. - codegen/tool_generators.py --check (run by regen_all.py --check and strictcheck): reruns the 62 reproducible tools/generate_*.py in a scratch copy and fails if one writes nothing, exits nonzero or writes a file that differs from the committed one (a planted edit to proofs/root_total.bend is caught). The six others are classified in ONE_SHOT with the reason. - tests/: 13 of the 15 Bun tests imported types/fulu*.bend, which the runtime compiler cannot compile as an entry, so none had run; removed with their helpers (primitive_backend.ts, generic_transport.ts), the dead test_transport.py and probe_backend.py. The live ones (sha256, layout, test_run_evidence) move to tests/; run_runtime_tests.py takes BUN and BEND_RUNTIME and runs every tests/**/*.test.ts by default: 3/3 tests, 2,694 assertions on the ssz server. docs/BUILD.md documents the tests and why types/fulu*.bend check only as imports. Co-Authored-By: Claude Opus 5.5 <[email protected]>

Fixes #1071.
Disclosure: I wrote this change with Claude Code (an AI coding agent).
AGENTS.mdasks thatbend2/bend.tsbe written by humans, so feel free to close this and write it yourselves. The patch is short, and the tests and measurements below still apply.Change
Before
term_comparenormalizes both sides, it checks whether they are syntactically identical. The check forces share cells, unfolds nothing, visits heads and first arguments first, and stops after 4096 visits, counting a shared node at every visit. Identical terms are convertible, so the check only ever answers "equal". If it finds a difference or runs out of visits, the comparison runs exactly as before. It only runs when a side is a call (ApporRef), because values already compare structurally at the same cost.gates/repo.ts: thebend.tscap goes from 44000 to 45000 ttok, since the file is 44444 after this change. #996 and 942573f raised it the same way.Lean 4's kernel does the same:
is_def_eqstarts withquick_is_def_eq, which first asksequiv_managerwhether the two terms are structurally equal, before any reduction (src/kernel/type_checker.cpp,src/kernel/equiv_manager.cpp).Budget fix (bdb251f)
The first version tested the budget only on pairs of distinct nodes. When visit 4096 was a pointer-identical pair, the counter went past zero and was never tested again, so the walk had no limit. On a term with much sharing, where the tree is exponentially larger than the graph, it did not finish. The loop now stops at the budget, and the answer is "equal" only when the walk completed.
tests/check/conversion_same_before_whnf.bendhas a case that hung before this commit.Checker benches (3ddfb03)
Two small benches in
bench/checker, pinned forapple_m4at 0.070 s each (best of 5 on an M4):hashes_4(37 lines), the use case: four laws from the generator below.shared_4(27 lines), the regression:dag(d, z) == wrap(d, z)at the four depths where the first version's walk did not finish.Linux server, one run each, startup included.
Benchmark: proofs about code that hashes
The generator below (in the collapsed block) writes N laws of the shape
{under(root(ws), L) == under(root(ws), L)}. Hererootis a 64-round hash over 16 words, andLis a list limit between 2^20 and 2^30. That is the shape a proof about hashing code reaches after a rewrite: both sides compute the same root of the same fixed data.mainevaluates both roots for every law. With this PR, the two sides are recognized as identical and nothing is evaluated.Control: a law equating the roots of two word lists that differ in one word fails on both, with the same error.
gen.py (
python3 gen.py N 64 > bench.bend)Case study: a verified SSZ library
SSZ ("Simple Serialize") is how Ethereum encodes its consensus data (blocks, validator records, the chain state) as bytes. It also defines how every such value hashes to a 32-byte "root": the data is split into 32-byte chunks and hashed pairwise with SHA-256 into a Merkle tree. Nodes compare these roots to agree on the state.
We wrote an SSZ library in Bend, with proofs that its encoder, decoder and root function match an independent transcription of the specification. It has about 300 proof modules. Many laws say "the root the code computes is the root the spec defines". Proving them means comparing terms that both contain the same hash computations over fixed data, such as the precomputed roots of empty subtrees and the SHA-256 constants. They also contain large protocol limits, for example 2^30 bytes for a transaction.
On
main, each such comparison evaluates the hash, or expands the limit in unary. Some of these checks overflow the stack, and others take minutes and gigabytes. With this PR, the SHA-256 correctness gate of the library (the runtime SHA-256 equals the FIPS 180-4 specification) goes from 7.97 s / 474 MB to 0.85 s / 253 MB.