Skip to content

Season 2 leaders (1/3): the AVM leader's stack - #1

Merged
asterite merged 116 commits into
mainfrom
leaders/avm
Nov 26, 2026
Merged

asterite merged 116 commits into
mainfrom
leaders/avm

Conversation

@asterite

@asterite asterite commented Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator

The first of three PRs that bring in the season 2 aztec-golf leaders, one leader's stack per PR. This one is the
AVM leader's whole stack, on top of aztec-packages v6.1.0: 115 commits, each one an original patch with its own
author and message, plus one WASM build fix (below).

How it was checked

This stack was run as one series on our benchmark runner (season 2, bb v6.1.0). On an AWS c7i.16xlarge it passed:

  • Correctness: proofs byte-identical to the unmodified bb 6.1.0's, with a fixed seed, on the public inputs and on
    holdout inputs nobody else sees; verified by the unmodified bb where they can be.
  • bb's unit tests: the 20 programs for the proving core.
  • Time versus bb 6.1.0: AVM −85.9%, rollup −48.1%, client −57.7%.
  • Peak RAM: AVM −24.4%, rollup −19.7%, client +10.8%.

What differs from what golf ran

Golf runs bb with four harness patches (a fixed-seed random generator, so proofs can be compared byte for byte, and
no self-check of a proof inside the timed run). They aren't here: the harness commits were dropped and their edits
taken back out of each later commit. Checked: this branch's tip is exactly the stack golf ran, minus the 7 files the
harness touches.

This PR's CI is also the first build that compiles the stack's own edited test files (golf's unit-test check used to
build bb's original versions of them).

One commit on top, not from golf: fix(msm): mark the native-only scalar drain helpers [[maybe_unused]] for WASM builds. Golf never builds an AVM submission for WASM, and its WASM machine uses an older wasi-sdk than the one
v6.1.0 pins (34), whose compiler rejects two helpers that only native builds use. The attribute changes no generated
code.

Not checked

The code hasn't been reviewed by the bb team. Byte-identical proofs show the prover does the same thing with a fixed
seed; with real randomness (as in production), they don't cover how random values are drawn.

Next: PR 2 (the rollup leader's stack), then PR 3 (the client-WASM leader's stack), then the release.

🤖 Generated with Claude Code

IlyasRidhuan and others added 30 commits November 25, 2026 10:16
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)
Long division by one limb computes the same exact quotient and remainder with a bounded carry chain; it changes no field/protocol inputs.

Applicability: Native cumulative prover source; effect varies by flow and available ISA.
Semantic prerequisites (minimum known feature IDs): none beyond the accepted source APIs; inspect context prerequisites.
Optional performance companions (not semantic requirements): none.
Patch-context predecessors: accepted base.
The exported patch is based on the ordered series prefix; context is not a claim of semantic dependence. Cherry-picking outside that prefix may require rebasing and new tests.

Clean layout: retain real helper headers, proper includes, normal authored test files/registration and source CMake policy. No relocated helpers, GOLF workaround annotations or special test overlay. Mandatory fixes are attached when the affected feature/tests first appear. The trusted runner-only build.sh offline-dependency correction is outside this contestant series; no extra baseline harness patch is required.

Source mail: client-research/chonk-golf/sources/final2/patches/0003-perf-single-limb-fast-path-in-uint256-divmod-chunked.patch
Source SHA256: fe35739a2d7a45b62b51fe9413c180371196f4cac5e44071ebfeb0dd890df9ae
Original author: opt <a@b>
Series feature ID: 001 (0003.division)

Validation: prior source/runtime evidence is retained, but new final-series local tests/measurements are pending Terra. No individual patch or arbitrary subset is declared qualified; Old workaround timings are held and are not a performance claim for this clean layout.
(cherry picked from commit 2d2c6cfd780e76cdeb0ad72bcd90700689e08e95)
The same sparse base-11 digits are extracted in bounded chunks; quotient/remainder arithmetic preserves the original witnesses.

Applicability: Native cumulative prover source; effect varies by flow and available ISA.
Semantic prerequisites (minimum known feature IDs): 001.
Optional performance companions (not semantic requirements): none.
Patch-context predecessors: accepted base.
The exported patch is based on the ordered series prefix; context is not a claim of semantic dependence. Cherry-picking outside that prefix may require rebasing and new tests.

Clean layout: retain real helper headers, proper includes, normal authored test files/registration and source CMake policy. No relocated helpers, GOLF workaround annotations or special test overlay. Mandatory fixes are attached when the affected feature/tests first appear. The trusted runner-only build.sh offline-dependency correction is outside this contestant series; no extra baseline harness patch is required.

Source mail: client-research/chonk-golf/sources/final2/patches/0003-perf-single-limb-fast-path-in-uint256-divmod-chunked.patch
Source SHA256: fe35739a2d7a45b62b51fe9413c180371196f4cac5e44071ebfeb0dd890df9ae
Original author: opt <a@b>
Series feature ID: 002 (0003.keccak)

Validation: prior source/runtime evidence is retained, but new final-series local tests/measurements are pending Terra. No individual patch or arbitrary subset is declared qualified; Old workaround timings are held and are not a performance claim for this clean layout.
(cherry picked from commit 49031c96500d0a751abb6788f2daa88aa4ba740d)
The transformation preserves mathematical field/witness results and existing protocol/transcript/RNG interfaces. Ownership and scheduling changes retain required value lifetimes and logical outputs. This is a source equivalence rationale, not a per-patch proof-byte test.

Applicability: Native cumulative prover source; effect varies by flow and available ISA.
Semantic prerequisites (minimum known feature IDs): none beyond the accepted source APIs; inspect context prerequisites.
Optional performance companions (not semantic requirements): none.
Patch-context predecessors: accepted base.
The exported patch is based on the ordered series prefix; context is not a claim of semantic dependence. Cherry-picking outside that prefix may require rebasing and new tests.

Clean layout: retain real helper headers, proper includes, normal authored test files/registration and source CMake policy. No relocated helpers, GOLF workaround annotations or special test overlay. Mandatory fixes are attached when the affected feature/tests first appear. The trusted runner-only build.sh offline-dependency correction is outside this contestant series; no extra baseline harness patch is required.

Source mail: client-research/chonk-golf/sources/final2/patches/0004-perf-msm-fused-scalar-batch-affine-drain-for-native-.patch
Source SHA256: d9dfa0c5539864cbde9c5a2ff3e9052d8becb45f0e765e3960f6d6f9f549de7f
Original author: opt <a@b>
Series feature ID: 003 (0004)

Validation: prior source/runtime evidence is retained, but new final-series local tests/measurements are pending Terra. No individual patch or arbitrary subset is declared qualified; Old workaround timings are held and are not a performance claim for this clean layout.
(cherry picked from commit 6fc7a8c53fb0a406bc5734064bdfa046e2021541)
The transformation preserves mathematical field/witness results and existing protocol/transcript/RNG interfaces. Ownership and scheduling changes retain required value lifetimes and logical outputs. This is a source equivalence rationale, not a per-patch proof-byte test.

Applicability: Native cumulative prover source; effect varies by flow and available ISA.
Semantic prerequisites (minimum known feature IDs): none beyond the accepted source APIs; inspect context prerequisites.
Optional performance companions (not semantic requirements): none.
Patch-context predecessors: accepted base.
The exported patch is based on the ordered series prefix; context is not a claim of semantic dependence. Cherry-picking outside that prefix may require rebasing and new tests.

Clean layout: retain real helper headers, proper includes, normal authored test files/registration and source CMake policy. No relocated helpers, GOLF workaround annotations or special test overlay. Mandatory fixes are attached when the affected feature/tests first appear. The trusted runner-only build.sh offline-dependency correction is outside this contestant series; no extra baseline harness patch is required.

Source mail: client-research/chonk-golf/sources/final2/patches/0005-perf-translator-fetch-only-grand-product-columns-per.patch
Source SHA256: d0a729df4241c815814791e8fd7c72e22ef35dd2430421dbdfe5ed92c6ee29cf
Original author: opt <a@b>
Series feature ID: 004 (0005)

Validation: prior source/runtime evidence is retained, but new final-series local tests/measurements are pending Terra. No individual patch or arbitrary subset is declared qualified; Old workaround timings are held and are not a performance claim for this clean layout.
(cherry picked from commit 49ff278a8163b9b371876b6f01cb0d45258c8381)
The transformation preserves mathematical field/witness results and existing protocol/transcript/RNG interfaces. Ownership and scheduling changes retain required value lifetimes and logical outputs. This is a source equivalence rationale, not a per-patch proof-byte test.

Applicability: Native cumulative prover source; effect varies by flow and available ISA.
Semantic prerequisites (minimum known feature IDs): none beyond the accepted source APIs; inspect context prerequisites.
Optional performance companions (not semantic requirements): none.
Patch-context predecessors: accepted base.
The exported patch is based on the ordered series prefix; context is not a claim of semantic dependence. Cherry-picking outside that prefix may require rebasing and new tests.

Clean layout: retain real helper headers, proper includes, normal authored test files/registration and source CMake policy. No relocated helpers, GOLF workaround annotations or special test overlay. Mandatory fixes are attached when the affected feature/tests first appear. The trusted runner-only build.sh offline-dependency correction is outside this contestant series; no extra baseline harness patch is required.

Source mail: client-research/chonk-golf/sources/final2/patches/0006-perf-sumcheck-skip-fold-multiply-for-bit-identical-n.patch
Source SHA256: a020292acd79a53372a3fffef7a4e5a23af11507ce46e514527d9018c08804d8
Original author: opt <a@b>
Series feature ID: 005 (0006)

Validation: prior source/runtime evidence is retained, but new final-series local tests/measurements are pending Terra. No individual patch or arbitrary subset is declared qualified; Old workaround timings are held and are not a performance claim for this clean layout.
(cherry picked from commit a2a5b786027d10b1d8a1940a0eba9c362c1fa7c4)
The transformation preserves mathematical field/witness results and existing protocol/transcript/RNG interfaces. Ownership and scheduling changes retain required value lifetimes and logical outputs. This is a source equivalence rationale, not a per-patch proof-byte test.

