Repository navigation
Conversation
…s and async calls A standalone executable (plain main(), `--smoke` CTest entry) with about 80 scenarios. They time the recursive and the stackless evaluators bare, and the sync and async schedulers under floods of small, large and mixed programs. They also cover async functions on the background pool, a lane and inline; compute fan-outs; messaging; native and state-tree calls; per-process footprint; armed limits; deep-data work; and parsing. Each record is a JSONL line with: - wall time, driver-thread and process CPU; - steps by kind and ns/step; - latency percentiles; - peak working set and private bytes; - allocation counts; - thread and handle counts, including the app's pooled threads. The driver pins itself to a performance core, and every scenario checks its programs' results. tools/bench/state_exec_bench.py runs one process per scenario with repetitions and compares two runs against their noise. docs/STATE_EXEC_BENCH.md describes every scenario, the metrics, how to get stable numbers, and the pathologies the first runs exposed: - scheduler steps that cost O(P log P); - the background pool's thread per call, kept alive with its result until ~app; - the step rate re-read from the state tree on every charge; - busy-spinning sleepers; - unreaped floods.
…x64) WPR and VSDiagnostics need elevation, so the bench samples itself. A sampler thread suspends the driver about every millisecond and unwinds its stack in place with RtlVirtualUnwind into a preallocated ring, with no allocation, locks or DbgHelp while the driver is suspended. A watchdog resumes it if a sample holds it over 50 ms. Waits and other system calls are told apart by the ntdll/win32u stub they sit in. After the run, DbgHelp, loaded on demand, symbolizes the samples into folded stacks (speedscope, flamegraph.pl) and top self/inclusive/line tables. Only the first measured rep is sampled, so the other reps' timings stay clean; records name the sample files. Elsewhere --sample says it is unsupported and points at perf.
…ompares Both evaluators matched a call head against every special form in turn, up to 19 std::string compares for each ordinary call. special_form_of() (special_forms.h, private) switches on the name's length and a letter or two and confirms the one candidate with a single compare. The order is unchanged: special forms first, then user macros (the macro map is no longer hashed when no macro is defined), then bindings. The recursive evaluator still treats yield and break as ordinary names. Tests: the classifier against every special form name and its one-letter neighbours, and the precedence of special forms over macros and bindings in both evaluators.
…lookup environment::extend() made a fresh std::unordered_map for every closure call, let and catch: on MSVC three allocations (the make_shared block, the map's list sentinel and its bucket array) before the first binding, and a node per binding. A scope from extend() now has a deleter that empties it the way its destructor would (the enclosing scope first, then each binding through ~value_tag, so a release backlog sees the same owners in the same order) and keeps it, with its bindings' nodes and its control block, for the next extend() and set() on the same thread. What is kept is bounded (64 scopes, 128 nodes, 64 blocks per thread) and only scopes whose map is still small; nothing is shared between threads, and a scope dropped after its thread's pool is gone is freed. environment::lookup() hashed the name again in every scope of the chain. It now skips empty scopes, hashes once, and walks the bucket of that hash in each scope. The bucket formula (a mask for a power-of-two bucket count, else a remainder) is checked against the map's own bucket() at startup; where it doesn't hold, lookups use find() as before. A standalone MSVC micro benchmark of a 17-scope chain: 86 -> 73 ns for '+', 99 -> 64 ns for 'fib', 401 -> 55 ns for a 24-character name. Tests: a recycled scope comes back empty, unfrozen and linked to its new parent; its bindings are dropped through the release backlog as a destroyed scope's are; a 200000-deep chain frees; lookups over 5000-name scopes, empty scopes and shadowing; a scope dropped at thread exit.
Most of a step's allocations were a frame's vectors: a call form copied its arguments into a fresh vector, its children's values grew another one from empty (two or three allocations for a two-argument call), and a set or for copied its name into a vector of strings. A popped frame now gives its emptied vectors back to a small per-thread store, kept by capacity, and a frame takes one of exactly the capacity it needs (the call's argument count, a begin's form count), so a frame holds no more than it did and the stack's heap measurement doesn't grow. The parts of a popped frame are freed in its destructor's order, so dropped owners reach a release backlog as before. Frames are built in place on the stack instead of moved in from a temporary, step_init reads the form's arguments in place and copies only what a frame keeps, and a for over a list copies the list once, not twice. Allocations per iteration (state_exec_bench, stackless): arith_loop 18 -> 0, closure_calls 24 -> 0, native_calls 17 -> 0, list_build_walk 21 -> 0, fib 16.5 -> 0.19. Tests: step counts of each kind for fourteen programs (calls, closures, loops, let, try, macros, classes, generators, sliced deep data), pinned at the values the evaluator took before this work; a popped frame keeps no value alive.
evaluation_stats::increment_step() did a lock-prefixed fetch_add on every step, although only the thread stepping a state counts its steps. Eval steps now go to a counter of their own, updated with a relaxed load and store; steps of the other kinds and the steps add_steps() charges (an async host, possibly from another thread) keep their atomic adds on the shared counter, and get_step_count() is the sum. Readers on other threads still read atomics, and every count is what it was. Test: a thread counting steps while another charges steps and a third reads them gets exact totals per kind, and a moved or restarted stats object carries or clears them.
A call of a DSL function whose body has several forms wrapped them in a new (begin ...) list every time: two allocations and a reference count per form. The stackless evaluator now makes that list when it makes the closure (lambda, defun, defclass methods) and keeps it in a new closure::body_expr; a call (and generator, which did the same) uses it while it still matches the body, form for form, and builds one as before otherwise (a closure made elsewhere, or a body changed since). The heap walks count it as one of the closure's edges and the cycle collector clears it with the body; the codec, printing and equality ignore it. Test: the list is made for a body of several forms only, holds the body's own forms, and a body changed after the closure was made runs as changed.
A call's init step looked its head up through the scope chain only to check it exists, and its apply step looked it up again. The init now records the binding it found (a node of a scope's bindings), the scope, and the sum of the sizes of the scopes from the frame's out to that one (eval_frame::callee, callee_scope, callee_stamp, not serialized). Apply uses it when that sum is unchanged and the binding still has the call's head name, and looks the name up otherwise. Bindings are only added to a live scope, so an unchanged sum means no nearer scope has gained a binding that could shadow the one found; a binding rebound in place is read through the node, so the apply step sees the value a lookup would. A restored frame has no record and looks the name up. environment::find_binding() is lookup() saying where. Tests: a function rebound in place, shadowed in a nearer scope, or rebound between calls while a call's arguments run is the one applied; the record of a call's init, and a binding added in the process scope between init and apply.
- The environment goes down by const reference: eval_internal, eval_form and every special form took the shared_ptr by value, two atomic reference count changes per node. - A form's copy of its arguments and the vector of their values come from vectors the evaluator keeps between forms (emptied when the form is done, so they hold no values), not fresh allocations. The copy itself stays: a program may change its own code while it runs, and a form evaluates the arguments it had. - The trail guard tells an unwinding exception from a return by a flag set when eval_form returns, not two std::uncaught_exceptions() calls per node (a fiber-local read on MSVC). - A let body runs over the form's own argument copy instead of a second copy. - evaluate() no longer makes a scope it throws away. With the scope and dispatch changes before it, the recursive eval.* programs run in about half the time and allocate nothing per iteration (arith_loop 9 -> 0, fib 12 -> 0.03). Test: a form's kept vectors hold no values once it is done.
…expression once A frame's value went to the frame below through pop_frame's by-value parameter: copied in, moved into the parent's results, then destroyed. A symbol's value, an atom, and the value an if, begin or let passes on are now put straight into the parent's results (an atom's and a passed-on value moved, not copied), before the frame goes: the value may live in that frame, or in a scope only that frame holds. The frame's parts are freed as before, in the same order. push_frame copies the expression and scope straight into the new frame when the stack has room (they may be in the top frame, which a growing stack moves), instead of copying them into parameters and moving those in.
…s exact size - A symbol or number token is found first and copied once, not built a character at a time, and strtod is asked only about a token it could read (a sign, then a digit, '.', or the i/n of inf and nan): every other token is a symbol, as strtod would have said. - A string's or bytes literal's plain characters up to the next quote or escape are appended as one run, the line and column moved on as advance() would have moved them. - A list's elements are collected in a vector the parser keeps (or one with room for eight) and the list gets a vector of its exact size, instead of growing one an element at a time: parse.large 37050 -> 17779 allocations, parse.small 42 -> 34, and a parsed program holds no spare capacity. Tests: tokens read as numbers, booleans, nil or symbols exactly as before (the cases checked against the previous parser too), line and column after tokens and multi-line strings, string and bytes runs around escapes, and parsed lists at their exact size.
closure::body_expr was a value_t, 72 bytes on MSVC, which footprint.closure showed on every closure (291 -> 364 heap bytes per closure). It is now the list_ptr itself (16 bytes); the heap walks count it as a list edge, and the cycle collector resets it.
- set binds a copy of its value and passes the value itself on, instead of copying it into a local, again into the binding and again into the frame below. - A native call's result is moved straight into the frame below. - Entering a try moves the body, cleanup and catch clauses into its frame instead of copying them out of initializer lists, and takes its vectors from the kept ones.
…zed ones A scope from environment::extend() and its shared_ptr control block are one allocation again, as make_shared made them: a scope_block holds the scope and a slot that the block's allocator hands out for the control block. The block is kept for reuse, or freed, when the control block is deallocated, which is after the deleter emptied the scope. Long-lived scopes (a process's) are back to one allocation each and sit where they did. Before, the separate control block made the many-process scheduler scenarios 5-18% slower. A scope is kept only while its map has the bucket count of a new map. On libstdc++ and libc++ a new map has no buckets allocated, so the bucket count of a recycled scope, which heap measurement counts, could depend on what the thread recycled before. Now it never does. On MSVC nothing changes: a new map has 8 buckets and keeps them up to 8 bindings. bind_new() takes the node out of the pool before filling it, so a throwing key copy or insert frees the node and its value, as a failed emplace would.
…copes by identity call_closure() popped the call's frame and then read the closure through `cls`, a reference into the callee's binding. When the function is a parameter called in tail position, that binding is in the scope only the popped frame held, and the scope recycler had just moved the value out of it: `(defun twice (f x) (f (f x))) (twice inc 5)` crashed. (Before the recycler this was a latent use after free; `(defun call-it (h) (h)) (call-it (lambda () 42))` crashed on the old code too.) The call now takes the bound scope and the body expression before the frame goes. Tests cover a named function and lambdas passed as parameters on the bare evaluators and both schedulers. A call's record of the function its init found now marks the scopes the lookup walked by their count and a stamp: the sum of their sizes (exact: a scope that gains a binding changes it) and a mix of their addresses, so a chain a host rewires (environment::outer, writable from pycvc) is looked up again. The init lookup computes the mark in the same walk, so there is one walk fewer per call. eval_frame now grows by 16 bytes, not 24 (224 -> 240 on MSVC x64). environment::find_binding(), added earlier on this branch, is gone. The last frame's parts are dropped before the state's old result again, as pop_frame did (with slicing on, release backlog order decides how freeing is split into data steps). push_frame() copies the expression and scope before it grows the stack, so an out-of-memory copy leaves the stack as it was.
… form makes closure::body_expr was built for every closure with a body of several forms when the closure was made: a list of n+1 values and its control block per closure, made even for closures never called, and counted by heap measurement. 100k two-form closures cost 717 bytes each instead of 418. Now the closures one lambda form makes share one (begin ...). A small per-thread table, one slot per form address, holds it weakly. A slot is used only while what it holds is exactly (begin body...) for the new closure's body, so a slot whose form was freed and its address reused is harmless. A closure costs its 16-byte pointer, and making one costs a few pointer compares, not two allocations. A generator gets a body list of its own again. (root) in a generator returns that list, and a generator that appends to it no longer changes the body of a sibling generator made from the same closure.
increment_step() is public, and pycvc wraps it (and start()). The evaluators release the GIL while they run, so a count made from another thread during stepping could be lost under the load-and-store fast path. increment_step() is a locked add again. The evaluators count their own eval steps through a private count_eval_step(), which keeps the load and store: the stepping thread is the only one that counts while it steps. start() now says not to reset the counts while another thread steps the state.
The parser copied every closed list into an exact-size vector and kept the vector it was collected in. For a large literal list that held about twice the list's memory while the list closed, and then kept the large vector until the parser was destroyed. Now a list collected in a vector of more than 64 values takes that vector, as before this branch. Only short vectors are copied and kept.
…i-form closure The recursive evaluator keeps at most 64 spare argument vectors of up to 8 values (was 16), about 37 KB per evaluator on 64-bit MSVC. The stackless evaluator's per-thread frame vectors are at most about 41 KB, and the scope pool (types.cpp) under 35 KB per thread. The comments now say so. footprint.closure_forms keeps n closures whose body has two forms, the case the per-closure (begin ...) cost showed up in; footprint.closure has a one-form body.
…ateless allocator The block allocator carried a pointer to its block, which made the control block 8 bytes larger and the block 136 bytes on MSVC (make_shared's was 104). footprint.environment measured 813 -> 861 bytes per item. Now the block is a 32-byte slot followed by the scope (120 bytes on MSVC). extend() names the block for the allocator in a thread-local just before it makes the shared_ptr, so the deleter and allocator are empty and the control block is 24 bytes (32 with libc++). Deallocation finds the block at the slot's address.
…alue scope_recycler moved each binding's value out and kept the node for the next bind_new(). That empties the node only if a moved-from value is empty. libc++ moves a std::function whose callable fits its small buffer by copying the callable, so a kept node held a live copy of a native function: a class constructor's copy kept the class dict alive, with its methods and the scopes they captured, until the node was reused (in some other process's step) or the thread exited. The node's value is now exchanged for nil, so the value still drops through the same local, in the same order. MSVC and libstdc++ already leave the source empty, so the new test fails only on libc++.
increment_step(eval) did a locked add on eval_step_count, the counter the stepping evaluator updates with a plain load and store in count_eval_step(), so a count made from another thread between that load and store was lost. increment_step() now adds to step_count, as it did before this branch, and only the stepping evaluator writes eval_step_count. get_step_count() and steps(eval) sum both, as before. New tests race increment_step() against each evaluator stepping a loop.
…begin ...) same_form() compared doubles with ==, so 0.0 and -0.0 were the same form. A lambda form made at the address of a freed one, whose body differed only in the sign of a zero, got the freed form's (begin ...) and evaluated the other literal: (defmacro k (v) (lambda () nil v)) (set a (k -0.0)) (set b (k 0.0)) (b) returned -0.0. Numbers now compare by bit pattern (a NaN is the same form as itself). The other atoms already compare exactly, and lists, dicts and closures by object.
A call's record stamped the scopes its lookup walked with their addresses and sizes. extend() hands out the block the last dropped scope left, so a host that rewired outer, dropping a scope, and built a replacement with as many bindings got the same address and the same stamp: the apply step then used the dropped scope's binding node, kept (holding nil) or freed. Each environment now has a serial, drawn when it is made, copied or assigned, and when extend() makes a scope in a kept block. Serials come from one count, a run of 1024 per thread at a time, so no two scopes share one until 2^32 have been made. The stamp mixes the serial in with the address. It is 4 bytes in the padding after `frozen`, so a scope is no larger (88 bytes on 64-bit MSVC before and after).
ExtendedScopeComesBackEmpty expected the next scope to be the one just dropped, which had bindings. Only MSVC keeps such a scope (its maps have 8 buckets from the start); libstdc++ and libc++ free it, so the check held only when the allocator happened to hand the same block back, and fails under ASan. The test now takes the thread's kept scopes first, so the pool has room, expects the same address only when the dropped scope had a new map's bucket count, and otherwise checks what holds everywhere: the next scope is empty, unfrozen and in the given scope.
The known-pathology bullets for per-form argument copies and string dispatch (with the step count's atomic increment) and for the (begin ...) body rebuilt on every call described the old code as current. Each now says what changed, as the scheduler and async bullets do, and the closure_body scenario no longer says its body is rebuilt on every call.
…ss steps The step-count notes said increment_step() adds to a counter the evaluators never write. The stackless evaluator writes it too, for its read and data steps (and the async evaluator for each of its steps). What keeps another thread's count is that every one of those writes is a locked add: only count_eval_step() stores plainly, and only to eval_step_count. increment_step()'s comment and the bench doc now say so, and name the one step where a count from another thread can still be lost, as at base: the step that ends a script read in slices moves the stats into the program's state, and a move copies the counts. The new test races increment_step() against a stackless evaluator that reads a script a token per step and walks data two nodes per step. It fails if those steps count with a plain store.
transfix
marked this pull request as ready for review
October 27, 2026 23:32
transfix
enabled auto-merge (squash)
October 27, 2026 23:33
The required clang-format (changed lines) check runs only on PRs against master, so it first ran when this PR was retargeted from #834's branch. Formatting only.
Owner
Author
Final A/B results (all three tracks)This is the A/B the description said would be posted here. It ran on 2026-10-27 against a7b966f, with Release builds of the state_exec benchmark on the same Windows machine as before.
Some absolute times for all three tracks together (phase 1, median wall time):
The combined build regresses nowhere:
Notes on single tracks:
|
This was referenced Oct 28, 2026
Merged
Merged
transfix
added a commit
that referenced
this pull request
Oct 28, 2026
The project version and the cvcpkg recipe family move to 3.7.2. Every recipe is at cvc_revision 1 already, so none restarts. 3.7.2 carries the dynamic plants on the terrain and in a Jolt world, and the four-wheel plant (#869): --plant dynamic and dynamic4w drive the ground, collide with the buildings and each other, and book the collisions. It also carries dyn_4w's port-Hamiltonian form (#850), dyn_bike's wheel-frame front slip (#852), the books goldens for GRL-SNAM's twins (#848, #849), pycvc's drive telemetry (#857) and keep-alives (#864), the macOS SDK's openssl (#846), and the state_exec scheduler and evaluator work (#842, #843, #844, #861, #863).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This branch speeds up both evaluators (recursive and stackless) and the parser, and fixes everything the review found. It sits on #834 (the benchmark suite). It changes no scheduler, async_host, app or thread_pool code.
What changed
Special-form dispatch:
special_form_of()switches on a name's length and letters, replacing up to 19 string compares per call form. Precedence is unchanged: special forms, then macros, then bindings.Variable lookup: a name is hashed once per lookup, not once per scope, and empty scopes are skipped.
Call scopes are recycled per thread. A scope and its control block are one allocation: a 32-byte slot followed by the scope, as with make_shared. A scope is kept only while it is empty and has a new map's bucket count. Binding nodes are reused. A kept binding node is left holding nil, not a moved-from value. libc++ moves a
std::functionwhose callable fits its small buffer by copying the callable. Without this, a kept node would keep a native function's captures alive until the node was reused (in some other process's step) or the thread exited. For a class constructor, that means its class dict, its methods and the scopes they captured.A call's function is looked up once, at init. The apply step reuses that binding only while the scopes the lookup walked are unchanged:
environment::serial, a 32-bit serial drawn when a scope is made, copied or assigned, and again whenextend()makes a scope in a kept block. So a host rewiringouteris detected even when the replacement scope sits in the dropped scope's block with as many bindings.The mark is computed in the init lookup's own walk.
Fewer allocations per step:
Shared closure bodies: a closure with a multi-form body shares one
(begin ...)with the other closures its lambda form makes. A generator gets its own copy. Forms match only if they evaluate the same: lists by object, numbers bit for bit (0.0 is not -0.0, and a NaN matches itself).Step counting: the recursive and stackless evaluators count their own eval steps with a plain load and store of
eval_step_count, which only the stepping evaluator writes (count_eval_step()). Publicincrement_step()is afetch_addonstep_count, whichcount_eval_step()never writes. Every write tostep_countis a locked add:increment_step()from any thread, the stackless evaluator's own read and data steps, the async evaluator's steps, andadd_steps(). So a count from another thread is not lost while an evaluator steps the state. One exception, unchanged from base: the step that ends a script read in slices (parse_options::step_tokens) moves the stats into the program's state, and the move copies the counts, so a count another thread makes during that one step can be lost.Parser: reads tokens and strings in runs and builds short lists at exact size. Long lists keep their own vector.
Review fixes
call_closure()read the closure after popping the frame that owned its scope. That crashed(defun twice (f x) (f (f x))) (twice inc 5), and(call-it (lambda () 42))already crashed on the old code. Fixed, with tests on both evaluators and both schedulers.(begin ...)is replaced by the shared one: 2-form closures cost 434 B each, against 418 at baseline and 717 before this fix.push_framecopies before the stack grows;bind_newfrees the node if the insert throws;increment_step()is safe from any thread again, also while an evaluator steps the state, except in the one step that ends a sliced read (as at base);increment_step()made from another thread is no longer lost against the stepping evaluator's eval-step count.(begin ...)is no longer shared between forms that differ only in the sign of a zero.ExtendedScopeComesBackEmptyno longer depends on allocator reuse off MSVC.increment_step()'s comment names the one step where another thread's count can still be lost.Numbers
Interleaved A/B against baseline a7b966f, pinned to lp 16, 3 to 5 rounds x 3 reps. The machine was at 100% CPU, so noise is high and driver CPU is the steadier figure.
Allocations per iteration fall to zero on most eval.* points, e.g. fib 16.5 -> 0.19, closure_calls 24 -> 0, closure_body forms=3 41 -> 0, arith_loop 18 -> 0.
eval. wall time* improves 30-60% on both executors:
sched.single.*: -6 to -21% wall on the sync scheduler, -5 to -18% on the async scheduler.
native.*: mostly faster, e.g. plain sync -19%, state_set async -29% (depth=1).
Many-process points the review flagged:
sched.scaling sync p=1000 and sched.bystanders sync b=1000 still lean slower on wall time (+7..+17% median across two runs), but their driver CPU is flat (-0.4%, +0.2%) and noise is about 15%. Worth a recheck on a quiet machine.
Memory:
Deep stacks therefore retain 7% more (eval.tail_rec).
environment::serialsits in padding:sizeof(environment)is 88 bytes on 64-bit MSVC with and without it (measured), so the table stands.Per-thread caches: under about 35 KB of scopes and nodes and about 41 KB of frame vectors. The recursive evaluator keeps at most about 37 KB.
Tests
state_exec_async_calls_testAS8 and AS24;test_pycvc_state_exec_async.py::test_a_python_kernels_wait_for_the_gil_isnt_chargedis unchanged from base and fails intermittently while the machine is loaded (0.13 to 0.19 s against its 0.2 s bound). It passes on rerun.increment_step()against a stepping evaluator: one through eval steps on both evaluators, and one through the stackless evaluator's read and data steps.Risks
static_asserton libstdc++ and libc++. Nothing was built on Linux or macOS here.bindingsmap, must clear waiting frames' records (documented oneval_frame). Neither action changes a scope's serial.shared_ptrcopy per step (lifetime);