Repository navigation
Season 2 leaders (2/3): the rollup leader's stack - #2
Merged
Merged
Conversation
Only enable the existing MSM scheduling hint for witness wire commitments. Equal scalars multiply aggregated base points, preserving commitment group elements, transcript ordering and randomness consumption. Leave inverse commitments unchanged. (cherry picked from commit 85ee5510f567517560327e451b056f517696b1c3)
Mechanical delta from accepted Ilyas AVM hint submission enable-duplicate-scalar-msm-hints-for-av-738e5e to the exact t165 screened source tree fdae2c47cdd57887b7d4f21abae9af5cfd218481. Retain full78: Oleh's original final2 collection, all 73 production mails, reviewed integration/parser/compiler/tuple/CPU corrections, and bounded reciprocal division. Add reviewed Sol PCS scratch elimination, equal-extent reuse and bounded inverse row scheduling. The accepted advisory hint is already present in the ancestor. No further algorithms are added here. Original authored mails, hashes and source review records remain preserved under client-research/chonk-golf/sources/final2, research/astra-cumulative, and research/sol-avm-inverse-scheduling. Upstream original collection: https://github.com/olehmisar/chonk-golf/tree/da701932463498f56fe784f9a105da52cf0cf742/sources/final2 Screen evidence is diagnostic. Full proof identity, original tests, all timing guards and memory qualification remain required. Co-authored-by: opt <a@b> Co-authored-by: bench <bench@local> Co-authored-by: Sol research <sol-research@local> Co-authored-by: IlyasRidhuan <ilyasridhuan@gmail.com> (cherry picked from commit 66d2b3ce8729b5950b00be7817ee57383d0ffee6)
The constant-product/nonconstant-addends branch only needs the product remainder, and a reduction retry discards the tentative quotient entirely. Compute the unchanged product-plus-add divmod only in its consuming branch. Preserve all reductions, witness and gate insertion, tags and RNG calls. (cherry picked from commit 729496e3697be094cde168ed83923ece7e5035fb)
Paired checked point addition/subtraction evaluates two slope divisions with the same denominator. Keep both complete bigfield division and gate emission paths in their original order, but share an opaque caller-owned native inverse cache, keyed by the reduced denominator. Other callers retain the uncached default and custom coordinate field types retain the original interface. Cache state never contains circuit witnesses. A hit reuses the exact inverse produced from the identical canonical integer key. All numerator reductions, field products, quotient bounds, constraints, tags and witness ordering remain. Zero denominators keep the old branch and recursive denominator reduction rechecks the key. No global state, randomness or protocol changes. A focused typed test compares cached and uncached raw builder witnesses, ordered trace blocks, copy indices and circuit validity for repeated and changed keys, plus the unchecked constant-zero case. Original paired biggroup tests remain the integration check. No runtime gain claimed. Inspired by Halo2 assigned rational host evaluation (Zcash Halo2, MIT/Apache-2.0), adapted only as exact local native inverse reuse. No external implementation code copied. Original source research t125. https://github.com/zcash/halo2/blob/3442dd33754ae0d44b8970e5a4eea79b0c3360bf/halo2_proofs/src/plonk/assigned.rs (cherry picked from commit 0c38e219029803a92a22d41462784c87bfaaf9bb)
Port Astra t360 selected-result lookup materialization to native rollup. Sol prepared this native-only port. Keep every native table lookup, normalization, witness, gate and origin-tag operation unchanged. Single-result and Keccak endpoint callers avoid three complete vectors of field_t wrappers. Preserve the original WASM execution branches. No measured native gain claim. (cherry picked from commit cb0807cd944722e07bda51987c37f3dfca2702ca)
For x below2^508 use a255-bit reciprocal and two256-bit extended products to estimate the quotient, followed by at most one correction. Return the exact original quotient/remainder; retain inherited576-bit and full-width paths for every other input. WASM execution unchanged. Extend existing numeric boundary oracle for the added interval. No measured whole-rollup gain claim. (cherry picked from commit ea7397ea530dd1f7c1b9f3201dfe3a80cae83556)
Validate dense one-key and rectangular two-key layouts from actual field columns. Resolve bounded integer keys directly and verify all output columns by the original field equality. Other layouts, pre-existing maps, large key aliases and failed direct membership use the original complete map path after joining all direct workers. No table identifiers or circuit identifiers participate in admission. Dense keys are unique, so the resolved row is identical to the original map. Duplicate and sparse tables retain the original last-row semantics. Keep integer count accumulation, trace offsets and final field additions unchanged. No witness/gate ordering, randomness or transcript changes. This removes map nodes, insertion hashes, per-query key field conversions and lookup hashes for verified tables. Existing Straus constant-point and uint AND/XOR producers have these layouts; coverage fraction is unknown. The Root lookup read-count phase is 3.40s of 45.46s, not a measured gain. (cherry picked from commit 4b25ea2bb7a5b5cf6805b216c781ec79eb37d13e)
Actual native production-flag codegen for DenseLookupIndex shows full Montgomery conversions for literal field zero/one. In particular, the second-column reset is inside every single-key validation row, despite being mathematically zero. Width detection also constructs zero in its loop. Use the existing raw-represented field factories instead. All field limbs, sequence increments, comparisons, admission conditions, query membership, fallback and final read-count updates are unchanged. No new state, runtime branch, allocation, protocol or witness changes. This is independent of sparse-count histogram removal. Actual constructor codegen and raw read-count checks must confirm the removal before timing. No whole-proof speedup or cause of noisy TxMerge changes is claimed. (cherry picked from commit 10c0a362d5beb947f60650ba170106e47fa33d23)
Keep the existing dense validator and direct lookup unchanged. After a non-dense table or a joined direct-query failure, use the reviewed compact row index for empty supported caches; prepopulated/unsupported maps retain original initialize/query behavior. Reuse one caller-owned slot buffer. The RowIndex helper is byte-identical to the standalone compact-map source (original mail44bc2da7), adapted only at the fallback integration boundary. Every query is rerun after direct failure, retaining aliases and duplicate last-row semantics. Histograms, tags, table offsets and field writes unchanged. No circuit detection, protocol/RNG changes or new ISA. Shared native/WASM source; native-only components cannot qualify other runtime paths. Keep the original dense, field-factory correction and compact alternatives as separate historical mails. This additive hybrid is not measured yet. (cherry picked from commit b2fd3ad9d44efdfc133bae6423e3eaed3cb499c3)
Mechanical application of the unchanged reviewed 0081 source delta onto the checked lookup hybrid. Original raw patch and provenance remain preserved; no new algorithm changes. (cherry picked from commit 6d3545125bc7b02523c52ce5bf829c9ab5d1de84)
Use a bounded histogram when an integer range list has at least as many values as alphabet entries. Preserve duplicates and the exact ascending uint32 sequence before the original witness/tag/gate emission. Keep the existing serial or parallel comparison-sort fallback for small, large- alphabet or out-of-range inputs. Counts use size_t, with at most 65536 counters and no persistent builder state or circuit/input identifiers. (cherry picked from commit c4ccb5308f0eb79092e0f2a53270a100db5a37ca)
Fresh sub-limbs already have exact uint64 values before Fr witness creation. Admit them from those values without an immediate Fr-to-native round trip. Keep arbitrary public witnesses on their original check path. Specialize one registration body for an empty witness-source tag or a native uint64 source. The public entry point delegates before creating field temporaries, permitting a tail call instead of retaining an aligned wrapper frame across an outlined registration call. Do not force the large body inline at the two limb sites. All failure/tag/list/gate order and the original public API remain unchanged. (cherry picked from commit 95c558744fc1c65bc2d6fb946611f43e88a0fecd)
For balanced batches with at least two large members, enough total point work and at least eight CPUs, run up to four independent jobs instead of serially running every large MSM at full width. Each job owns its arena and sets its TLS concurrency before creating its existing per-caller pool. The sum of job widths is no greater than the original CPU width. Largest-first queue order limits the tail; results retain their original vector indices. GLV preparation is completed before jobs and its immutable views are shared. The canonical arena sizer uses the same external GLV, hint and thread cap as the actual kernel. A16GiB aggregate canonical-arena admission cap is not an expected memory consumption or RSS bound: stack/sort/GLV overhead remains. New std::thread callers avoid reentering the parent's TLS pool. They join before return; their TLS pools are destroyed when the jobs finish. Thread startup, private allocation, GLV setup and cleanup must be included in tests. Caller stats parent is propagated as with the existing pool. No transcript, RNG, field/curve arithmetic or scalar/point input data changes are introduced. Existing wide AVM concurrency and small-member dispatch remain. Repeated or partially overlapping large scalar spans retain sequential processing because the kernel temporarily converts/restores scalar backing in place. Shared immutable SRS views may overlap. WASM,32-bit and no-multithreading builds keep their original route. Unbalanced, small or arena-ineligible batches retain sequential dispatch. Thread creation failure uses any created jobs to drain the queue, or original sequential kernels if no job starts. No new ISA or architecture-specific kernel is introduced. This is a memory-for-parallelism experiment, not an extrapolation from older Gemini/Oink batching that retained sequential large members. Whole-proof upside0–4percent is theoretical; cache contention and setup can regress. (cherry picked from commit 85a4beb8573ed91f1b82f4f097adfb70dfae0133)
Precompute matrix-transposed subrelation weights once per round. Reuse the existing prover batching dispatch and preserve original relation accumulation and WASM paths. Combine weighted linear terms before selector multiplication. (cherry picked from commit 6cc74d6064e9b752c0fd2857769180224de9cba5)
Conversion multiplies by raw one, so start from the existing four-word input and perform only the four fixed Montgomery reduction rounds. This removes the structural zero input products without introducing an operand-dependent early exit. Canonical reduction remains unchanged. Limit the runtime kernel to native128 four-word small moduli. Preserve constexpr, WASM, no128, large and one-word field conversion paths, and all general field multiplication. Preserve the constant-time arithmetic contract; random/mixed and actual range consumers must still be measured. (cherry picked from commit 68679f630d042d1de9139cbc71da021149093e45)
A fixed-base cycle_group batch_mul over n points asks the offset generator store for n + 1 generators; the in-circuit IPA verifier asks for 32768. The store derived every block with the serial Group::derive_generators, one hash_to_curve per index, and re-derived the prefix it already held, so that request ran more than 32768 hash_to_curve calls on one thread. Generator i depends only on the domain separator and i. Expose that per-index derivation from group (hash_domain_separator and derive_generator), use it in derive_generators, and have the store copy the generators it already holds and derive only the new indices with parallel_for, each into its own preallocated slot. Outputs are unchanged: derive_generator builds the same 64-byte preimage (domain hash, big-endian 32-bit index, zero padding) and calls the same hash_to_curve, so every point is bit-identical, and the copied prefix was derived from the same domain and indices. Each slot is written once by a pure function, so the block does not depend on the thread count or on scheduling. derive_generators keeps its signature and results for every other caller. (cherry picked from commit d4993c577b071a6bd018b7a424a8fd878f8a2460)
The native Straus loops in cycle_group's variable-base and plookup fixed-base batch_mul track the offset generators folded into the accumulator by adding offset generator j + 1 to a native accumulator after every point of every round. Each round adds the same points, so the plookup path over 32767 points with 8-bit windows spent about a million projective additions recomputing one sum 32 times. Compute that sum once and add it once per round, after the same doublings as before. Outputs are unchanged: the accumulator is a native value read only once, as the affine offset_generator_delta returned to batch_mul, and it is the same group element (2^w * previous + sum) in every round, since the projective addition and doubling formulas used here handle infinity and equal points. The hint transcript and every gate are untouched. (cherry picked from commit 2a36b0ce8f1d1308c444b622ab7ecb5ab0611dab)
…_mul The plookup fixed-base batch_mul computes every intermediate Straus accumulator natively and converts them to affine hints; for the in-circuit IPA verifier that is about 1.05M points (32767 points x 32 rounds, plus the doublings). Three parts of that were wasteful: - the projective transcript (about 100 MB) grew by reallocation; it is now reserved at its exact size; - each affine table entry was promoted to projective and added with the general addition; it is now added with the mixed addition; - one serial batch normalization over all points was followed by a serial copy into the hint vector; normalization now runs in chunks under parallel_for_heuristic, one batched inversion per chunk, and each chunk writes its own affine hints. Outputs are unchanged. The mixed addition is the general addition with Z2 = 1 and takes the same branches: it doubles equal points, returns infinity for opposite points, and copies or keeps the finite operand when the other is at infinity. When both are at infinity it keeps the table entry instead of re-encoding infinity; a table entry at infinity was produced by self_set_infinity and normalized, so it carries the same (x, y) and the hint is the same. Normalization maps each point to its unique affine coordinates and treats infinity per point, so chunk boundaries, and with them the thread count, never change a hint value. Every gate and every builder call is unchanged. The accumulation itself stays serial: parallelizing it needs a per-round prefix scan that doubles the group operations, which loses on one or two threads. Applies on top of the commit that adds the summed offset generators once per Straus round, which edits the same loop. (cherry picked from commit 60ae0eec190e5e6f2e2c44ccfc96cab50467fb86)
IPA::create_random_valid_ipa_claim_and_proof draws a random polynomial and evaluation point and then proves that opening. Split it into IPA::sample_random_opening, which makes the draws (optionally from a given engine), and IPA::create_valid_ipa_claim_and_proof, which proves a given opening; create_random_valid_ipa_claim_and_proof now calls one after the other. RollupIO gains an add_default overload that takes the opening, and add_default(builder) draws it with sample_random_opening. This lets a caller draw the opening before it builds the circuit, or make the draws without proving at all. Behaviour is unchanged: the same values are drawn from the same engine in the same order (the transcript, commitment key and default pairing points that now follow the draws draw nothing), and the same gates and witnesses are added to the builder in the same order. (cherry picked from commit 69a8c909fef041f342a25db8fb6754a646c5805e)
…redicate Outside write-VK mode, every Honk recursion constraint built a one-gate circuit, constructed its prover instance and VK and ran the Ultra prover (for RollupIO also committing to and proving a random 2^15-coefficient IPA opening). The resulting proof and VK are read only in write-VK mode, which takes another branch, or when the predicate is a witness. With a constant predicate all of that work was thrown away. Skip it in that case for non-ZK flavors, but keep its random draws, since later draws become witness values. draw_arbitrary_circuit_randomness makes every draw the construction uses (three gate values, one value per ACIR public input, then for RollupIO the IPA polynomial and evaluation point), and construct_arbitrary_valid_honk_proof_and_vk and the new discard_arbitrary_valid_honk_proof_randomness both draw only through it. A non-ZK prover, its prover instance, VK and commitment keys draw nothing (challenges come from the transcript), so the engine ends in the same state and every later witness, and hence the proof, is unchanged. ZK flavors keep the full construction: their provers draw masking values, some on worker threads. construct_arbitrary_valid_honk_proof_and_vk takes an optional engine so that a test can check, with the resettable debug engine, that discarding draws exactly what construction draws and that construction depends on no other randomness. Depends on IPA::sample_random_opening and on the RollupIO::add_default overload that takes the IPA opening. (cherry picked from commit 052e920278b01dabe16ba7735d89080d0126f169)
slice_input_using_variable_bases splits every plookup key into the slices of its multitable. Each digit took `target % base` and then `target /= base`: two uint256_t divisions, each four 128-by-64-bit divisions even when the dividend fits in one limb. divmod_in_place returns the remainder and the quotient of one division: a mask and a shift when the base is a power of two (all SHA-256 tables except the choose output, and the uint, blake2s and fixed-base tables), one native 64-bit division once the remaining key fits in a limb, and one uint256_t::divmod(uint64_t) otherwise. A SHA-256 compression slices about 2,900 key digits. Outputs are unchanged: for every base b > 0 and integer t, quotient and remainder are the unique q, r with t = q*b + r and 0 <= r < b, which is what both versions compute (for b = 2^k with k <= 63, r is the low k bits of the lowest limb and q is t >> k; a dividend below b gives q = 0, r = t). The range check that throws on an oversized last slice runs before the division as it did, and a zero base still reaches uint256_t::divmod, which rejects it with the same message. The new test compares the slices with the two-division reference for every multitable's slice sizes and for edge bases (1, 784, 2^63, 2^64 - 1, 2^63 + 1), on zero, the largest representable key, random keys of every bit length, and checks that the first unrepresentable key still throws. (cherry picked from commit 364b55f9de8726ca44601ca7e1e88620433dee2c)
get_lookup_accumulators collected the raw slice values of each column in three temporary vectors that grew one element at a time, appended the lookup entries to an unreserved vector, and only then sized the three accumulator columns and copied the raw values back. A 16-slice SHA-256 choose-output lookup paid about twenty allocations for this, with regrowth copies of the 128-byte lookup entries. The raw values are now written straight into the accumulator columns, sized once, and the backward pass turns them into accumulators in place; the lookup entries vector is reserved to its final size. This leaves one allocation per returned vector. Outputs are unchanged. Each column element receives the same raw value as before (the same fr(uint64_t) conversion and the same conditional expressions), the last element keeps its raw value, and the pass computes lookup[i - 1] = raw[i - 1] + lookup[i] * step[i] with the same operands in the same order: when step i runs, element i - 1 still holds its raw value and element i already holds its accumulator. The lookup entries are the same values in the same order. (cherry picked from commit 3cc3c3ba80dcfcdcf573540ca59d757da70e0c44)
create_gates_from_plookup_accumulators appends one witness index per basic lookup to each of the three ReadData<uint32_t> columns it returns. The columns started empty, so a 16-slice lookup reallocated each of them five times; they are now reserved to the number of basic lookups, one allocation each. Outputs are unchanged: reserve only sets capacity. The same indices are pushed in the same order, and no gate, variable or lookup entry depends on a vector's capacity. (cherry picked from commit bd92ed2e959d67f88d45cc22fcc31c4470c54a4f)
The SHA-256 gadget reads three accumulator rows of each SHA256_CH_INPUT and SHA256_MAJ_INPUT lookup and eight of each SHA256_WITNESS_INPUT lookup, but it called plookup_read::get_lookup_accumulators, which wraps every row of every column in a field_t, in three vectors that grow one element at a time. These lookups run twice per round and once per message-schedule word: about 180 times per compression. plookup_read::read_rows_from_table<N> returns lookup[columns[i]][rows[i]] for the requested cells only. It reuses read_selected_lookup_rows, whose row selector becomes an explicit row index (LAST_LOOKUP_ROW keeps the last-row selection of read_first_and_last_from_table). That helper is now compiled for WASM as well because the gadget calls it on every platform; the existing wrappers keep their WASM branches. Outputs are unchanged. read_selected_lookup_rows performs the same builder operations as get_lookup_accumulators, in the same order: the same native accumulators, the same constant-key and key-normalization handling, the same create_gates_from_plookup_accumulators call, hence the same gates, variables and lookup entries. Each returned wrapper is built exactly as the full read builds the wrapper at that position (same witness index or constant, same merged origin tag), and constructing wrappers does not touch the builder. The new test runs both reads on equal builders, with a witness key given as a non-normalized affine expression and with a constant key, and requires equal values, witness indices, variables, gate counts and exported circuits. (cherry picked from commit 41a7499d2dca9b053f20f769b94faafd56376546)
create_gates_from_plookup_accumulators looked up the basic table and converted its table_index to a field element (a Montgomery multiplication) for every basic lookup, although consecutive basic lookups of a multitable usually use the same table: SHA-256 choose output uses one table for all 16 slices, majority and message-schedule output for all 11. A compression's 2,900 lookup gates come from about 700 runs of equal ids. The loop now calls get_table and computes the q_3 selector only when the basic table id differs from the previous one, and passes the selector to append_lookup_gate, the body of create_lookup_gate with q_3 supplied by the caller. create_lookup_gate keeps its signature and computes FF(table.table_index) as before. Outputs are unchanged. A skipped get_table call has the same id as the previous call in the same loop, which returned the first table with that id and left one in place; nothing between the two calls adds a table (variables, gate rows and lookup entries only), so the skipped call would have returned the same table and created none. Table creation order, and so every table_index, is unchanged, and q_3 is the same conversion of the same table's unchanged table_index. Gate rows, variables and lookup entries are appended in the same order with the same values. No functional dependency on earlier commits; the diff context assumes the reserve calls added by the commit that reserves the witness index columns of a lookup read. (cherry picked from commit 02b7327c7e4bdfe5a186d2c4a5e49e50c14a6675)
map_into_sparse_form tested all 32 bit positions of its input and added base^i for each set bit. It computes the values of every sparse lookup table query (the SHA-256 choose, majority and message-schedule input tables, AES, keccak input), one or two calls per basic lookup, about 1,600 calls per SHA-256 compression, and every row when such a table is built. Lookup keys are table slices of at most 14 bits, so most iterations were wasted and the data-dependent branch mispredicted often. The loop now walks the set bits of the low 32 bits with countr_zero, clearing the lowest set bit each step. Outputs are unchanged: it adds base_powers[i] for exactly the set bits i < 32 of the input, in increasing order of i, which is the sequence of uint256_t additions the 32-step loop performed (bits 32 and up were ignored and are masked off). The function stays constexpr. The new test compares it with the bitwise loop for bases 3, 9, 11, 16 and 28 on zero, every single bit, all ones, inputs with high bits set and random inputs, and checks a value at compile time. (cherry picked from commit 30f3b3f76b63138b07360d1e7cc05e529e702ff2)
create_valid_ipa_claim_and_proof commits to the polynomial to build the claim witness, then compute_opening_proof committed to it again to seed the transcript. Add overloads of add_claim_to_hash_buffer and compute_opening_proof that take the commitment, and use them there. The transcript, and so the proof, is unchanged. Applies on top of the commit that splits create_random_valid_ipa_claim_and_proof into sample_random_opening and create_valid_ipa_claim_and_proof: this one changes the latter. (cherry picked from commit 56abf7417f3aa4cc102a5189344f61bc76d7be15)
range_constrain_two_limbs converted each limb from Montgomery form twice (range check, then sublimb extraction) and then registered every sublimb through create_small_range_constraint, which re-read the variable it had just created and converted it again: 14 conversions per call for two 70-bit limbs. Convert each limb once, slice the five 14-bit sublimbs from its two low words, and register each sublimb with its known value through the uint64_t value source of register_small_range_constraint. The circuit is unchanged: the sublimb values are the same bits ((limb >> 14k) & (2^14 - 1)), fr(uint64_t) and fr(uint256_t) of the same small value are the same element, variables are still created lo 0..4 then hi 0..4, and the range check of a sublimb compares the value its variable was created from, which is what reading it back returned. Failure messages and their order are unchanged. (cherry picked from commit 10302e345acd6f1f42ab88479124f9f8d322d7c4)
register_small_range_constraint searched range_lists with count() and then again with operator[] on every call. Find the list once and insert it only when the search misses. The circuit is unchanged: the list is created by the same create_range_list call at the same point (before the variable's tag is read), and operator[] on a key known to be present returned the element find() returns. (cherry picked from commit e1a313750d3ef0889fe316274207cfee7c6db618)
The sublimbs of range_constrain_two_limbs and create_limbed_range_constraint are variables the builder has just created: each is its own real variable and carries DEFAULT_TAG. Registering them through register_small_range_constraint searched range_lists on every sublimb (ten times for two 70-bit limbs, although only two ranges occur) and ran the generic tag checks. register_new_variable_range_constraint keeps the caller's last list and goes straight to tagging and appending. The circuit is unchanged. For such a variable the generic path compares DEFAULT_TAG with the list's range tag (never DEFAULT_TAG), takes the DEFAULT_TAG branch, assigns the tag to real_variable_tags[variable_index] and appends the index: the same writes. The range assertion, the failure check and message, and the creation of a missing list happen per sublimb in the same order as before; a cached list pointer stays valid because std::map does not relocate elements on insertion, and it is only reused for an equal target range. Applies on top of the commits that convert each limb once in range_constrain_two_limbs and that look up the range list once per small range constraint: it edits the same functions. (cherry picked from commit 767e8cc60828ee5da2fa610a838fed1f684c24bd)
… recording builder Why: the next patch stops a scratch build it will not use instead of waiting for it to finish. This gives it the means. A SpliceRecording may carry a SpliceCancellation, whose check() the builder calls before each recording; a throw from it abandons the build at that point, and the builder is then only destroyed. A builder that does not record never reaches the check. Proof and VK bytes are unchanged: a builder that does not record never reaches the check, and a recording builder whose build was abandoned is destroyed without being spliced. Needs the earlier patches that add the recording mode and the splice, whose tests it extends.
…s scratch build is not ready Why it is faster: when the building thread reaches the first constraint before its scratch build has finished, waiting for that build makes a circuit with little work before the constraint slower than a serial build. The building thread now builds the constraint itself and cancels the scratch build. Which path builds the first constraint depends on timing: when the building thread reaches it and its scratch build has finished, it is spliced; otherwise that build is cancelled, take(0) returns at once and the constraint is built in place. Every later constraint still waits for its scratch build. A cancelled build never touches the real builder or engine; it throws at its next recording, its thread is joined by the splicer's destructor before its builder is discarded, and its draws, from its own draw scope or thread buffer, are dropped as a refused build's are. It is counted as built in place, not refused. launch() now returns before touching the engine when the list is empty or its first constraint is ineligible. The verbose report adds the head start of scratch build 0 and how much earlier it finished, or that it had not, or under the waiting test policy the signed margin. Proof and VK bytes are unchanged: the builder and the proof do not depend on which path ran. Both outcomes are tested equal to the serial build: under a seeded engine in every builder member, the variable values and the engine position; under the default engine in every member but the variable values. Needs the scratch-build patch and the cancellation patch before it.
…ell-formed constraints What it guards: a scratch build needs more stack than a secondary thread gets by default on some platforms, where it would overflow. Each scratch thread is now a joinable pthread with an 8 MiB stack, the usual main-thread default, and a thread that cannot start fails the launch. Scratch builds are unavailable on Windows and under OpenMP, whose loops ignore the per-thread core count that keeps a scratch thread's loops inline. A constraint naming a witness index the builder does not have is ineligible, since a scratch build reads its inputs before the serial build would reject the constraint. take() receives the constraint being built and refuses one other than the constraint launched at that index. The per-thread core count is now set inside the scratch build's try block. The splice tests skip in builds where no scratch build starts. Proof and VK bytes are unchanged: where scratch builds already ran, the same constraints are built and spliced the same way; the new conditions only withhold a scratch build, and the constraint is then built serially. Needs the scratch-build, cancellation and in-place patches before it.
…er the Honk recursion constraints What it guards: a join of a scratch build nobody will use waited for the whole build, and a cancelled first build kept its memory through the later recursion constraints. Every path that joins a scratch thread it has not taken, the destructor, a failed launch, an error on the building thread or a changed constraint, now requests cancellation first, so a join waits only until that build's next recording, or its end when none is left. finish() replaces the report after the Honk recursion constraints: it cancels, joins and destroys every scratch build still held, so a cancelled first build no longer lives on through the later recursion constraints, then reports. Proof and VK bytes are unchanged: only the moment at which unused scratch builds stop and are destroyed changes; none of them reaches the real builder or the engine. Needs the scratch-build patches before it.
What it guards: a scratch build that threw had its own message replaced by a fixed text before the constraint was built serially, which hid the cause from whoever read the log. Such a build is still refused, discarded and built serially, but the refusal reason now carries the exception's message, and each such refusal logs it with the constraint index on the verbose log, so a later one is not hidden behind the first. A normal run prints nothing new. Proof and VK bytes are unchanged: which constraints are spliced and which are built serially is as before; only the text of a refusal reason and one verbose log line are new. Needs the scratch-build patches before it.
…per-variable arrays A builder's five per-variable vectors grow by reallocation: each one copies everything written so far into a larger buffer, whose pages are then faulted in again. Ultra builders constructed from ACIR and the recording builders that scratch threads build on now reserve 2^25 entries per vector up front, so growth within that copies nothing and each written page is first touched once. Proof bytes are unchanged: capacity is not observable in any output. The reservation is one ordinary allocation per vector. With glibc's default settings a block this large is a fresh mapping of which only the written pages are resident. It is skipped when MALLOC_PERTURB_ or GLIBC_TUNABLES is present in the environment, since perturbation writes every block. An allocator configured inside the process to write or pre-fault what it hands out is outside what this detects. With transparent huge pages on "always", a written page can bring a whole huge page with it, per vector: 2 MiB on x86-64, other sizes on other architectures. It is also made only under heuristic (0) or always (1) overcommit with an unlimited RLIMIT_AS: under strict overcommit, an unreadable mode or a finite limit, a reservation that fits could make a later real allocation fail. These facts are read once per process, and read nothing of the input. The five reservations are all or nothing. They require every vector to have zero capacity, which holds at both constructors, since each makes the reservation first. A refusal frees whatever was reserved, and the builder then reserves the witness-count hint exactly as it does today. The builder records whether the reservation was made. 2^25 is a capacity chosen for address space, not derived from any circuit or input; above it the vectors grow as std::vector does. One builder reserves 2^25 x 48 bytes = 1.5 GiB of address space, 63 concurrent scratch builders 94.5 GiB. A default-constructed builder reserves nothing. Mega builders constructed from ACIR keep the witness-count hint and record that no reservation was attempted. A process builds many Mega circuits in turn. After the first, glibc may serve their hint-sized buffers from heap blocks that earlier circuits freed, whose pages are already faulted in, while a reservation is a fresh mapping every time, so each written page is faulted again and unmapped with its builder. The reserved capacity also qualifies all five vectors for the parallel page release that precedes freeing them, where smaller vectors are left to the allocator. This is reasoning from the code: it does not rank the two costs, and the cost of the reservation on such flows was not measured in isolation. Compiled out, keeping today's hint (max(4 x witnesses, 65536) for ACIR builders, seeds + 1 for recording builders): WASM, non-Linux, non-glibc and 32-bit targets, builds without exceptions, and builds under the address, hwaddress, memory or thread sanitizer.
A batch with more than 100 large members runs each of them single-threaded, one per worker, largest span first. Its admission gate compares spans (max n <= sum of n / pool width), but a member's cost follows its non-zero scalars: wide sparse members inflate the sum while costing almost nothing, so a few dense members can each take longer on one thread than the rest of the batch takes on all of them, and the other workers go idle while they finish. In the AVM's wire and log-derivative inverse commitment batches the largest dense members take two to three times the batch's ideal per-worker time. Members wider than 2^16 points now run as contiguous chunks of at most that many points, queued with all other members longest-first, and each member's result is the sum of its chunks' results. The kernel converts a member's scalars from Montgomery form in place and restores them, so concurrent members must not share scalar memory. The path now also requires the members' scalar spans to be pairwise disjoint, as the large-member job path already does; a batch with repeated or overlapping spans takes the other paths. Why the commitments cannot change: an MSM is a sum of terms s_i * P_i, so the sum of the MSMs over disjoint ranges that cover the member is the same group element as the MSM over the whole member, for any correct Pippenger (each chunk calls the same single-threaded kernel on its own scalars and points). Partial results are added with the complete Jacobian addition, which handles infinity and equal points, in a fixed order. The in-memory affine coordinates may be a different representative of the same field element, as they already are between thread counts, but every serialization of a point (field write and the conversion to transcript fields) reduces to the canonical value, so transcript, challenges and proof bytes are unchanged. Chunks own disjoint scalar ranges, so the kernel's in-place conversion and restore of scalars cannot overlap between concurrent chunks. A measured duplicate count, which only steers the window choice, is shared between chunks in proportion to their length. Members of at most 2^16 points run exactly as before, and the other dispatch paths are unchanged.
The chunked concurrent path let every chunk allocate its own arena, so a batch of hundreds of chunks allocated and faulted in hundreds of arenas. Each worker now reuses one slice of a single block, sized for the batch's largest chunk, and releases the slice's pages from that worker once it runs out of chunks, so the slices are released concurrently and the block's free only unmaps empty pages. The block is capped at 2 GiB, a bound on its size rather than a fit to any pool: a slice for a 2^16-point chunk is about 32 MiB, or 33 MiB when the member carries a dedup hint, so 61 to 64 workers fit for chunks that large and a pool that needs more slices runs fewer workers. Results cannot change: the slice is scratch that the single-threaded kernel initializes before use, exactly as on the small-member path, which already runs out of per-worker slices of one uninitialized block, and each chunk's MSM is otherwise the same call as before.
The chunked path split each member into the fewest parts of at most 2^16 points, so the chunk count was whatever the member sizes gave. A count just past a multiple of the pool width runs its last round on a few workers while the rest idle: a batch of three members of about 1.5M points makes 69 chunks, which on 64 workers is one full round and a round of five, so the batch takes about two chunk-times while 59 workers wait. For a batch whose chunks cost more per point, those two rounds take longer than running each member on its share of the pool. The total is now raised to the next multiple of the pool width, starting from the same minimum per member, and each extra part splits the member whose parts are currently the largest, so parts stay as equal as member boundaries allow and no part exceeds 2^16 points. The 69 chunks above become 128 of about 35K points, two full rounds. No constant is added: the cap is the existing 2^16 points and the target is the pool width. Results cannot change, for the reason the chunked path already relies on: an MSM is a sum of terms, so the sum of the MSMs over disjoint ranges covering a member is the same group element as the MSM over the whole member, and the partial results are still added in a fixed order.
…eads
A batch of a few large members runs them through the shared schedule:
up to four jobs share the pool, each member running on its job's
threads. Each member that is spread over many threads pays for it in
CPU and in threads idling through its reductions; the rollup circuits'
commitment batches are three members of 1.5M to 8M points on a pool of
64, about 21 threads per member.
Such a batch now takes the chunked concurrent path when each member's
share of the pool, pool width / members, is at least 8/3 threads, and
its fewest 2^16-point chunks still fill the pool. Single-threaded chunks
pay no cross-thread reduction. With one or two threads per member there
is no such cost to remove, and the chunked path's own tail is a loss.
The many-member admission is unchanged.
What fixes 8/3: the chunked path against the shared schedule, call by
call in the same process, on the commitment batches of Root,
CheckpointRoot, PublicTxBase and BlockMerge at 8, 16, 32 and 64
threads. Their three-member batches win at every width, first at 8
threads (8/3 per member); the batches that lose there and on the client
and AVM inputs have at most 1.6 threads per member. Nothing below the
smallest winning share is admitted.
The gain is measured at 64 threads. Below that it is mixed. The same
comparison on BlockRootSingleTx, CheckpointMerge and
PublicChonkVerifier, whose admitted batches are three members of 0.77M
or 1.5M points or one 1.5M-point member with two small ones, gives per
proof:
8 threads: BlockRootSingleTx -36 ms, CheckpointMerge -111 ms,
PublicChonkVerifier +19 ms (not resolved);
16 threads: BlockRootSingleTx +29 ms, PublicChonkVerifier +226 ms
(about 4%), CheckpointMerge +81 ms (not resolved);
32 threads: CheckpointMerge +31 ms, PublicChonkVerifier +62 ms,
BlockRootSingleTx -2 ms (not resolved).
Where three equal members lose at 16 threads, the chunks use 20-30%
more CPU with the pool about as busy; in the other losses the chunks
leave more of the pool idle. The counters do not locate either cost
further, and no threads-per-member share separates the wins from the
losses.
The clause also admits two and four or more wide members, and one
member once it exceeds (pool width - 1) * 2^16 points; of those only
the one-member batches above were measured. On the rollup circuits at
64 threads only their three-member batches qualify.
Results cannot change: the chunked path computes the same group
element per member (see the chunked path's own commit), and the
admission only chooses between paths that do.
Both batch tests drew their points and scalars inside parallel_for_range. Under BBERG_DEBUG_LOG, get_randomness() returns one shared, unsynchronised mt19937_64, so those draws raced. Every scalar is now drawn on the calling thread; only the point arithmetic (the generator times a random scalar) runs in parallel. Test-only: no prover code changes.
…ul exit Why it is faster. After its outputs are closed, bb spends 28-155 ms in exit on the bench box (AVM 28-121 ms, rollup Root 155 ms): the kernel frees every resident page of the process on one core (55-67 ms per GB), and glibc trims the brk heap first. On success, bb now hands its private anonymous memory back with madvise(MADV_DONTNEED) from up to min(16, cpus, mapped bytes / 32 MiB) threads and then calls _exit, which is left mostly empty mappings to unmap. Why no proof, VK or public-input byte can change. The release starts only after parse_and_run_cli_command has returned 0, so every output file is written and closed (proof, VK and public inputs through write_file's open/write/close, the --bench_out*, trace and memory-profile files through scoped std::ofstream). What a normal exit would still write is written first: the BB_BENCH report (~GlobalBenchStatsContainer, the only writing destructor; bb registers no atexit hook) through the same function, then cout, clog, cerr and C stdio are flushed. A non-zero status, and every case below, takes the unchanged normal return, so failure-path exit codes are unchanged. Why each piece exists: - Signals blocked first, for good: no handler can run on this thread between the checks and _exit (one could start a thread or touch released memory); the release threads inherit the mask. If blocking fails, or any check below fails, the mask is restored (a failed restore is logged) and the normal exit runs. - Thread count, from st_nlink of /proc/self/task: 2 plus the kernel's thread count for the thread group, the number /proc/self/status prints as Threads:, at one stat call. The kernel raises it in clone before the new thread runs and lowers it only when it releases an exiting thread, after that thread has left the address space (exit_mm). The count must first equal this thread plus its parallel_for workers, which shows that /proc counts threads (an emulated /proc that does not, or that reports a constant, fails here), and must then come down to one once parallel_for_stop_workers() has stopped and joined them. With one thread, whose signals are blocked, no other thread can touch memory or start. - The polling: a joined thread stays counted until the kernel releases it, so each count is polled (yield, with a 20 us sleep every 8th poll so a thread queued on this CPU can finish). A count that reads as required ends the wait whenever it comes; after one that does not, the wait gives up once 2 ms have passed, so a slow stat or sleep can carry it past 2 ms. The join is outside the wait. The -v exit line reports the polls and microseconds of the second wait. - Scope: the count covers this thread group only. A process sharing the memory without being a thread (clone with CLONE_VM and without CLONE_THREAD), access from another process (ptrace, process_vm_writev) and asynchronous I/O in flight are outside it, and a CLONE_VM sharer would keep using memory a normal exit leaves intact. bb creates none of them: barretenberg/cpp/src outside tests has no clone, vfork, fork, posix_spawn, popen, system, io_uring, io_submit, aio_*, lio_listio, process_vm_*, ptrace, timer_create or SIGEV_THREAD call. - parallel_for_stop_workers(): the calling thread's parallel_for workers sleep on pool state in released memory, so they are stopped and joined; the pool (now an optional, thread_local on native as before) is rebuilt on next use. Under OpenMP dispatch the pool is unused, its worker count is 0, and the release is off. - BIND_NOW check: the calls made after the release (madvise, sched_yield, pause, _exit, write) go through this object's PLT; a lazy slot would run the dynamic resolver over link maps in anonymous memory. The kit binary is BIND_NOW; others fall back. - Range selection, a pure function over /proc/self/maps text: private writable mappings with no file ([heap], [anon:*], unnamed). Every loaded object's PT_LOAD ranges (allocator and thread-library state), the scratch mapping and a 64 KiB window around this thread's TLS and TCB are cut out, all rounded out to whole pages; mappings holding the stack or TLS are dropped whole. Pieces under 2 MiB, and totals under 64 MiB, are skipped. - Scratch mapping, a whole number of pages: release-thread stacks, their TCBs and the shared state live in one fresh mmap that is never released, so nothing the release threads or this thread touch after "go" can be zeroed. - Preparation (the range lists, the maps text, the -v exit line) allocates; an exception there takes the normal exit. The writes after it are noexcept, as in the destructor they replace. - Abort path: a failed thread start sets go=ABORT, joins the threads that started (they return without touching anything), restores the mask and unmaps scratch. - A failed madvise call leaves its pages to exit; failures are counted and, with -v, reported after the release. - ExitReleaseSystem: the thread count, binding check, mmap and thread start are replaceable, so each "cannot establish" case (a live thread, a /proc that does not count, lazy binding, a failed or throwing mmap, a failed thread start) is forced in a unit test and shown to leave the ballast intact, write nothing, restore the signal mask and leave parallel_for working. One test takes the fast path for real in a fresh process (a gtest exit test in the threadsafe style, which re-runs the test binary): it writes and closes a 1 MiB file, releases and exits with status 0 rather than the fallback's 3, having written the BB_BENCH report to stderr; the parent then compares the file's bytes. - Instrumented builds (ASan, TSan, MSan, coverage runtimes) and wasm or NO_MULTITHREADING builds compile or branch to the normal exit. Simpler forms considered: calling _exit without the release saves only glibc's brk trim (the kernel still frees everything on one core); a single-threaded madvise saves nothing. Spin-and-yield and pause() replace a futex handshake and raw SYS_exit; whole-mapping pins plus a TLS window replace exact TCB arithmetic. Memory: what the release touches is bounded by the scratch mapping (4.1 MiB: 16 stacks of 256 KiB and the range table, reserved with MAP_NORESERVE) plus the selection's temporaries, and it is touched after the outputs are closed. With 4 KiB pages each release thread touches about 20 KiB (8 KiB of static TLS, its TCB, the stack in use); transparent huge pages can raise that up to the mapping's size. Threads are scheduled by mapped bytes, not resident ones; page-table reclamation in MADV_DONTNEED can send TLB shootdowns to every CPU that ran this process. Peak RSS and the gain are measured on the bench box. Needs no earlier patch.
Why it is faster. glibc returns the free top of the main heap to the kernel
("trims" it) once it exceeds a threshold: one thread shrinking the heap in
steps while the proving pool waits. On the largest AVM inputs this happens
after sumcheck's tables are freed, in some runs and not others. Blocks between
128 KiB and 32 MiB are also mapped and unmapped on every use until glibc's
dynamic mmap threshold has risen, and each use faults its pages in again.
avm_prove and prove --scheme ultra_honk now turn trimming off and pin the mmap
threshold at 32 MiB before their work starts. Measured with the same settings
given through the environment, on top of "release process memory on several
threads before a successful exit", which frees the kept memory in parallel at
exit: rollup proofs ran 3.8% faster (geomean, best of three) with 12% fewer
minor faults, and the AVM inputs 1.5% faster.
What is set:
- mallopt(M_MMAP_THRESHOLD, 32 MiB), DEFAULT_MMAP_THRESHOLD_MAX on 64-bit,
the ceiling glibc's own dynamic threshold climbs to. glibc serves every
request from free heap space first, kept space included; a block of 32 MiB
or more gets its own mapping only when no free heap space holds it.
- mallopt(M_TRIM_THRESHOLD, -1). mallopt takes an int; -1 becomes
(unsigned long)-1 inside glibc, the value its malloc.c documents as
disabling trimming. This stops the main heap's top trim and the partial
shrink of thread arenas, not the unmapping of an entirely free arena heap
nor explicit malloc_trim() calls.
- Both are set: each turns off glibc's dynamic thresholds, so either alone
freezes the other at its starting 128 KiB. The mmap threshold goes first,
and a refusal stops before the trim setting.
Where it applies. The rule reads the command and the scheme, never an input
(command_keeps_heap). It is an empirical policy per prover family, chosen by
measurement rather than by circuit shape (an UltraHonk proof can itself prove
inner circuits, as PublicTxBase's AVM recursion does): avm_prove and
prove --scheme ultra_honk keep heap. prove --scheme chonk, which proves many
circuits in turn, typically on a user's machine where peak matters more, is
left out: there the same settings measured 5.2% faster for 16% more peak,
because each step's kept heap adds to the peak. Adding chonk is a one-line
change to command_keeps_heap. --slow_low_memory excludes the policy for any
command: a user who asked for low memory does not get a setting that trades
memory for time. msgpack run, which serves many requests from one process, and
every other command leave the settings in force untouched. Nothing is set when
the environment configures malloc (a GLIBC_TUNABLES entry named glibc.malloc.*,
or any MALLOC_* variable), nor in non-Linux, non-glibc, wasm and sanitizer
builds. The call runs after the command line is parsed and before any worker
the command creates (glibc documents mallopt as unsafe once threads exist),
outside the lazily evaluated verbose log, so it applies at every log level.
One verbose line gives the outcome: "malloc policy: applied (no heap trim, mmap
threshold 32 MiB)", "... unchanged (not applied to this command or with
--slow_low_memory)", "... left to the environment (...)", "... refused by
glibc" or "... not built in".
Why no proof, VK or public-input byte can change. Where a block comes from,
and whether freed memory is kept, changes no computed value. No code can rely
on a fresh mapping's zeros for blocks under 32 MiB: glibc's default policy
already serves those from reused heap once its threshold has risen, and calloc
zeroes explicitly.
Memory. Kept heap raises peak where a later phase needs memory it does not
serve (another thread's arena, a larger block, a different size pattern).
Measured worst-of-three peak, absolute and relative:
- AVM: +1.2% geomean; worst amm +38 MB (+4.7%), from the pinned threshold.
- UltraHonk rollup: +1.7% geomean. Processes over 800 MB move -3 to +64 MB
(at most +0.85%); PublicTxBase +143 MB (+2.8%). Small processes pay a few
MB that is a large share: CheckpointPadding 42 to 48 MB (+14.6%),
InboxParity4 +4 MB (+3.8%).
Tests:
- command_keeps_heap per command and scheme: avm_prove and prove ultra_honk
keep heap, but not with --slow_low_memory; prove chonk, msgpack run,
write_vk and verify do not.
- The environment rule both ways on given environments.
- Through an injected setter, with nothing applied to the test process: no
call outside the rule or when the environment configures malloc; the mmap
threshold then -1 for trim inside it; a refused first setting stops there;
start-up at the default log level applies both and prints nothing, and at
verbose prints the outcome line.
- glibc's own mallopt accepts both values, in a fresh process (a threadsafe
gtest exit test, which re-executes the test binary).
Needs no earlier patch.
…s and tables A recording builder whose circuit reads lookup tables is now spliced into its target instead of being refused, so lookup-heavy gadgets (SHA-256 compression, 32-bit logic) can be built on another thread and appended in order. This also widens what the existing callers of the Ultra splice accept: the recursion splicer, which refused a recording that held lookup rows or tables and built that constraint in place, may now accept and splice it. Each source table becomes the table get_table would give for its id on the target: the first target table of that id, or a new table appended to the registry, new tables being created in the order the source first read them and numbered by their registry position. Source lookup rows are copied like any other row, with q_3 rewritten to the target number of their table, and each source table's read records are appended to those of its target table. Why the bytes are those of building the same rows on the target. A lookup row holds its three wires and the zero index, which the splice already remaps; the step sizes in q_2, q_m and q_c, which are constants of the multitable; and its table number in q_3, its only builder-local selector. A table get_table created is create_basic_table_contents(id) plus its number: its columns, step sizes, twin-key flag and key-to-value function follow from the id, its read records hold values only, and its index map stays empty until the composer fills it. So the splice carries the rows with q_3 renumbered, the new tables in first-read order with their numbers, and the read records in row order, which is all that the lookup relation, the table polynomials, the read counts and the dyadic size read. Building the rows on the target calls get_table in the same order, finding or creating the same tables under the same numbers and appending the same records. Still refused, with the target unchanged: elliptic rows (RowForm); a table registered with register_basic_lookup_table, whose contents its id does not fix (UnknownForm, now recorded in the splice log); a source table numbered other than by its registry position, or a lookup row whose number names no source table (UnknownForm). These are checked before the first change to the target, and nothing after it refuses. Tests, in ultra_honk/splice_lookup.test.cpp: twelve SHA-256-style gadgets (32-bit XOR, majority-function input lookup, 32-bit AND, offset by a cached constant) are built serially and in three chunks spliced onto a target that already holds AND tables, a range list with a tagged variable and the cached constant; the result feeds a later gate and copy cycle; every builder member is compared before and after finalization, and both circuits are proved and their proofs compared byte for byte. A second run is spliced onto the result and compared the same way. An elliptic row beside lookup rows, a misnumbered table, a registered table and two seeds joined on the target are each refused for their reason and leave the target unchanged.
A behaviour-equivalent refactor: the pieces of the recursion splicer that any scratch build of a circuit needs move from recursion_splice.cpp into scratch_build.hpp and scratch_build.cpp, under acir_format::scratch_build: - the condition under which scratch builds are available, now BB_SCRATCH_BUILDS_AVAILABLE, and the minimum thread count; - the thread with an 8 MiB stack, as ScratchThread (start, join, running); - the cancellation, as ScratchCancellation; the recursion splicer passes "RecursionSplicer" and its test hook, counted as before; - the refusal texts, the return of freed memory before a scratch builder is destroyed, exception messages and milliseconds_between. It is not a literal move in two ways. ScratchCancellation builds an owned message string from its owner's name and calls a stored callback before each check, where the recursion splicer's cancellation threw a literal and called its test hook directly. And the helpers, which lived in an anonymous namespace of recursion_splice.cpp, gain external linkage. Otherwise nothing changes: every text, count and code path of the recursion splicer is as it was, and its cancellation message keeps the "RecursionSplicer: " prefix.
…tch threads When an Ultra circuit's SHA-256 compression constraints are numerous enough, they are cut into equal contiguous chunks. The building thread builds chunk 0 in place. Every later chunk is built on a recording builder on a thread of its own, started beside the Honk recursion scratch builds before any opcode reaches the builder, and is spliced into the real builder at its turn in list order; the building thread waits for a chunk that has not finished. Why the bytes are the serial build's. A chunk's scratch build reads nothing of the real builder: its seeds are the witnesses its compressions read and write, and their values are copied at launch from the builder, which holds every ACIR witness from its construction. The SHA-256 construction path draws no randomness. A chunk is refused if the position of a seeded engine moved during its scratch build, which a draw from that engine does; an ordinary engine has no position, so the check detects nothing there. At the chunk's turn the splice checks that each seed still has its value, that no two seeds share a copy cycle and that none carries a tag, then appends what building the chunk there would append: rows (lookup rows and tables since the previous commit), variables, copy cycles, tags, range lists and constants. Chunks are spliced in list order where the serial build would build them, so the circuit does not depend on the chunk count, the thread count or the timing. Built in place at its turn instead: a chunk the splice refuses, one whose scratch build threw or moved a seeded engine's position, and one naming a variable the builder lacks, which is never launched; every chunk if the list differs from the one launched. Nothing starts in write-VK mode, with fewer than three threads, without native threads, pthreads and exceptions, under OpenMP, for Mega builders, or when gates per opcode are collected, since those are counted one compression at a time. The chunk count is min(compressions / 8, 16, threads); under two the run is built in place. Splicing a chunk saves the building thread its in-place build less its launch, its splice and the destruction of its scratch builder. The constants come from measuring an earlier form of this splice, which spliced into a fresh builder, on a 64-thread machine: a compression took 1.7 to 1.9 ms to build in place, and launch, splice and discard cost about 1 ms per chunk plus 0.6 ms per compression, so from 8 compressions a chunk's in-place build cost more than twice its splice. 16 is the most chunks measured; on 512 compressions 16 chunks saved about a fifth more than 4. On a real circuit of 512 compressions, 16 chunks took the building thread's run from 886 ms in place to 537 ms, about 1.0 ms per spliced compression all told. Each chunk after the first needs a thread of its own, hence the thread bound. Scratch threads are started, cancelled, joined and discarded with the helpers the recursion splicer shares in scratch_build.hpp: 8 MiB stacks, cancellation at the next recording, every thread joined on every exit path, the exception text kept, and freed memory returned before each scratch builder is destroyed. ProgramMetadata gains sha256_run: the chunk rule's inputs, with the defaults above, and observer callbacks for tests. The callbacks are fields compiled in production builds and reachable through ProgramMetadata, so native callers can set them; every caller in this repository leaves them empty, and nothing serialized exposes them. With -v the run logs one line, in the recursion splice's form: sha256 splice: <n> compressions in <k> chunks, <s> of <l> spliced, <r> refused, <p> built in place (head start <ms> ms, chunk <i> margin <ms> ms; first refusal: <reason>) Test, in dsl/acir_format/sha256_splice.test.cpp: a program with a 32-bit XOR, so tables exist before the run, 32-bit range constraints on message words, twelve chained compressions and a Poseidon2 permutation of the last output is built in three chunks and in place; every builder member is compared before and after finalization, and both circuits are proved and their proofs compared byte for byte. These comparisons always run; the chunk counts are checked only when scratch threads started, since a thread that fails to start, as under a thread quota, makes the run build in place whole, and the test is then skipped with that reason.
…-built run Adds to dsl/acir_format/sha256_splice.test.cpp, on the same kind of program of chained compressions: - Chunk counts: built in two, three and the most chunks the machine allows (sixteen at most), each build equals the serial one in every builder member before and after finalization. - Refusal and throw of the middle of three chunks: an 8-bit range constraint tags one of its message words, so the splice refuses it for the tag, and a scratch build made to throw is refused with its message. Either way the chunk is built in place at its turn, the builder equals the serial one, and the counts name the refusal. - Below the threshold: fifteen compressions under the production rule start no scratch thread and are built in place whole. - Cancellation: an error on the building thread while it builds chunk 0 in place, with both scratch builds running, cancels them before joining them and surfaces as the serial build's error; the held build never finishes and both scratch builders are destroyed. A thread that fails to start, as under a thread quota, makes a run build in place whole. The builder comparisons with the serial build always run; the checks of chunk, splice and refusal counts then give way to checks that the run was built in place, and the test is skipped with that reason. The cancellation test first builds once without hooks and is skipped if no scratch thread started.
…row by doubling Why it is faster: when a splice adds a recording's range-constrained variables to a range list the target already holds, it first reserved the list's exact new size. A vector reserved to its exact size has no spare capacity afterwards, so the next splice into the same list reallocates it again: every splice copied the whole list, and k splices feeding one list copied it k times. That is the case of a run of chunks that all extend the builder's default range list, as the chunks of a SHA-256 run do through their 32-bit range constraints. The reserve is removed, so push_back grows the list by doubling, as it does when the same constraints are built in place, and k splices copy it a number of times that grows with the logarithm of its size. A list the splice creates is still reserved once, to its own size. Why no byte changes: only the list's capacity differs, which no output reads. The list receives the same variable indices in the same order. Not timed on its own. No new test: capacity is not observable, and the splice tests already compare the lists' contents with a serial build.
…ltraHonk Why peak memory falls. CircuitProve built its prover instance with CopiedCircuitData::KEEP, so the builder's trace blocks and lookup tables stayed resident until the builder was destroyed after construction. On circuits whose peak is reached at the end of construction, that peak holds the sigma and id polynomials and the copy cycles on top of the whole builder. CircuitProve discards the builder right after building the instance, and nothing reads it in between: the VK, when it is computed, comes from the instance's polynomials. It now builds the instance with RELEASE, as chonk already does. The lookup tables are freed once their polynomials are built, and each block once its wires are copied, before the copy cycles are counted. write_vk, which shares the helper, and every other caller keep KEEP. What moves in time. The memory freed is the same as before, freed earlier. With KEEP the builder's destructor handed the pages of large chunks back from several threads before freeing them. With RELEASE each block is freed by the worker that finished copying it, and a chunk held in its own mapping is unmapped on that thread. RELEASE itself is unchanged, so chonk, its other user, behaves as before. Why no byte changes. RELEASE changes when memory is freed, never a value. Every read of a block's rows happens before its free: the selector pass ends before the wire pass, and the task that finishes a block's last chunk frees it after an acquire-release count. Afterwards only the blocks' sizes and offsets are read, and both survive the free. Neither the thread that frees a block nor the thread count affects any output. Test: the prove mode lives in one function, circuit_prove_instance, which CircuitProve calls and a new test calls on its own circuit. The test builds an Ultra circuit with arithmetic, public-input, lookup, range, ROM and RAM rows twice. With CircuitProve's instance every block with rows holds no gate data and the lookup tables are empty, while sizes and offsets match. The VK and the proof equal those built with KEEP, byte for byte, and the proof verifies. The test catches a change of the mode inside that function, not CircuitProve ceasing to call it.
…tch threads
Why faster. The root rollup verifies two rollup proofs one after the
other on the building thread, about 0.3 s each, before its in-circuit
IPA verification. The recursion splicer already builds rollup Honk
verifiers on scratch threads, where they run alongside each other and
alongside whatever the building thread builds before them; the root's
two were left out only by their proof type. is_eligible now admits
ROOT_ROLLUP_HONK, and predicted_draws predicts its draws as for
ROLLUP_HONK. Nothing else in the splicer reads the proof type: launch
selects through is_eligible, and take, the splice and the rebinding of
the output are the same for every type.
Why no byte changes. create_ultra_honk_recursion_constraint builds a
root rollup constraint with the same code as a rollup one,
UltraRecursiveFlavor with RollupIO, which is already spliced, and so
makes the same draws. The proof type is read again only by the caller,
after the constraint is built, to collect its IPA claim and proof and to
mark the circuit as the root, whichever way the constraint was built. A
spliced constraint leaves the builder and the engine as building it in
place does: the splice is accepted only when the engine stands where the
scratch build started, and the engine then moves to where that build
ended. Which verifiers end up spliced depends on timing, since the first
is spliced only if its scratch build has finished when the building
thread reaches it, and that cannot change a byte: every other outcome
builds the constraint in place on the unchanged builder and engine,
which is the serial build.
Tests.
- RecursionSpliceTest.RootRollupConstraintsAlone, per merge: the two
root constraints through create_recursion_constraints with and without
a splicer, without the IPA verification that follows them. Both are
spliced, and the builders are equal in every member before and after
finalization. With BB_DETERMINISTIC_PROVING set, which seeds the
engine, that includes the variable values, and the engine positions
after each constraint are compared too.
- HonkRecursionConstraintTestRootSplice builds the whole root program,
about 6.35M gates. Its name puts it in the nightly run with the other
root rollup tests (barretenberg/cpp/bootstrap.sh); it is
nightly-sized.
- SplicedBuildsMatchTheSerialBuild: one serial build, which a build
with the first take forced to wait and a build under the production
first-take policy each equal in every member, before and after
finalization, values and engine positions included when the engine
is seeded. The forced build splices both constraints and, with the
engine seeded, proves to the same bytes as the serial build; under
the default engine the two builds draw different offset generators,
so their proofs are not compared. The production build's spliced and
built-in-place counts are logged, not checked. Three root
constructions, and two root proofs when the engine is seeded.
- RefusedConstraintIsBuiltInPlace: the second root constraint, refused
for a range-tagged input, is built in place after the first was
spliced, and the build equals a serial build with the same tag. Two
root constructions.
- RefusesATaggedInput now shares its tagging hook with the root test.
…e hints on several threads The plookup fixed-base batch multiplication computes natively, as hints for its in-circuit Straus loop, the accumulator after every doubling and table read, one group operation after the other. For the in-circuit IPA verification, 32767 points over 32 rounds, that is a serial chain of about a million mixed additions. The computation moves to straus_native_hints.hpp and .cpp, unchanged, as compute_straus_hints_serial, beside compute_straus_hints_parallel. The parallel version cuts each round's table reads into chunks of 1024 points and sums each chunk on its own thread. The accumulator before each chunk then follows serially from the chunk sums and the round's doublings, a few thousand group operations, and each chunk fills its transcript entries on its own thread from that start. Every read is added twice, and the chain is spread over the threads. The sum of the offset generators is computed in the same chunks. Why no value can change. Group addition is associative, and the formulas used (mixed and projective addition, doubling) are complete on Grumpkin: they handle points at infinity, equal points and opposite points. So every transcript entry is the serial entry's group element. A hint is the affine form of its entry, and affine coordinates are unique, which the chunked normalization after this step already relies on; the offset generator accumulator is converted to affine as before. A point at infinity has no unique coordinates and its hint carries the raw projective ones, so if any entry is at infinity the serial result is returned instead. Chunks have a fixed size, so no intermediate value depends on the thread count either. Which variables, rows and lookups the loop creates, and their order, is untouched: only the native computation of their values changes. Threshold. The parallel version runs from 2^16 table reads (2048 points with 8-bit tables) and with at least four threads; otherwise the serial code runs. The doubled work needs about four threads to halve the time, and a shorter chain is small against the circuit that holds it. The bound keeps every other batch multiplication on the serial code: in-circuit IPA verification is the only caller of this path outside tests. Mega builders instantiate the function too and reach the same code under the same rule. Tests, in stdlib/primitives/group/straus_native_hints.test.cpp: - the threaded and the dispatched hints equal the serial ones, compared as the batch multiplication normalizes them (raw coordinates at infinity), for random reads from tables built on the offset generators and for edge reads, below and above the threshold: a table entry at infinity, an addition of equal points, cancellation and doubling inside a chunk sum, a chunk that sums to infinity, and a transcript entry at infinity, which takes the serial fallback; - a round that ends at infinity in its third chunk, through a table entry at infinity whose raw y is not zero: the serial chain carries that y into the next round's doublings, while the threaded code rebuilds the round's end from chunk sums in its own encoding of infinity, so only the serial fallback makes those hints agree; - a batch multiplication of 1025 points with 4-bit tables, one scalar zero, built with a fresh parallel_for pool of one thread, which takes the serial path, equals in every builder member, before and after finalization, the same multiplication built with fresh pools of 4 and of 16 or more threads, which take the threaded path. After each build the test checks the calling thread's pool worker count, and it restores the width, with a fresh pool, however it exits. Builds without threads or with OpenMP check only the first build and skip.
Why faster. With CopiedCircuitData::RELEASE, the worker that finishes copying a trace block's rows frees the block, and freeing a large tile chunk unmaps it there, page by page, while the copy pass waits for that worker. On the largest Ultra circuits that is a serial pause on a single thread at the end of the pass. For Ultra flavors that worker now first hands the block's chunk pages to release_pages_in_parallel, the helper the builder's destructor uses for the same chunks, so the free that follows only unmaps empty ranges. The helper's floors apply unchanged: chunks under 32 MiB are skipped, and a block with less than 64 MiB in such chunks starts no threads. The choice is made at compile time on the flavor, so Mega flavors, and with them chonk, compile the free site as before. Why no byte changes. The release runs at the place where the block's memory was already freed, after the last read of its rows, and only discards pages that are freed right after; no value, row or offset is read from them again. Which threads release the pages, and whether any do, affects no output.
Two lines added by earlier commits of this chain do not compile for wasm32 under -Werror, so no wasm target of the tree built. - polynomials/backing_memory.hpp, release_pages_of_sole_owned, from "perf(polynomials): release an instance's polynomial pages with one team of threads": a size_t was added to std::array iterators. In the wasm toolchain's libc++ those iterators are a class type whose operator+ takes a difference_type, so the sum is a signed conversion (-Wsign-conversion). The two searches now run over data(), which is plain pointers in every standard library. - stdlib_circuit_builders/ultra_circuit_builder.cpp, create_limbed_range_constraint, from "perf(builder): trim the native bookkeeping of create_limbed_range_constraint": reserve(num_limbs) narrowed a uint64_t to size_t, which is 32 bits on wasm32 (-Wshorten-64-to-32). The count is now cast; it is at most the bit count the function has just bounded. Why nothing changes. Natively std::array's iterators already are the pointers data() returns and size_t is uint64_t, so both edits compile to the code that was there, and no line moves. On wasm32 the searches visit the same elements and the reserve asks for the same count: no value any output depends on is touched.
partially_evaluate_first_two_rounds ran one parallel_for task per polynomial, so the longest polynomials set the wall while most threads idled. The fold now runs as chunks of 2^14 outputs across all polynomials, into freshly allocated destinations; every output is computed by the same kernel, so the table is identical for any thread count. Only non-ZK flavors with lazy short edges (Ultra and the applicable Mega flavors) take this path; ECCVM, Translator, AVM and ZK sumcheck keep theirs.
compute_batched wrote explicit zeros from actual_data_size_ up to the dyadic size, so compute_fold_polynomials sized the folds from the dyadic size, and the early folds carried zero tails through the fold and its commitment. A0 is now backed on [0, actual_data_size_) with virtual zeros beyond, and the folds are sized from the data extent. Commitments, evaluations and the opening proof are unchanged; callers that pass no data extent (AVM, Translator) are unaffected.
asterite
added a commit
that referenced
this pull request
Nov 27, 2026
A workflow_dispatch workflow (bench.yml) that builds bb, bb-avm and the UltraHonk micro-benchmark at each point of .github/bench/points.json (v6.1.0, then PRs #1, #2 and #3), and times every point on the same hosted runner, taking turns, per column: aztec-packages' pinned Chonk flows, its micro-benchmark, and the rollup and AVM inputs of the bench-inputs-v6.1.0 release asset. Fastest of 3 runs, highest peak RSS; each point's proofs are checked by the original bb. A dispatched run publishes data.json, a page and aztec-packages style bench JSON per point to gh-pages. A pull request that changes the benchmarks runs them without publishing.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
The second of three PRs bringing in the season 2 leaders. This one merges the rollup leader's whole stack into the
AVM leader's (PR #1): the stack's original commits, each with its own author and message, and the merge commit that
joins the two.
How it was checked
The rollup stack alone was run as one series on our benchmark runner (season 2, bb v6.1.0). On an AWS c7i.16xlarge it
passed: proofs byte-identical to the unmodified bb 6.1.0's (fixed seed, public and holdout inputs), verified by the
unmodified bb where they can be, and bb's unit tests. Time versus bb 6.1.0: rollup −64.3%, AVM −63.4%, client −58.6%.
Peak RAM: rollup −20.3%, AVM −5.4%, client +9.5%.
As in PR #1, the runner's harness patches aren't here. Checked: the rollup side of the merge is exactly the stack the
runner ran, minus the 7 files the harness touches.
The merge
The two stacks share early work (the rollup stack imported the AVM leader's cumulative stack at one point), so most of
the 19 conflicted files held the same change at two stages; the later stage was kept. Where both sides evolved the same
code differently:
pippenger_batched.hpp, the concurrent large-member MSM path: the rollup stack's version (also admits a few widemembers; chunks raised to whole rounds of the pool; one arena block per worker). The AVM side's small-member changes
merged cleanly.
backing_memory.hpp: combined. The rollup stack's deleter (releases pages early) first offers the block to the AVMstack's deferred one-team release.
sumcheck.hpp: the AVM stack's first two rounds (its gate-separator table check) with the rollup stack's chunkedfold for
partially_evaluate_first_two_rounds.logderivative_library.hppandvm2/constraining/prover.cpp: the AVM stack's (later stages of the same work).trace_to_polynomials.cpp,uintx,fold_stride2.hpp, the CRS loaders: the rollup stack's (supersets of the AVMside's).
Not checked
This exact step (AVM + rollup) was never built or timed by the runner: this PR's CI is its first build. The runner
did time the final combination (after PR 3): AVM −86.2%, rollup −65.1%, client −61.1%, byte-identical proofs on all
inputs. The code hasn't been reviewed by the bb team, and byte-identical proofs with a fixed seed don't cover how
random values are drawn in production.
Next: PR 3 (the client-WASM leader's stack), then the release.
🤖 Generated with Claude Code