Applicability: Native cumulative prover source; effect varies by flow and available ISA.
Semantic prerequisites (minimum known feature IDs): none beyond the accepted source APIs; inspect context prerequisites.
Optional performance companions (not semantic requirements): none.
Patch-context predecessors: accepted base.
The exported patch is based on the ordered series prefix; context is not a claim of semantic dependence. Cherry-picking outside that prefix may require rebasing and new tests.

Original author rationale (historical, not a new measurement):
Evaluate each BATCH of safegcd divsteps several at a time (the variable-time
formulation of libsecp256k1's modinv64): count-trailing-zeros consumes a run
of g-even steps at once, and consecutive g <- (g + f)/2 steps collapse into a
single g <- g + w*f cancelling up to 4 (6 after a swap) low bits. Same divstep
sequence, matrix and delta as the one-step-per-iteration loop, without one
unpredictable branch per divstep. Shared by the Native5x64 and Wasm9x29 kernels.

Fq inversion 2.97 us -> 1.60 us on the 4-vCPU bench VM.

Clean layout: retain real helper headers, proper includes, normal authored test files/registration and source CMake policy. No relocated helpers, GOLF workaround annotations or special test overlay. Mandatory fixes are attached when the affected feature/tests first appear. The trusted runner-only build.sh offline-dependency correction is outside this contestant series; no extra baseline harness patch is required.

Source mail: client-research/chonk-golf/sources/final2/patches/0007-perf-ecc-batched-variable-time-divsteps-in-Bernstein.patch
Source SHA256: deb7fdb309ee98d4a5186c645f3f82bb40a44ab8eaff3bf341ba11922fd8ec85
Original author: bench <bench@local>
Series feature ID: 006 (0007)

Validation: prior source/runtime evidence is retained, but new final-series local tests/measurements are pending Terra. No individual patch or arbitrary subset is declared qualified; Old workaround timings are held and are not a performance claim for this clean layout.
(cherry picked from commit 6b9ad56fef95d5645560931346bea98c8ce2f067)
…ions on the prover

The transformation preserves mathematical field/witness results and existing protocol/transcript/RNG interfaces. Ownership and scheduling changes retain required value lifetimes and logical outputs. This is a source equivalence rationale, not a per-patch proof-byte test.

Applicability: Native cumulative prover source; effect varies by flow and available ISA.
Semantic prerequisites (minimum known feature IDs): none beyond the accepted source APIs; inspect context prerequisites.
Optional performance companions (not semantic requirements): none.
Patch-context predecessors: accepted base.
The exported patch is based on the ordered series prefix; context is not a claim of semantic dependence. Cherry-picking outside that prefix may require rebasing and new tests.

Original author rationale (historical, not a new measurement):
Poseidon2QuadInternal, Poseidon2QuadInternalTerminal and Poseidon2TransitionEntry
apply different constant linear maps to the same S-box outputs in each subrelation and
scale every subrelation by the same selector factor. SumcheckProverRound now hands
relations that opt in (SubrelationBatchingConstants) their subrelation separators
relative to the first one; such a relation accumulates the separator-weighted sum of its
subrelations into the first accumulator. Each S-box constant is folded into the degree-1
factor of x^5 = x^4 * x, so the per-row cost of the quad internal relation drops from
~320 to ~155 field multiplications. scale_univariates then multiplies by the first
separator, so the round univariate is unchanged. Verifier paths are untouched.

Mandatory integrated corrections: complete CPU/OS ISA detection and pinned-compiler target compatibility where applicable; MessagePack EXT copying or flavor tuple preservation at the feature that first needs it. They are not deferred broken intermediate states.
Correction source: research/sol-tuple-family-fix/0078-preserve-flavor-tuple-family-in-subrelation-batching.patch sha256=23b2316d8a66cc99e7661324d037dd0f7fe395de870dd4681285798d7bab2a6e

Clean layout: retain real helper headers, proper includes, normal authored test files/registration and source CMake policy. No relocated helpers, GOLF workaround annotations or special test overlay. Mandatory fixes are attached when the affected feature/tests first appear. The trusted runner-only build.sh offline-dependency correction is outside this contestant series; no extra baseline harness patch is required.

Source mail: client-research/chonk-golf/sources/final2/patches/0008-perf-sumcheck-fold-subrelation-separators-into-Posei.patch
Source SHA256: 1b6488c6f52c21c1c49cbb06656bbc513a97f820d146c8edc433a70ce741854b
Original author: bench <bench@local>
Series feature ID: 007 (0008)

Validation: prior source/runtime evidence is retained, but new final-series local tests/measurements are pending Terra. No individual patch or arbitrary subset is declared qualified; Old workaround timings are held and are not a performance claim for this clean layout.

Co-authored-by: Golf Research <golf@invalid>
(cherry picked from commit eae7408a4d8682db8a25ce54152aa5eaf1294129)
The transformation preserves mathematical field/witness results and existing protocol/transcript/RNG interfaces. Ownership and scheduling changes retain required value lifetimes and logical outputs. This is a source equivalence rationale, not a per-patch proof-byte test.

Applicability: Native cumulative prover source; effect varies by flow and available ISA.
Semantic prerequisites (minimum known feature IDs): none beyond the accepted source APIs; inspect context prerequisites.
Optional performance companions (not semantic requirements): none.
Patch-context predecessors: accepted base.
The exported patch is based on the ordered series prefix; context is not a claim of semantic dependence. Cherry-picking outside that prefix may require rebasing and new tests.

Original author rationale (historical, not a new measurement):
Every q_busread row activated all seven SingleBusLookup relations although only the
column whose selector is set has a non-zero read selector. skip() now also fires when
the column selector vanishes, and the prover accumulate drops the terms whose read
selector or read count is identically zero on the edge.

Clean layout: retain real helper headers, proper includes, normal authored test files/registration and source CMake policy. No relocated helpers, GOLF workaround annotations or special test overlay. Mandatory fixes are attached when the affected feature/tests first appear. The trusted runner-only build.sh offline-dependency correction is outside this contestant series; no extra baseline harness patch is required.

Source mail: client-research/chonk-golf/sources/final2/patches/0009-perf-sumcheck-skip-databus-lookup-rows-of-other-bus-.patch
Source SHA256: f635ce4c77971d0927cea24d2727ff4d1d01b80bb2fc5ae20b91911f7aa8f270
Original author: bench <bench@local>
Series feature ID: 008 (0009)

Validation: prior source/runtime evidence is retained, but new final-series local tests/measurements are pending Terra. No individual patch or arbitrary subset is declared qualified; Old workaround timings are held and are not a performance claim for this clean layout.
(cherry picked from commit 7c6013a816a5ae9b6f47e0b841c3dd589afe426c)
…_view field names

The transformation preserves mathematical field/witness results and existing protocol/transcript/RNG interfaces. Ownership and scheduling changes retain required value lifetimes and logical outputs. This is a source equivalence rationale, not a per-patch proof-byte test.

Applicability: Native cumulative prover source; effect varies by flow and available ISA.
Semantic prerequisites (minimum known feature IDs): none beyond the accepted source APIs; inspect context prerequisites.
Optional performance companions (not semantic requirements): none.
Patch-context predecessors: accepted base.
The exported patch is based on the ordered series prefix; context is not a claim of semantic dependence. Cherry-picking outside that prefix may require rebasing and new tests.

Original author rationale (historical, not a new measurement):
The generated serde decoders built each enum variant in a local and copy-assigned it into the
std::variant (deep-copying every Expression / vector of coefficients), and passed field-name
literals as std::string const&, allocating a temporary per field for names over 15 chars
(e.g. linear_combinations on every Expression). Variants are now moved in and field names are
std::string_view. The same edit should be made in the noir cpp_codegen generator.

Clean layout: retain real helper headers, proper includes, normal authored test files/registration and source CMake policy. No relocated helpers, GOLF workaround annotations or special test overlay. Mandatory fixes are attached when the affected feature/tests first appear. The trusted runner-only build.sh offline-dependency correction is outside this contestant series; no extra baseline harness patch is required.

Source mail: client-research/chonk-golf/sources/final2/patches/0010-perf-dsl-move-decoded-ACIR-enum-variants-instead-of-.patch
Source SHA256: 13db615188e5d0538c6eb9bb4ccba34479ae7adb79db5f4463bc582a70da4a97
Original author: bench <bench@local>
Series feature ID: 009 (0010)

Validation: prior source/runtime evidence is retained, but new final-series local tests/measurements are pending Terra. No individual patch or arbitrary subset is declared qualified; Old workaround timings are held and are not a performance claim for this clean layout.
(cherry picked from commit 691635cb009cf6f819599e9dc6ec6c95383ee9de)
The transformation preserves mathematical field/witness results and existing protocol/transcript/RNG interfaces. Ownership and scheduling changes retain required value lifetimes and logical outputs. This is a source equivalence rationale, not a per-patch proof-byte test.

Applicability: Native cumulative prover source; effect varies by flow and available ISA.
Semantic prerequisites (minimum known feature IDs): none beyond the accepted source APIs; inspect context prerequisites.
Optional performance companions (not semantic requirements): none.
Patch-context predecessors: accepted base.
The exported patch is based on the ordered series prefix; context is not a claim of semantic dependence. Cherry-picking outside that prefix may require rebasing and new tests.

Original author rationale (historical, not a new measurement):
circuit_buf_to_acir_format unpacked the whole program (including the Brillig functions and the
assert messages, ~1/3 of the bytes) into one msgpack object tree, converted it into a full
Acir::Circuit, and only then into AcirFormat. For the msgpack-compact array layout it now walks
the outer arrays by hand, unpacks one opcode at a time into a reused zone (STR/BIN referencing the
input buffer) and feeds it straight to an incremental AcirFormatConverter; the Brillig functions,
function name, private parameters and assert messages are skipped. circuit_serde_to_acir_format
uses the same converter, so both paths produce the same AcirFormat.

witness_buf_to_witness_vector reads the compact witness map directly into the WitnessVector
(no object tree, no std::map of byte vectors). The map is validated in full (uint32 keys in strictly
increasing order, 32-byte bin8 values) before any value is written, and holes are filled with
random elements in the same order as witness_map_to_witness_vector.

Any other layout falls back to the generic decoders.

Clean layout: retain real helper headers, proper includes, normal authored test files/registration and source CMake policy. No relocated helpers, GOLF workaround annotations or special test overlay. Mandatory fixes are attached when the affected feature/tests first appear. The trusted runner-only build.sh offline-dependency correction is outside this contestant series; no extra baseline harness patch is required.

Source mail: client-research/chonk-golf/sources/final2/patches/0011-perf-dsl-stream-msgpack-compact-ACIR-program-and-wit.patch
Source SHA256: f5d5034e182aa4c32086fc2a6fea37f0694a425a49afcf57ef92af1bb32d0a79
Original author: bench <bench@local>
Series feature ID: 010 (0011)

Validation: prior source/runtime evidence is retained, but new final-series local tests/measurements are pending Terra. No individual patch or arbitrary subset is declared qualified; Old workaround timings are held and are not a performance claim for this clean layout.
(cherry picked from commit 7e6b6d422c7b7b80de138c8c0ee895ebcf6f0f76)
The transformation preserves mathematical field/witness results and existing protocol/transcript/RNG interfaces. Ownership and scheduling changes retain required value lifetimes and logical outputs. This is a source equivalence rationale, not a per-patch proof-byte test.

Applicability: Native cumulative prover source; effect varies by flow and available ISA.
Semantic prerequisites (minimum known feature IDs): none beyond the accepted source APIs; inspect context prerequisites.
Optional performance companions (not semantic requirements): none.
Patch-context predecessors: accepted base.
The exported patch is based on the ordered series prefix; context is not a claim of semantic dependence. Cherry-picking outside that prefix may require rebasing and new tests.

Original author rationale (historical, not a new measurement):
bigfield's native quotient/remainder computation multiplies ~256-bit values held in uint512/uint1024,
so most of the cross products in uintx::operator* and mul_extended have a zero factor. operator*
now skips the cross terms whose factor half is zero (and uses the truncating product for them), and
mul_extended returns the single low product when both high halves are zero. Results are unchanged.

barrett_reduction now works on a static constexpr copy of its modulus: the class-type template
parameter object is not placed at base_uint's 32-byte alignment, which the vectorised zero test
in mul_extended would otherwise fault on.

Clean layout: retain real helper headers, proper includes, normal authored test files/registration and source CMake policy. No relocated helpers, GOLF workaround annotations or special test overlay. Mandatory fixes are attached when the affected feature/tests first appear. The trusted runner-only build.sh offline-dependency correction is outside this contestant series; no extra baseline harness patch is required.

Source mail: client-research/chonk-golf/sources/final2/patches/0012-perf-uintx-skip-multiplications-by-zero-halves.patch
Source SHA256: 8ea21a8b4fbe7d0f5b193d52c149a4b1b9bede8912546fc36323deea701f72fe
Original author: bench <bench@local>
Series feature ID: 011 (0012)

Validation: prior source/runtime evidence is retained, but new final-series local tests/measurements are pending Terra. No individual patch or arbitrary subset is declared qualified; Old workaround timings are held and are not a performance claim for this clean layout.
(cherry picked from commit f5cc85a5a6162d526b25081292949a9cfadd8c79)
The transformation preserves mathematical field/witness results and existing protocol/transcript/RNG interfaces. Ownership and scheduling changes retain required value lifetimes and logical outputs. This is a source equivalence rationale, not a per-patch proof-byte test.

Applicability: Native cumulative prover source; effect varies by flow and available ISA.
Semantic prerequisites (minimum known feature IDs): none beyond the accepted source APIs; inspect context prerequisites.
Optional performance companions (not semantic requirements): none.
Patch-context predecessors: accepted base.
The exported patch is based on the ordered series prefix; context is not a claim of semantic dependence. Cherry-picking outside that prefix may require rebasing and new tests.

Original author rationale (historical, not a new measurement):
field::one() returned field(1), which performs the Montgomery conversion (a full modular
multiplication) at runtime on every call; neg_one() additionally negated. Both now return a
constexpr local, so the value is computed at compile time. stdlib::field_t calls fr::one() in every
constructor and in is_normalized(), so this is hot during circuit construction.

Clean layout: retain real helper headers, proper includes, normal authored test files/registration and source CMake policy. No relocated helpers, GOLF workaround annotations or special test overlay. Mandatory fixes are attached when the affected feature/tests first appear. The trusted runner-only build.sh offline-dependency correction is outside this contestant series; no extra baseline harness patch is required.

Source mail: client-research/chonk-golf/sources/final2/patches/0013-perf-field-compile-time-one-and-neg_one.patch
Source SHA256: 8b5c7e7939948af4baaf2f5d7eafd1bbe8275108981ff2509dbd03b5d2e45001
Original author: bench <bench@local>
Series feature ID: 012 (0013)

Validation: prior source/runtime evidence is retained, but new final-series local tests/measurements are pending Terra. No individual patch or arbitrary subset is declared qualified; Old workaround timings are held and are not a performance claim for this clean layout.
(cherry picked from commit 9a4c605d1ddadf851b435f408a989858cf415eed)
… sleeping

The transformation preserves mathematical field/witness results and existing protocol/transcript/RNG interfaces. Ownership and scheduling changes retain required value lifetimes and logical outputs. This is a source equivalence rationale, not a per-patch proof-byte test.

Applicability: Native cumulative prover source; effect varies by flow and available ISA.
Semantic prerequisites (minimum known feature IDs): none beyond the accepted source APIs; inspect context prerequisites.
Optional performance companions (not semantic requirements): none.
Patch-context predecessors: accepted base.
The exported patch is based on the ordered series prefix; context is not a claim of semantic dependence. Cherry-picking outside that prefix may require rebasing and new tests.

Original author rationale (historical, not a new measurement):
Iterations are claimed by CAS on a packed (generation, next-iteration) word instead of under the pool mutex, and idle
workers / the waiting caller busy-wait for up to 100us before blocking on a condition variable. Chonk proving issues
~5000 parallel_for calls per proof, roughly half of them shorter than 50us, and waking blocked workers cost ~25us per
call on average.

Adds a stress test of many back-to-back parallel_for calls of varying size.

Clean layout: retain real helper headers, proper includes, normal authored test files/registration and source CMake policy. No relocated helpers, GOLF workaround annotations or special test overlay. Mandatory fixes are attached when the affected feature/tests first appear. The trusted runner-only build.sh offline-dependency correction is outside this contestant series; no extra baseline harness patch is required.

Source mail: client-research/chonk-golf/sources/final2/patches/0015-perf-threading-lock-free-parallel_for-pool-with-boun.patch
Source SHA256: ac70ebab2af8ae27d7e1aa09581cf78c0574b2d364e6dde01441bb4e628420b6
Original author: opt <a@b>
Series feature ID: 015 (0015)

Validation: prior source/runtime evidence is retained, but new final-series local tests/measurements are pending Terra. No individual patch or arbitrary subset is declared qualified; Old workaround timings are held and are not a performance claim for this clean layout.
(cherry picked from commit c2766088a9c1321a6ad62db2a14d23d75fcf1b6f)
The transformation preserves mathematical field/witness results and existing protocol/transcript/RNG interfaces. Ownership and scheduling changes retain required value lifetimes and logical outputs. This is a source equivalence rationale, not a per-patch proof-byte test.

Applicability: Native cumulative prover source; effect varies by flow and available ISA.
Semantic prerequisites (minimum known feature IDs): none beyond the accepted source APIs; inspect context prerequisites.
Optional performance companions (not semantic requirements): none.
Patch-context predecessors: accepted base.
The exported patch is based on the ordered series prefix; context is not a claim of semantic dependence. Cherry-picking outside that prefix may require rebasing and new tests.

Original author rationale (historical, not a new measurement):
Keep the state in locals across rounds, interleave the four external S-boxes
stage by stage, and in internal rounds compute state[0] <- D_0*sb + t and
state[i] <- (D_i-1)*state[i] + (sb + t), issuing the three off-path diagonal
multiplications between the S-box steps. Same multiplications and additions,
same field values. Native permutation 8.97 us -> 7.69 us.

Clean layout: retain real helper headers, proper includes, normal authored test files/registration and source CMake policy. No relocated helpers, GOLF workaround annotations or special test overlay. Mandatory fixes are attached when the affected feature/tests first appear. The trusted runner-only build.sh offline-dependency correction is outside this contestant series; no extra baseline harness patch is required.

Source mail: client-research/chonk-golf/sources/final2/patches/0016-perf-poseidon2-shorter-critical-path-in-native-permu.patch
Source SHA256: a37bdffd6cf823f6fd508be66f509fd158c42c9ad810ca6d8f7e4714a04f7805
Original author: bench <bench@local>
Series feature ID: 016 (0016)

Validation: prior source/runtime evidence is retained, but new final-series local tests/measurements are pending Terra. No individual patch or arbitrary subset is declared qualified; Old workaround timings are held and are not a performance claim for this clean layout.
(cherry picked from commit af611c399dba4f4725ed46a8e7d7d75741a9e688)
The transformation preserves mathematical field/witness results and existing protocol/transcript/RNG interfaces. Ownership and scheduling changes retain required value lifetimes and logical outputs. This is a source equivalence rationale, not a per-patch proof-byte test.

Applicability: Native cumulative prover source; effect varies by flow and available ISA.
Semantic prerequisites (minimum known feature IDs): none beyond the accepted source APIs; inspect context prerequisites.
Optional performance companions (not semantic requirements): none.
Patch-context predecessors: accepted base.
The exported patch is based on the ordered series prefix; context is not a claim of semantic dependence. Cherry-picking outside that prefix may require rebasing and new tests.

Original author rationale (historical, not a new measurement):
sha256() compresses complete blocks straight from the input instead of first
copying it byte by byte, and pads only the tail. Block compression uses the
x86 SHA extensions (SHA256RNDS2/MSG1/MSG2) when CPUID reports them, falling
back to the portable sha256_block. 4 MiB: 19.2 ms -> 2.6 ms (SHA-NI), 14.3 ms
portable. Used by the Grumpkin CRS integrity check on every load.

Clean layout: retain real helper headers, proper includes, normal authored test files/registration and source CMake policy. No relocated helpers, GOLF workaround annotations or special test overlay. Mandatory fixes are attached when the affected feature/tests first appear. The trusted runner-only build.sh offline-dependency correction is outside this contestant series; no extra baseline harness patch is required.

Source mail: client-research/chonk-golf/sources/final2/patches/0017-perf-sha256-x86-SHA-extensions-and-streaming-input-f.patch
Source SHA256: 825a44f8ccbee4fa8f72958b5303e7a6600f9a8a73f3b9e83a5dfcc90a97cf76
Original author: bench <bench@local>
Series feature ID: 017 (0017)

Validation: prior source/runtime evidence is retained, but new final-series local tests/measurements are pending Terra. No individual patch or arbitrary subset is declared qualified; Old workaround timings are held and are not a performance claim for this clean layout.
(cherry picked from commit 94156f08036423d6ab9896be79f121ac341b4066)
…ients

The transformation preserves mathematical field/witness results and existing protocol/transcript/RNG interfaces. Ownership and scheduling changes retain required value lifetimes and logical outputs. This is a source equivalence rationale, not a per-patch proof-byte test.

Applicability: Native cumulative prover source; effect varies by flow and available ISA.
Semantic prerequisites (minimum known feature IDs): none beyond the accepted source APIs; inspect context prerequisites.
Optional performance companions (not semantic requirements): none.
Patch-context predecessors: accepted base.
The exported patch is based on the ordered series prefix; context is not a claim of semantic dependence. Cherry-picking outside that prefix may require rebasing and new tests.

Original author rationale (historical, not a new measurement):
Apply every source to an L1-sized tile of dst before moving on, so dst is
streamed once per tile instead of once per source, and skip the multiply for
zero source coefficients (selector columns are mostly zero inside their
backing range). c * 0 adds nothing, so dst is unchanged.

Clean layout: retain real helper headers, proper includes, normal authored test files/registration and source CMake policy. No relocated helpers, GOLF workaround annotations or special test overlay. Mandatory fixes are attached when the affected feature/tests first appear. The trusted runner-only build.sh offline-dependency correction is outside this contestant series; no extra baseline harness patch is required.

Source mail: client-research/chonk-golf/sources/final2/patches/0018-perf-polynomials-tile-add_scaled_batch-and-skip-zero.patch
Source SHA256: 7b9214b190069aa512fe0f25a9af08b1e56faf4b32f9ccc3dea158ba6ce3dbfe
Original author: bench <bench@local>
Series feature ID: 018 (0018)

Validation: prior source/runtime evidence is retained, but new final-series local tests/measurements are pending Terra. No individual patch or arbitrary subset is declared qualified; Old workaround timings are held and are not a performance claim for this clean layout.
(cherry picked from commit ba954cf1df0369de8ac0b5834ef3b4c820934fff)
The transformation preserves mathematical field/witness results and existing protocol/transcript/RNG interfaces. Ownership and scheduling changes retain required value lifetimes and logical outputs. This is a source equivalence rationale, not a per-patch proof-byte test.

Applicability: Native cumulative prover source; effect varies by flow and available ISA.
Semantic prerequisites (minimum known feature IDs): none beyond the accepted source APIs; inspect context prerequisites.
Optional performance companions (not semantic requirements): none.
Patch-context predecessors: 008.
The exported patch is based on the ordered series prefix; context is not a claim of semantic dependence. Cherry-picking outside that prefix may require rebasing and new tests.

Original author rationale (historical, not a new measurement):
Databus and lookup inverse polynomials are computed and batch-inverted per
thread over slices of the inverse polynomial's backing range instead of a
serial whole-polynomial batch_invert after the row loop. The databus pass only
visits rows inside the q_busread and read_counts backing ranges (both are zero
elsewhere) and inverts just the non-zero entries of each slice. Inverses are
unique, so slice-wise inversion yields the same values; masking rows in the
backing range are still inverted as before.

Clean layout: retain real helper headers, proper includes, normal authored test files/registration and source CMake policy. No relocated helpers, GOLF workaround annotations or special test overlay. Mandatory fixes are attached when the affected feature/tests first appear. The trusted runner-only build.sh offline-dependency correction is outside this contestant series; no extra baseline harness patch is required.

Source mail: client-research/chonk-golf/sources/final2/patches/0019-perf-oink-parallel-range-limited-log-derivative-inve.patch
Source SHA256: 6e0e7d3e673626576dd3a44332c63d97163bd79cfc64de537741714836592f1a
Original author: bench <bench@local>
Series feature ID: 019 (0019)

Validation: prior source/runtime evidence is retained, but new final-series local tests/measurements are pending Terra. No individual patch or arbitrary subset is declared qualified; Old workaround timings are held and are not a performance claim for this clean layout.
(cherry picked from commit 80d5a9f80926bee1067b8426f0ea4254486b9ace)
The transformation preserves mathematical field/witness results and existing protocol/transcript/RNG interfaces. Ownership and scheduling changes retain required value lifetimes and logical outputs. This is a source equivalence rationale, not a per-patch proof-byte test.

Applicability: Native cumulative prover source; effect varies by flow and available ISA.
Semantic prerequisites (minimum known feature IDs): none beyond the accepted source APIs; inspect context prerequisites.
Optional performance companions (not semantic requirements): none.
Patch-context predecessors: 004.
The exported patch is based on the ordered series prefix; context is not a claim of semantic dependence. Cherry-picking outside that prefix may require rebasing and new tests.

Original author rationale (historical, not a new measurement):
The permutation grand product (UltraPermutationRelation) reads only the wire,
id and sigma columns. Dispatch on the relation rather than on
IsUltraOrMegaHonk, which does not include MegaAppFlavor/MegaKernelFlavor (the
folded app and kernel circuits): those took the generic get_row() path that
loads every column (~72) into a fresh row and copy-assigns it per trace row.
Write the 12 needed columns straight into the reused row instead.

Clean layout: retain real helper headers, proper includes, normal authored test files/registration and source CMake policy. No relocated helpers, GOLF workaround annotations or special test overlay. Mandatory fixes are attached when the affected feature/tests first appear. The trusted runner-only build.sh offline-dependency correction is outside this contestant series; no extra baseline harness patch is required.

Source mail: client-research/chonk-golf/sources/final2/patches/0020-perf-honk-fill-only-the-permutation-columns-of-the-g.patch
Source SHA256: c527a59c57b735436c7931c4a900d7f19fff9e8603f42062924d3c88bcd0ce59
Original author: bench <bench@local>
Series feature ID: 020 (0020)

Validation: prior source/runtime evidence is retained, but new final-series local tests/measurements are pending Terra. No individual patch or arbitrary subset is declared qualified; Old workaround timings are held and are not a performance claim for this clean layout.
(cherry picked from commit 530af2de7e445fda1c35d4f0e1a447232c63158c)
The transformation preserves mathematical field/witness results and existing protocol/transcript/RNG interfaces. Ownership and scheduling changes retain required value lifetimes and logical outputs. This is a source equivalence rationale, not a per-patch proof-byte test.

Applicability: Native cumulative prover source; effect varies by flow and available ISA.
Semantic prerequisites (minimum known feature IDs): none beyond the accepted source APIs; inspect context prerequisites.
Optional performance companions (not semantic requirements): none.
Patch-context predecessors: accepted base.
The exported patch is based on the ordered series prefix; context is not a claim of semantic dependence. Cherry-picking outside that prefix may require rebasing and new tests.

Original author rationale (historical, not a new measurement):
Each thread evaluates its chunk with Horner's rule (one multiplication per
coefficient instead of two), scales by z^start once, and stores its partial
sum once at the end instead of accumulating into adjacent elements of a
shared vector on every iteration (false sharing). Same value: field
arithmetic is exact.

Clean layout: retain real helper headers, proper includes, normal authored test files/registration and source CMake policy. No relocated helpers, GOLF workaround annotations or special test overlay. Mandatory fixes are attached when the affected feature/tests first appear. The trusted runner-only build.sh offline-dependency correction is outside this contestant series; no extra baseline harness patch is required.

Source mail: client-research/chonk-golf/sources/final2/patches/0021-perf-polynomials-Horner-per-thread-chunk-in-polynomi.patch
Source SHA256: b24b071841c20f07a91c48d95d0ad6094129a81d73b7e684d58bffcd4a9debc4
Original author: bench <bench@local>
Series feature ID: 021 (0021)

Validation: prior source/runtime evidence is retained, but new final-series local tests/measurements are pending Terra. No individual patch or arbitrary subset is declared qualified; Old workaround timings are held and are not a performance claim for this clean layout.
(cherry picked from commit 2349665b85cfdcb2e8b9e66d81b64f1f18289015)
…the edge on the prover

The transformation preserves mathematical field/witness results and existing protocol/transcript/RNG interfaces. Ownership and scheduling changes retain required value lifetimes and logical outputs. This is a source equivalence rationale, not a per-patch proof-byte test.

Applicability: Native cumulative prover source; effect varies by flow and available ISA.
Semantic prerequisites (minimum known feature IDs): none beyond the accepted source APIs; inspect context prerequisites.
Optional performance companions (not semantic requirements): none.
Patch-context predecessors: accepted base.
The exported patch is based on the ordered series prefix; context is not a claim of semantic dependence. Cherry-picking outside that prefix may require rebasing and new tests.

Original author rationale (historical, not a new measurement):
Each memory gate type is identified by a selector product (ROM consistency q_1 q_2,
RAM consistency q_3, RAM timestamp q_1 q_4, memory record q_1 q_m, ROM-LogUp
table/read q_2 (1 - q_1) / q_4 (1 - q_1)). The prover path (Univariate accumulators
only) tests those factors on the edge and skips the terms whose selector product is
identically zero: a product of univariates vanishes identically iff one factor does, so
the dropped contributions are exact zeros. Verifier paths are untouched.

Clean layout: retain real helper headers, proper includes, normal authored test files/registration and source CMake policy. No relocated helpers, GOLF workaround annotations or special test overlay. Mandatory fixes are attached when the affected feature/tests first appear. The trusted runner-only build.sh offline-dependency correction is outside this contestant series; no extra baseline harness patch is required.

Source mail: client-research/chonk-golf/sources/final2/patches/0022-perf-sumcheck-drop-memory-relation-terms-of-gate-typ.patch
Source SHA256: 66dc3e5ede053efadd7dc0db0f287f690bc2637fba0f9e5aa97894b72e86559c
Original author: bench <bench@local>
Series feature ID: 022 (0022)

Validation: prior source/runtime evidence is retained, but new final-series local tests/measurements are pending Terra. No individual patch or arbitrary subset is declared qualified; Old workaround timings are held and are not a performance claim for this clean layout.
(cherry picked from commit ce3325143f1bb8e9a006ae79e4a5d21e2c124862)
…mb divisions

The transformation preserves mathematical field/witness results and existing protocol/transcript/RNG interfaces. Ownership and scheduling changes retain required value lifetimes and logical outputs. This is a source equivalence rationale, not a per-patch proof-byte test.

Applicability: Native cumulative prover source; effect varies by flow and available ISA.
Semantic prerequisites (minimum known feature IDs): 001.
Optional performance companions (not semantic requirements): none.
Patch-context predecessors: 002.
The exported patch is based on the ordered series prefix; context is not a claim of semantic dependence. Cherry-picking outside that prefix may require rebasing and new tests.

Original author rationale (historical, not a new measurement):
normalize_and_rotate splits each lane at 11^right_bits and theta splits D at 11^64. Those divisors span several
uint256_t limbs, so uint256_t::divmod took the bit-serial shift-subtract loop. divmod_base_power divides by
11^18 (11^9 on wasm) chunks through the single-limb path instead; floor(floor(x/a)/b) = floor(x/(ab)), so
quotient and remainder are unchanged.

Clean layout: retain real helper headers, proper includes, normal authored test files/registration and source CMake policy. No relocated helpers, GOLF workaround annotations or special test overlay. Mandatory fixes are attached when the affected feature/tests first appear. The trusted runner-only build.sh offline-dependency correction is outside this contestant series; no extra baseline harness patch is required.

Source mail: client-research/chonk-golf/sources/final2/patches/0023-perf-keccak-divide-by-multi-limb-powers-of-11-via-ch.patch
Source SHA256: cec9e3f04f839a08d5af332f370bd81bd0b68c12c0b148886a10dae9de59d9be
Original author: bench <bench@local>
Series feature ID: 023 (0023)

Validation: prior source/runtime evidence is retained, but new final-series local tests/measurements are pending Terra. No individual patch or arbitrary subset is declared qualified; Old workaround timings are held and are not a performance claim for this clean layout.
(cherry picked from commit 1972b568d68ad4d3547d3e1d1e3c78d92f437f7f)
Field-modulus-derived values are computed once instead of repeatedly. Values and branches remain mathematically identical.

Applicability: Native cumulative prover source; effect varies by flow and available ISA.
Semantic prerequisites (minimum known feature IDs): none beyond the accepted source APIs; inspect context prerequisites.
Optional performance companions (not semantic requirements): none.
Patch-context predecessors: accepted base.
The exported patch is based on the ordered series prefix; context is not a claim of semantic dependence. Cherry-picking outside that prefix may require rebasing and new tests.

Original author rationale (historical, not a new measurement):
get_maximum_crt_product, get_maximum_unreduced_value, get_prohibited_value and unreduced_zero are fixed per
field but were recomputed with 1024-bit multiplications and a 512-bit division on every reduction_check,
sanity_check, overflow check and division. They are now function-local statics computed once.
operator- computed its borrow factor with a 1024-bit division although the dividend is below 2^460; the
same quotient is computed with uint512_t.

Clean layout: retain real helper headers, proper includes, normal authored test files/registration and source CMake policy. No relocated helpers, GOLF workaround annotations or special test overlay. Mandatory fixes are attached when the affected feature/tests first appear. The trusted runner-only build.sh offline-dependency correction is outside this contestant series; no extra baseline harness patch is required.

Source mail: client-research/chonk-golf/sources/final2/patches/0024-perf-bigfield-compute-fixed-CRT-bounds-once-512-bit-.patch
Source SHA256: 90125a37343b19b100447382401441fdc5c7e1ed5107da9289a3439bc8fbd8af
Original author: bench <bench@local>
Series feature ID: 024 (0024.constants)

Validation: prior source/runtime evidence is retained, but new final-series local tests/measurements are pending Terra. No individual patch or arbitrary subset is declared qualified; Old workaround timings are held and are not a performance claim for this clean layout.
(cherry picked from commit 9467f6aee7d73a9a060fda49c5534fdd9adfedbf)
The shifted bound is below 512 bits; narrowing the temporary preserves the exact division quotient and correction value.

Applicability: Native cumulative prover source; effect varies by flow and available ISA.
Semantic prerequisites (minimum known feature IDs): none beyond the accepted source APIs; inspect context prerequisites.
Optional performance companions (not semantic requirements): none.
Patch-context predecessors: accepted base.
The exported patch is based on the ordered series prefix; context is not a claim of semantic dependence. Cherry-picking outside that prefix may require rebasing and new tests.

Original author rationale (historical, not a new measurement):
get_maximum_crt_product, get_maximum_unreduced_value, get_prohibited_value and unreduced_zero are fixed per
field but were recomputed with 1024-bit multiplications and a 512-bit division on every reduction_check,
sanity_check, overflow check and division. They are now function-local statics computed once.
operator- computed its borrow factor with a 1024-bit division although the dividend is below 2^460; the
same quotient is computed with uint512_t.

Clean layout: retain real helper headers, proper includes, normal authored test files/registration and source CMake policy. No relocated helpers, GOLF workaround annotations or special test overlay. Mandatory fixes are attached when the affected feature/tests first appear. The trusted runner-only build.sh offline-dependency correction is outside this contestant series; no extra baseline harness patch is required.

Source mail: client-research/chonk-golf/sources/final2/patches/0024-perf-bigfield-compute-fixed-CRT-bounds-once-512-bit-.patch
Source SHA256: 90125a37343b19b100447382401441fdc5c7e1ed5107da9289a3439bc8fbd8af
Original author: bench <bench@local>
Series feature ID: 025 (0024.borrow)

Validation: prior source/runtime evidence is retained, but new final-series local tests/measurements are pending Terra. No individual patch or arbitrary subset is declared qualified; Old workaround timings are held and are not a performance claim for this clean layout.
(cherry picked from commit 5a6a0fdf700fc4fb503d7fe56a5badaa5a1b0704)
The transformation preserves mathematical field/witness results and existing protocol/transcript/RNG interfaces. Ownership and scheduling changes retain required value lifetimes and logical outputs. This is a source equivalence rationale, not a per-patch proof-byte test.

Applicability: Native cumulative prover source; effect varies by flow and available ISA.
Semantic prerequisites (minimum known feature IDs): none beyond the accepted source APIs; inspect context prerequisites.
Optional performance companions (not semantic requirements): none.
Patch-context predecessors: 023.
The exported patch is based on the ordered series prefix; context is not a claim of semantic dependence. Cherry-picking outside that prefix may require rebasing and new tests.

Original author rationale (historical, not a new measurement):
The per-slice lookup witness computation was unrolled with constexpr_for for every lane and slice, which spread
normalize_and_rotate over ~1.4MB of code; its cost was dominated by instruction-cache misses. The slices are now
produced by one compact runtime loop (append_normalize_lookup_rows), with the ReadData columns reserved up front.
Same values, same order.

Clean layout: retain real helper headers, proper includes, normal authored test files/registration and source CMake policy. No relocated helpers, GOLF workaround annotations or special test overlay. Mandatory fixes are attached when the affected feature/tests first appear. The trusted runner-only build.sh offline-dependency correction is outside this contestant series; no extra baseline harness patch is required.

Source mail: client-research/chonk-golf/sources/final2/patches/0025-perf-keccak-runtime-slice-loop-in-normalize_and_rota.patch
Source SHA256: b947eaf8d927a3f501f8de495b7c30fe013d600532cd90cc202ab2be8d9f21dd
Original author: bench <bench@local>
Series feature ID: 026 (0025)

Validation: prior source/runtime evidence is retained, but new final-series local tests/measurements are pending Terra. No individual patch or arbitrary subset is declared qualified; Old workaround timings are held and are not a performance claim for this clean layout.
(cherry picked from commit e01875f85ee61d2b4807bd0a549ed1cf9fa9f828)
The transformation preserves mathematical field/witness results and existing protocol/transcript/RNG interfaces. Ownership and scheduling changes retain required value lifetimes and logical outputs. This is a source equivalence rationale, not a per-patch proof-byte test.

Applicability: Native cumulative prover source; effect varies by flow and available ISA.
Semantic prerequisites (minimum known feature IDs): none beyond the accepted source APIs; inspect context prerequisites.
Optional performance companions (not semantic requirements): none.
Patch-context predecessors: accepted base.
The exported patch is based on the ordered series prefix; context is not a claim of semantic dependence. Cherry-picking outside that prefix may require rebasing and new tests.

Original author rationale (historical, not a new measurement):
bb::fr::one() / bb::fr::neg_one() convert to Montgomery form at runtime outside constant expressions (the
x86 Montgomery multiplication is inline asm), so every field_t constructor and every is_normalized() call paid
a field multiplication. field_t::ONE / NEG_ONE are static constexpr and hold the same values.

Clean layout: retain real helper headers, proper includes, normal authored test files/registration and source CMake policy. No relocated helpers, GOLF workaround annotations or special test overlay. Mandatory fixes are attached when the affected feature/tests first appear. The trusted runner-only build.sh offline-dependency correction is outside this contestant series; no extra baseline harness patch is required.

Source mail: client-research/chonk-golf/sources/final2/patches/0026-perf-field_t-compile-time-Montgomery-1-and-1.patch
Source SHA256: f198cd298b9d02e616fc3874a54acde6373a2fd937d7ae434f1f234f525737cd
Original author: bench <bench@local>
Series feature ID: 027 (0026)

Validation: prior source/runtime evidence is retained, but new final-series local tests/measurements are pending Terra. No individual patch or arbitrary subset is declared qualified; Old workaround timings are held and are not a performance claim for this clean layout.
(cherry picked from commit 519d85f1873e4ae2532fa0c7b4101909dee20cc9)
… parallel region

The transformation preserves mathematical field/witness results and existing protocol/transcript/RNG interfaces. Ownership and scheduling changes retain required value lifetimes and logical outputs. This is a source equivalence rationale, not a per-patch proof-byte test.

Applicability: Native cumulative prover source; effect varies by flow and available ISA.
Semantic prerequisites (minimum known feature IDs): none beyond the accepted source APIs; inspect context prerequisites.
Optional performance companions (not semantic requirements): none.
Patch-context predecessors: accepted base.
The exported patch is based on the ordered series prefix; context is not a claim of semantic dependence. Cherry-picking outside that prefix may require rebasing and new tests.

Original author rationale (historical, not a new measurement):
The joint sumcheck partially evaluated the MegaZK and translator tables with two
back-to-back parallel_for regions (46 + 190 polynomials of very different sizes),
each paying its own dispatch and load-imbalance tail. Fold both circuits' tables
from a single work list sorted largest-first. Same fold_stride2 per polynomial,
so every partial evaluation (and hence the proof) is unchanged.

Clean layout: retain real helper headers, proper includes, normal authored test files/registration and source CMake policy. No relocated helpers, GOLF workaround annotations or special test overlay. Mandatory fixes are attached when the affected feature/tests first appear. The trusted runner-only build.sh offline-dependency correction is outside this contestant series; no extra baseline harness patch is required.

Source mail: client-research/chonk-golf/sources/final2/patches/0027-perf-joint-fold-both-circuits-sumcheck-tables-in-one.patch
Source SHA256: 35cb04b7178ff221da1b95ac02136cc3e902b42c193a24b020ed1899bb761064
Original author: bench <bench@local>
Series feature ID: 028 (0027)

Validation: prior source/runtime evidence is retained, but new final-series local tests/measurements are pending Terra. No individual patch or arbitrary subset is declared qualified; Old workaround timings are held and are not a performance claim for this clean layout.
(cherry picked from commit adc0fbd4ea35696480abe7509ca592b358f1b59b)
The transformation preserves mathematical field/witness results and existing protocol/transcript/RNG interfaces. Ownership and scheduling changes retain required value lifetimes and logical outputs. This is a source equivalence rationale, not a per-patch proof-byte test.

Applicability: Native cumulative prover source; effect varies by flow and available ISA.
Semantic prerequisites (minimum known feature IDs): none beyond the accepted source APIs; inspect context prerequisites.
Optional performance companions (not semantic requirements): none.
Patch-context predecessors: accepted base.
The exported patch is based on the ordered series prefix; context is not a claim of semantic dependence. Cherry-picking outside that prefix may require rebasing and new tests.

Original author rationale (historical, not a new measurement):
Shplonk's batched quotient Q(X) = sum_j nu^j (f_j(X) - v_j)/(X - x_j) was built by copying each
claim polynomial, dividing it serially with factor_roots and add_scaled-ing it into Q. KZG's
quotient was a copy plus a serial factor_roots.

add_batched_linear_quotients computes the same polynomial with the descending synthetic-division
recurrence q_i = p_{i+1} + x q_{i+1}, split into work-balanced chunks: a Horner pass gives each
chunk's boundary value, then every chunk runs the recurrence and accumulates nu_j q_i directly
into the output, with no per-claim copies. Exact division is still asserted (p_0 - v + x q_0 = 0).

Shplonk's partially evaluated quotient G = Q - sum_j s_j f_j is applied in one add_scaled_batch
pass, a Gemini fold polynomial opened at +-r^{2^l} entering once with the sum of its two factors,
and G is moved rather than copied into the returned claim.

Clean layout: retain real helper headers, proper includes, normal authored test files/registration and source CMake policy. No relocated helpers, GOLF workaround annotations or special test overlay. Mandatory fixes are attached when the affected feature/tests first appear. The trusted runner-only build.sh offline-dependency correction is outside this contestant series; no extra baseline harness patch is required.

Source mail: client-research/chonk-golf/sources/final2/patches/0028-perf-pcs-parallel-batched-linear-quotients-for-Shplo.patch
Source SHA256: f298b7e3eb69fd3a507d2683d43f59c49f7a654f9b79c1609da34b39348ef057
Original author: bench <bench@local>
Series feature ID: 029 (0028)

Validation: prior source/runtime evidence is retained, but new final-series local tests/measurements are pending Terra. No individual patch or arbitrary subset is declared qualified; Old workaround timings are held and are not a performance claim for this clean layout.
(cherry picked from commit 1eafc92f9c25cb97b9c5a7c14fdc759e5cf51796)
The transformation preserves mathematical field/witness results and existing protocol/transcript/RNG interfaces. Ownership and scheduling changes retain required value lifetimes and logical outputs. This is a source equivalence rationale, not a per-patch proof-byte test.

Applicability: Native cumulative prover source; effect varies by flow and available ISA.
Semantic prerequisites (minimum known feature IDs): none beyond the accepted source APIs; inspect context prerequisites.
Optional performance companions (not semantic requirements): none.
Patch-context predecessors: accepted base.
The exported patch is based on the ordered series prefix; context is not a claim of semantic dependence. Cherry-picking outside that prefix may require rebasing and new tests.

Original author rationale (historical, not a new measurement):
A0+ = F + G/r and A0- = F - G/r are written in one parallel pass over F and G (one multiplication
per coefficient) instead of zero-init, copy and two add_scaled passes.

Clean layout: retain real helper headers, proper includes, normal authored test files/registration and source CMake policy. No relocated helpers, GOLF workaround annotations or special test overlay. Mandatory fixes are attached when the affected feature/tests first appear. The trusted runner-only build.sh offline-dependency correction is outside this contestant series; no extra baseline harness patch is required.

Source mail: client-research/chonk-golf/sources/final2/patches/0029-perf-gemini-single-pass-for-the-partially-evaluated-.patch
Source SHA256: 09fbd7c49fa94ab07c88f5858cc859a6051b45041bb6bc5bf7ad9452b410c83a
Original author: bench <bench@local>
Series feature ID: 030 (0029)

Validation: prior source/runtime evidence is retained, but new final-series local tests/measurements are pending Terra. No individual patch or arbitrary subset is declared qualified; Old workaround timings are held and are not a performance claim for this clean layout.
(cherry picked from commit d80b44fbd8dbae67c8b33a18a726218ac8381e39)
The transformation preserves mathematical field/witness results and existing protocol/transcript/RNG interfaces. Ownership and scheduling changes retain required value lifetimes and logical outputs. This is a source equivalence rationale, not a per-patch proof-byte test.

Applicability: Native cumulative prover source; effect varies by flow and available ISA.
Semantic prerequisites (minimum known feature IDs): none beyond the accepted source APIs; inspect context prerequisites.
Optional performance companions (not semantic requirements): none.
Patch-context predecessors: accepted base.
The exported patch is based on the ordered series prefix; context is not a claim of semantic dependence. Cherry-picking outside that prefix may require rebasing and new tests.

Original author rationale (historical, not a new measurement):
The non-largest claim polynomials are merged with one add_scaled_batch pass, and the largest is
scaled only when its scalar is not one (claim 0).

Clean layout: retain real helper headers, proper includes, normal authored test files/registration and source CMake policy. No relocated helpers, GOLF workaround annotations or special test overlay. Mandatory fixes are attached when the affected feature/tests first appear. The trusted runner-only build.sh offline-dependency correction is outside this contestant series; no extra baseline harness patch is required.

Source mail: client-research/chonk-golf/sources/final2/patches/0030-perf-multilinear_batching-batched-merge-in-compute_n.patch
Source SHA256: ac5503bde13037c1a5e925267319e1e06ee8e6421c74e1493bd920b568745f8d
Original author: bench <bench@local>
Series feature ID: 031 (0030)

Validation: prior source/runtime evidence is retained, but new final-series local tests/measurements are pending Terra. No individual patch or arbitrary subset is declared qualified; Old workaround timings are held and are not a performance claim for this clean layout.
(cherry picked from commit 556065311f6f045f0139b4dbb755ce3f97bbd7dc)
…he proof

When proving finishes, the AVM frees gigabytes of polynomials. A block
freed into the allocator's arenas keeps its pages resident, and the
kernel later frees them one by one on a single thread: when the main
arena is trimmed during static destruction, and when the process exits.
On the inputs measured, every polynomial block was in the arenas, and
that serial page freeing is most of the time between the last log line
and process exit. A block the allocator mapped on its own is unmapped
as soon as it is freed, which is the same serial work on the freeing
thread.

PolynomialMemoryRelease is a scope in which a polynomial backing block
whose last owner is dropped on the scope's thread is collected instead
of freed. When the scope ends, if the collected blocks hold at least
32 MiB, the whole pages inside them are released with
madvise(MADV_DONTNEED) from up to 16 parallel_for tasks of at least
16 MiB each; then the blocks are freed as before. Below 32 MiB nothing
is released and the blocks are simply freed. AvmProvingHelper::prove
activates one after the proof is constructed, so the proving key, the
prover polynomials and the prover's own polynomials are released
together when the function returns.

Why no output byte, exit code or error path can change:
- The proof is computed before the scope is activated, which happens
  just before the function returns it, and it holds no polynomial
  memory, so returning it touches no collected block.
- A block is collected only from its deleter, i.e. after its last
  owner is gone, so no polynomial can read it again. A block that still
  has an owner outside the scope is never touched.
- Only whole pages strictly inside the block are released, so the
  allocator's chunk headers are intact, and every collected block is
  freed exactly once, as before. The allocator makes no assumption about
  the contents of freed memory.
- Nothing new can fail: madvise results are ignored, a failed
  allocation while collecting frees the block at once, and an exception
  while releasing skips the release; the blocks are freed either way.
  If construct_proof throws, the scope was never activated and frees
  happen as before.
- Builds without threads or exceptions (WASM) are unchanged.

Verification keys are unchanged: no constraint, column or precomputed
value changes.

Blocks dropped after activation are freed when the scope ends rather
than at once, and collecting them allocates a small vector, so the
effect on peak memory is a measurement, not a guarantee.

The test runs at parallel_for concurrency 16, 3 and 1. The setting and
the pool are both per thread, and the pool is sized by the thread's
first parallel_for, so each setting is applied first thing on a fresh
thread; the test checks that it took effect there and that no more
threads than that run the pool's iterations. At each setting, a block
shared outside the scope keeps its contents, and a collected 64 MiB
block is freed exactly once, when the scope ends; on Linux, where
MADV_DONTNEED discards private anonymous pages, every whole page inside
it already reads zero. The test has no sleeps or timeouts. Builds
without the release run only the shared-block check.

This commit depends on no other commit in this series.
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.

Verification key commitments are serialized the same way, so
verification keys are unchanged too.

This commit depends on no other commit in this series.
read_uncompressed_g1_points read the whole cached CRS file into a
std::vector<uint8_t> (64 bytes per point) before converting anything:
the vector's zero-fill and the single read() of the full file both ran
on one thread, and the staging buffer doubled the loader's peak memory.
At 2^23 points that is 512 MB zeroed and 512 MB copied serially, then
freed again.

Each worker now preads its own contiguous slice of the shared file
descriptor through a 64 KiB buffer and deserializes the points straight
into the output vector. Reads and conversions proceed in parallel, and
the transient memory drops from 128 bytes per point to 64.

A worker that throws (from_buffer rejects a point off the curve) catches
the exception and records the first one, which is rethrown once every
worker has finished: the caller sees the same exception and no worker
is still reading when it unwinds. The descriptor is held by a scoped
guard, so every exit closes it, including an exception from starting
the workers.

Every point is parsed by the same from_buffer (big-endian coordinates,
conversion to Montgomery form, on-curve check) from the same bytes at
the same offsets, so the points, and every commitment, proof and
verification key built from them, are unchanged. WASM and Windows keep
the previous path.

This commit depends on no other commit in this series.
After the parallel pread loader, the remaining serial step in loading
the cached CRS is std::vector<affine_element>(n): affine_element is
trivially default-constructible, so value-initialisation zero-fills all
64·n bytes on one thread (512 MiB at 2^23 points) before the parallel
conversion overwrites every byte. The same pages are first touched by
that single thread, so they also all fault serially.

The native factory now loads through load_bn254_g1_points, which
allocates the array with new[] (default-initialisation: no zero-fill)
and lets the pread workers deserialize straight into it, so each page
is first touched, in parallel, by the thread that fills it. MemBn254Crs
owns its points through a shared array and exposes the same span, so
nothing downstream changes.

get_bn254_g1_data keeps its vector interface for its callers and tests,
and the decompression and download paths (which populate the cache) are
reused unchanged. Where points arrive in a vector (those paths, and the
vector constructor of MemBn254CrsFactory used by in-memory and WASM
callers), the vector stays their owner through the shared array's
aliasing constructor, so no path copies the CRS. Every point is still
parsed by the same from_buffer from the same bytes, so the CRS,
commitments, proofs and verification keys are unchanged.

Depends on: Read the cached BN254 CRS with parallel pread.
…everal threads

Freeing a multi-megabyte block unmaps it on the calling thread, and the
kernel then frees its pages one at a time. madvise(MADV_DONTNEED) on
disjoint ranges of one mapping runs concurrently in the kernel.

release_pages_in_parallel(ptr, bytes) splits the whole pages strictly
inside [ptr, ptr + bytes) over up to 16 short-lived threads that release
them; the caller then frees the block as before, which only has to unmap
an empty range. Blocks under 64 MiB are left alone. Only whole interior
pages are touched, so allocator metadata next to the block is intact.
The threads are started with pthread_create into fixed-size arrays, so
nothing in the helper can throw, and if a thread cannot be created the
calling thread releases the remaining slices itself; it does not use the
parallel_for pool, so it is safe from destructors on any thread. Builds
without threads (WASM) do nothing.

No caller yet; the next commit uses it for the native CRS. With no
caller it changes no output: proofs and verification keys are
unchanged.

This commit depends on no other commit in this series.
…royed

The native CRS lives in the global factory until static destruction at
exit, where freeing its array unmaps 64 bytes per point on one thread:
up to 1 GiB for a 2^24-point CRS, freed page by page inside the
process's wall time.

Give the array that load_bn254_g1_points allocates for the cached file
a deleter that hands its interior pages back with
release_pages_in_parallel before freeing it. Points still owned by a
vector (the cold decompression and download paths) are freed as before.
Only freed memory is affected; proofs and VKs are unchanged.

Depends on: Load the native CRS into uninitialised storage; Add a helper
that releases a large block's pages from several threads.
Loading the cached Grumpkin CRS ran serially on the calling thread: a
zero-filled buffer filled by one read(), the SHA-256 check of every
pinned chunk it covers, then from_buffer on each point. A rollup proof
loads it during circuit construction, before its IPA opening can start.

The cached file's prefix is now read with one pread per thread into
uninitialised storage, and the points are parsed with parallel_for. The
integrity check is unchanged and still runs on the whole prefix before
any point is parsed, so a parse only ever sees pinned data. Each point
is produced by the same from_buffer from the same bytes at the same
index, so the points and their order do not change, at any thread
count, nor do the commitments, proofs and verification keys built from
them. The pread helper moves to srs/factories/pread.hpp, where a scoped
guard closes the descriptor on every exit, including an exception from
starting the workers, and the BN254 loader uses it from there. Wasm and
Windows keep the read_file read; the parse uses parallel_for on every
target, which runs inline in builds without multithreading.

Depends on: Read the cached BN254 CRS with parallel pread; Load the
native CRS into uninitialised storage.
The inverses round splits every lookup's rows into chunks that the
thread pool claims one at a time. A row of the costliest lookups
(bytecode-decomposition byte fetching, execution-spec reads) takes several
times a typical row, so a 2^16-row chunk of one of them was still running
alone after every other chunk had finished, and it set the round's wall.

The size is the largest power of two at which, on the large inputs, no
chunk is left running with three or fewer others at the end of the round
(2^14 and 2^13 still leave one), and at which no input's round is slower.

Chunk boundaries depend only on the row count. Each chunk computes its
rows' denominators and batch-inverts them; batch_invert leaves a zero
entry zero and replaces every other entry by its unique inverse, so the
inverse polynomials, and the proof, do not depend on where chunks end.
A new test checks chunked against whole-range batch inversion around the
boundaries, with zeros at the start, at the end, across a boundary and
filling a whole chunk.

Verification keys are unchanged: no constraint, column or precomputed
value changes.

Known effect: the verbose per-relation timings
(prove/log_derivative_inverse_round/<relation>_ms) sum each chunk's time
truncated to whole milliseconds, so with sixteen times as many chunks
they undercount more than before. Nothing else in the output changes.

This commit depends on no other commit in this series.
…es are one span

Building the AVM proving key checks that each of its 2,866 unshifted
polynomials carries the label of the prover polynomial moved into it,
calling flavor_get_label on both containers. The lookup scanned every
entity to find the element's address, so the check was quadratic: about
7-8 ms on one thread per AVM proof, the same on every input size.

When a container's get_all() returns a std::span of the element's type,
the element's index is its address offset from the span's start, so the
label is found in O(1). Other containers keep the scan. The zip_view over
labels and entities is still built, so a container with a missing label
fails the same assertion with the same message, and the call sites and
their assertion text are unchanged.

Labels feed only assertions: proofs and verification keys are unchanged.

Test (new file flavor/flavor_get_label.test.cpp, in flavor_tests):
FlavorGetLabel.FindsEachEntity covers a span, a subrange of one, a
reference vector, and an element outside the container;
FlavorGetLabel.RequiresOneLabelPerEntity checks that a missing label
still fails.

This commit depends on no other commit in this series.
Once the execution trace is built, its events (one per executed
instruction, each holding several vectors) were freed on the calling
thread before the group of builder jobs started. On the largest
transactions that takes tens of milliseconds on one thread while the
rest of the pool is idle.

No job of the group reads the execution events, so freeing them is now
one more job of the group. It runs beside the builders, and the group's
join completes it before the memory rows are written and before anything
after the group runs. The execution builder has finished reading the
events before the group starts.

Only the events' storage is affected: the trace, proofs and
verification keys are unchanged.

Test: AvmTraceGenHelperTest.ExecutionEventsFreedAfterTheirRows fills the
trace columns of a simulated transaction and checks that its execution
events are freed and that every execution column matches the rows the
execution builder makes from the same events.

This commit depends on no other commit in this series.
…n group

The bytecode decomposition writes one row per byte of every bytecode, each
row about 52 cells. It ran as one job of the tracegen builder group, and
on transactions with a lot of bytecode it is the group's longest job,
finishing alone on one thread after every other builder.

Above 2^13 rows the decomposition now runs as up to 8 jobs of the same
group. Each job takes a range of whole trace-container shards (2^11 rows)
and writes every cell of its rows and no other. Every cell is a function
of the bytecode, its id, its length and the byte's position: the sliding
window and counters as before, and per row the packed field at each
31-byte group's start or, between starts, the next packed pc and its
precomputed inverse. That is what the per-group pass wrote. Row offsets
come from a prefix sum of the bytecode lengths.

The three batch-inverted columns are inverted once, by the same
invert_columns call as before, after every part has written its rows:
an atomic countdown lets whichever part finishes last run it and then
free the events. No part waits for another, so this holds at any pool
width. The inversion sees the same non-zero values in the same shard
order, so its results are the same raw limbs.

The number of parts depends on the row count alone, not on the input's
content or the thread count. Up to 2^13 rows the decomposition is the
existing single job. The trace container keeps no per-write state, so
the order of writes cannot show in the trace: proofs and verification
keys are unchanged. The split adds a prefix sum of the bytecode lengths
and a small shared state for the countdown; peak memory, measured on
the five public AVM inputs at 64 threads, one run each, stayed within
+1.3% of v6.0.0.

Tests (new file vm2/tracegen/bytecode_decomposition_parts.test.cpp, in
vm2_tests):
- BytecodeDecompositionPartsTest.MatchOneJobInEverySequentialOrder
  runs three parts one after another in all six orders, so each part is
  once the last. Each time it checks that the inversion and the final
  callback ran exactly once, and that every cell has the raw limbs of
  the single-job trace. Bytecodes of 0, 1, 30, 31, 32, 62, 8209, 4000
  and 37 bytes put windows and groups across part boundaries.
- BytecodeDecompositionPartsTest.MatchOneJobWhenThePartsRunConcurrently
  runs seven parts on the pool, eight times, with the same checks, so
  the inverting part must see the others' writes through the countdown.
- BytecodeDecompositionPartsTest.DependOnTheRowCountAlone checks
  the part count at its bounds and the default split of the same events.

This commit depends on no other commit in this series.
…pool

When the lookups and permutations have been computed, the interaction
jobs and the shared destination-table indices were freed one by one on
the calling thread as their scope ended. An index holds one row list per
destination tuple. On a large transaction the indices and the jobs'
own row lists come to millions of allocations, freed serially for tens
of milliseconds while the rest of the pool is idle.

After the jobs have finished, they are now destroyed in a parallel_for.
SharedIndexCache::release_in_parallel then moves each index's row lists
out of its map and frees them in chunks of 2^14 lists across the pool.
The jobs go first, since they point into the indices. Nothing reads a
job or an index after this point. If finish() throws, the scope unwinds
and frees them as before.

Only memory that has stopped being used is affected: the trace, proofs
and verification keys are unchanged.

Test: SharedIndexCacheTest.ReleaseInParallelEmptiesTheCache builds an
index of 40,000 row lists (more than one chunk) and checks that it is
served from the cache until release_in_parallel, then rebuilt on the
next request with the same content. Releasing an empty cache does
nothing.

This commit depends on no other commit in this series.
…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.
…rkers

The small-member pool runs out of one block of num_workers slices (up to
2 GiB). The block was freed on the calling thread after the pool's join,
and its resident pages were unmapped there one by one, in single-core
kernel time on every commitment batch, while the rest of the pool
waited for the large-member phase.

When the block is at least 64 MiB, the floor of
release_pages_in_parallel, each worker now discards the whole pages
inside its slice with a new helper, release_arena_slice (madvise
MADV_DONTNEED), once it has no member left. Workers that finish early
do this while others are still computing; the last worker to finish
still releases its own slice before the join. When the block was mapped
on its own, its free then unmaps only what the advice left resident:
the pages that straddle slice boundaries, and any range whose advice
failed (failures are ignored).

The gain depends on where the allocator placed the block and on whether
its memory is reused. glibc serves a block this large from free heap
space when it fits. Its free then returns the memory to the heap, where
a trim of the heap top may still unmap it on this thread, and the next
allocation placed there faults the discarded pages back in, where they
would otherwise have stayed resident. The release runs for every
qualifying block, including such reusable ones.

Results cannot change: a slice is scratch that the single-threaded
kernel initializes before use, and nothing reads it after its worker's
last member returns; each member's result is returned by value.

The new test runs a batch whose small-member block qualifies and checks
every member's result and restored scalars, twice. It does not observe
the advice itself, so it would also pass without this change.
…he polynomials

The AVM prover loaded 2^21 CRS points (128 MiB) for every proof. Every commitment of the
proof, including the PCS's, is to a polynomial that ends within the longest trace column
rounded up to a power of two, so that many points suffice: 2^16 or 2^17 on a small
transaction.

Once the trace is generated, the prover reads its longest column and asks the CRS factory for
that many points. In threaded builds they load on a second thread while the trace becomes
polynomials; without multithreading they load after the polynomials are built. A factory
that already holds more points serves those instead of loading. The proving key keeps the key
it is given; proving_key_from_polynomials loads its own when that key holds too few points.
Commitments past the loaded points still abort before reading the CRS. Proofs and the fixed
VK are unchanged, since every commitment uses the same prefix of the CRS.

At -v the prover logs "CRS: largest column R rows, proof needs N points, M loaded".
…nds read

The sumcheck prover filled the gate separator table for the whole hypercube: 2^21 entries,
64 MiB, for the AVM. Round r reads it at (idx / 2) * 2^(r+1) for even idx below that round's
effective round size E_r, and since folding halves the largest end index each round, no read
reaches 2^k, where k = ceil(log2 E_0). The first 2^k entries are the products of the first k
betas only, so the AVM prover now computes just those, a table of 2^16 or 2^17 entries on a
small transaction. All betas are kept for the partial evaluations, so the round univariates,
the transcript and the proof are unchanged. Other flavors are untouched.

Before every round the AVM prover asserts, in release builds too, that the table covers the
largest index the round will read, (E_r / 2 - 1) * 2^(r+1). At -v it logs the table size.
…tching task

For flavors that batch relations in parallel, batch_over_relations scaled
every subrelation accumulator by its separator on the calling thread, batched
the relations in parallel, then zeroed every accumulator on the calling
thread again. Both passes run over the whole tuple every round whatever the
round size, which for AVM is about ten thousand coefficients.

Each relation's batching task now scales its own accumulators before reading
them and zeroes them after. The separators, the index of each subrelation and
the per-relation sums are unchanged, so every coefficient goes through the
same multiplication, reads and reset in the same order and the round
univariate keeps its limbs. Flavors that batch serially keep the two passes.
The zeroing Polynomial constructor splits the memset over every pool
thread, and dispatches that job even when there is nothing to zero. AVM
builds its sumcheck book-keeping table with one such construction per
column, and every column whose source is empty gets a zero-size polynomial,
so each proof runs one pool job per empty column. The to-be-shifted
columns are built the same way.

A zero-size polynomial now returns after allocating its (empty) backing.
Its sizes, start index and memory are what they were. This applies to
every zero-size construction, in every flavor.
The earlier commit "perf(avm): release the proving polynomials' pages in
parallel after the proof" declares PolynomialMemoryRelease's previous_ and
active_ in every build but uses them only where backing_memory.cpp builds the
release (native, threaded, with exceptions). In the WASM build, and in any
build without threads or exceptions, clang reports both as unused private
fields, and -Werror makes that fatal. Building this series for WASM found it.

Mark both fields [[maybe_unused]]. The attribute only silences the
diagnostic: the class layout and native code are unchanged, and no line moves.
…ge at a time

AVM's columns are allocated as prefixes of the trace, so the leading edges of
a round usually carry the most live columns. On the AVM benchmark inputs, the
16-row chunk that held them was measured running on one thread after the other
threads had finished, setting the wall time of the middle and late rounds; a
round of at most 16 rows is that one chunk. The scheduler now hands out the
first 512 rows of each round as one-edge chunks, ahead of the 16-row chunks.
The head size is a constant, so chunk boundaries depend only on the round's
edge range, never on the thread count. Other flavors have a head size of 0 and
the head path is compiled out.

Proofs are unchanged: chunks and slots only regroup each accumulator's per-edge
terms, field addition is exact, and proofs serialize the reduced form.
…mmitments

In a batch MSM, members below the multithreading bound run whole, one per
worker. A member's cost tracks its non-zero scalars times their bit length,
not its span, so a few dense members can each run longer on one thread than
the rest of the batch takes on all of them.

SmallMsmSchedule::SPLIT_BY_COST samples one scalar per 64th of each small
member (fixed positions, no randomness), estimates its cost, and cuts any
member above the pool's fair share into contiguous parts of at least 2048
points at cost quantiles. Parts are claimed costliest first and run exactly
as concurrent chunks do: disjoint scalars converted and restored by their
own call, the aligned slice of the shared GLV buffer, and a share of the
member's duplicate count. Partials are summed per member in offset order
with the complete addition and converted to affine afterwards. When no
small member is long enough for two parts, nothing is sampled and the
existing whole-member pool runs unchanged.

Why the commitments do not change: inside a call, the only additions that
skip the equal-x check are the batched affine additions of bucket partial
sums (the tree reduction and the dedup cluster sums). Each batch multiplies
its x-differences before its one inversion and calls throw_or_abort on a
zero product, inside noexcept code, so a coincidence of two partial sums
terminates the process and never yields a wrong point. Absent one, every
part's result is exact; the parts partition the member's terms, so for any
cut points they sum to the member's group element, and the complete
addition and the unique affine form give the same commitment.

A coincidence needs a non-trivial relation sum c_i P_i = 0 among distinct
SRS points, with c_i in {0, +-1, +-lambda, +-1 +- lambda} (GLV adds
lambda P_i). For the KZG SRS, P_i = tau^i G, that is a non-zero polynomial
of degree below the SRS size vanishing at tau: at most d/r per addition for
an SRS of d points and inputs chosen without knowledge of tau, below 2^-231
for d <= 2^22. Grumpkin's generated points, with independent unknown
discrete logs, give 2^-254 per addition. The existing schedules rest on the
same assumption and already vary their pairings with the thread count, the
member size (GLV) and the chunking. With two equal or opposite points under
equal scalars, both schedules abort when the points share a part, and the
split schedule returns the exact sum when a cut separates them.

The schedule is opt-in through new overloads of MSM::batch_multi_scalar_mul,
CommitmentKey::batch_commit and CommitBatch::commit_and_send_to_verifier.
The AVM's wire and log-derivative inverse commitments use it; every other
caller keeps the existing path.
…for WASM builds

drain_batch_scalar and tree_reduce_in_place_scalar are only reached from a native-only path, so a WASM build
compiles them unused, and wasi-sdk 34's compiler (clang 23, the version aztec-packages v6.1.0's build image
pins) rejects that under -Werror (-Wunused-template). The attribute changes no generated code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@asterite
asterite merged commit e9f8b30 into main Nov 26, 2026
13 checks passed
@asterite
asterite deleted the leaders/avm branch November 26, 2026 22:38
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants