Multithreaded runtimes and numerical libraries are difficult to verify with ordinary unit tests because rare thread interleavings can hang a program after millions of passing runs. Programs using these runtimes while performing floating-point calculcations can accumulate additional errors from imprecise math functions returning zero, infinity, or NaN on extreme valid inputs. Using formal verification tools such as Temporal Logic of Actions (TLA+) and Herbie, we can find both classes of defects before deployment. But implementation and specification often drift apart substantially as development continues.
In this rather extensive post, I want to discuss my work on single-source models (SSMs), a design pattern in which the formal specification and the production implementation live inside one source declaration and are verified automatically during compilation before object code is emitted. To evaluate this pattern on a demanding real-world system, single-source models were applied while modernizing and extending Weave, a message-passing parallel runtime for Nim. Running these checks during compilation uncovered six concurrency bugs in Weave and one in Nim’s standard atomics, ten numerical degredations in Nim’s standard math library, and prevented two rounding hazards in my double-double vector math module, while keeping runtime performance competitive with Intel oneTBB and LLVM OpenMP.
SSMs as a pattern can be applied to any language with a sufficiently powerful compile-time metaprogramming system (e.g. Nim, Rust, Terra, Zig, etc.), they do not rely on the language to be proof-oriented (e.g. F*).
Title image: Real execution trace of Weave running six hybrid parallel waves across 18 Apple Silicon cores (6 Super cores top, and 12 Performance cores bottom). Each horizontal track is a worker executing tasks with cross-worker work steals (terracotta links), parallel loop splits (gold traces), dataflow event triggers (blue traces), and global synchronization barriers (vertical white lines).
- Introduction
- Background on TLA+, TLC, TLAPS, GenMC, Herbie, and FPCore
- Single-source models in detail
- Concurrency bugs found with TLA+
- Floating-point bugs found with Herbie
- Comparative evaluation
- Scope and limits
- Closing Remarks
- References
- Notes
Introduction
I have built several projects on Weave, a multithreading runtime for Nim originally created by Mamy Andre-Ratsimbazafy (2019), including the parallel nearest-neighbor search engine in Findsight. Across those projects, I repeatedly encountered rare hangs that never appeared in unit tests because they required specific thread schedules. In the past three years, I applied Weave to problems in 3D geometry, across modules concerned with path-tracing, mesh simplification, NURBS geometry and more. Certain steps in those applications require additional precision, beyond the usual IEEE floats, as they would subtly break on extreme coordinates, tiny subnormal numbers, or sums that cancel across large magnitudes. Geometry kernels are built on layers of increasing complexity, so a tiny error or NaN propagation in the fundamental math causes major issues down the road.
Beyond my own work, formal verification is all the rage these days, with rapidly accelerating machine-assisted proofs generated by AI and checked by (various implementations of) Lean. While I’m not quite ready to share the revised Weave version I’ve been working on, I thought it important to talk about the concept of SSMs, as I’ve seen a tremedous improvement in correctness and soundness in code written by AI, when forced to use SSMs. The verification tools used here, and explained in detail in later sections, represent in my opinion a dramatically more useful set for the common programmer (read: not a well-funded mathematician with infinite tokens to spend), as that programmer is vastly more likely to encounter concurrency bugs than unsolved math mysteries. Though where Lean is useful, the concept of SSMs can be extended to it. We have long surpassed the point where “what language is an LLM good/bad at” is even a useful question, as inherent knowledge merely serves to glue tool calls and, and this is the important bit, verifiable goals together.
With that said, I’ve tried to be as precise as possible in this write-up, and you need no prior knowledge of any of the tools involved, nor Nim, nor Weave. Still, I invite you to consider the cited references further reading.
To understand why Weave exists in the first place, consider how modern multicore programs divide work. Operating system threads are expensive to create and switch, so when a program splits a computation into millions of small independent pieces, a parallel runtime maintains one worker thread per CPU core and distributes those small tasks automatically so no core sits idle while another is overloaded. In mainstream parallel runtimes such as Intel oneTBB, LLVM OpenMP, Cilk, and Rust’s Rayon, each worker holds a double-ended queue of pending tasks, pushes and pops its own tasks at one end, and lets idle workers reach directly into the opposite end of a busy worker’s queue to steal surplus work (a concurrent shared queue known as a Chase-Lev deque, Chase & Lev, 2005). Because multiple CPU cores read and write that shared queue simultaneously, every local task operation requires careful atomic synchronization.
- Owner pushes T3 at bottom with an atomic release store.
- Owner pops T3 from bottom after a memory fence.
- Thief steals T1 directly from top via atomic CAS.
- On the final task T2, owner and thief contend via atomic CAS.
Mamy Andre-Ratsimbazafy (2019) built Weave around an alternative design grounded in research by Acar et al. (2013) and Prell (2016). In Weave, every worker owns its task queue privately, eliminating concurrent access from the common local path. When a worker runs out of tasks, it sends an explicit theft request message to another worker over a small communication channel, and the busy worker replies with stolen tasks through a private return slot (a message-passing work-stealing architecture). To avoid pausing CPU cores behind traditional mutual-exclusion locks - which serialize execution when many cores coordinate at microsecond timescales - workers exchange those messages using atomic CPU instructions without blocking locks (a lock-free design). After Nim 1.2, Weave was left unmaintained while Nim adopted deterministic ARC and ORC memory management. Message passing has grown massively in popularity, and its use in the next version of Nim (Nimony, or Nim 3) is discussed at the end. In general, the Go devs’ mnemonic is a good one: we don’t communicate by sharing memory, we share memory by communicating.
- Owner pushes T4 locally with plain pointer writes (zero atomics).
- Idle Worker 1 sends a theft request to Worker 0's MPSC inbox.
- Worker 0 splits T1 and T2 privately and replies via SPSC mailbox.
- Worker 1 unpacks T1 and T2 into its own private deque.
While updating Weave for Nim 2 and Apple Silicon, I added portable SIMD (based on nimsimd, but extended primarily for modern Arm64), 3D vector math, extended-precision arithmetic represented as the unevaluated sum of two 64-bit floats (double-double arithmetic, introduced by Dekker, 1971), and pure-Nim matrix multiplication (GEMM).
- On the binary64 number line, gaps double at each power of 2, so an exact sum a + b falls between representable ticks.
- A single 64-bit float snaps to the nearest tick hi and drops the low-order residual bits past bit 52.
- Dekker's TwoSum captures the rounding residual e into a second 64-bit float lo scaled to exponent exp - 53.
- Combining hi + lo subdivides the gap with 106 significand bits, restoring the exact position of a + b.
DDA is broadly useful for 3D operations such as mesh simplification, tests for watertightness in geometry kernels and related work where fixed point math would be ideal, but is infeasible to implement in a performant way.
Background on TLA+, TLC, TLAPS, GenMC, Herbie, and FPCore
Leslie Lamport (2002) created Temporal Logic of Actions (TLA+) for specifying concurrent systems as mathematical state machines with explicit safety invariants and temporal liveness properties. TLA is fairly easy to understand, and has been applied in countless ways to find and squash bugs in concurrent systems, from stdlib allocation to distributed databases.
To check finite models, Yuan Yu, Panagiotis Manolios, and Leslie Lamport built TLC at Compaq Systems Research Center (Yu et al., 1999). Using TLC, every reachable interleaving for a bounded number of worker threads and work items can be enumerated against both safety invariants and liveness properties.
Because finite model checking with two or three workers cannot prove that a protocol stays safe at larger thread counts, Denis Cousineau, Damien Doligez, Leslie Lamport, Stephan Merz, Daniel Ricketts, and Hernan Vanzetto built the TLA+ Proof System (TLAPS) at the Microsoft Research-INRIA Joint Centre (Cousineau et al., 2012). With TLAPS, structured hierarchical induction proofs can be written over arbitrary finite sets and unbounded natural numbers, and the proof manager splits each theorem into independent obligations dispatched to automated provers such as Zenon, Isabelle, and SMT solvers like Z3. It’s verification all the way down.
Even an unbounded TLA+ proof assumes that all CPU cores observe memory writes in a single global order (sequential consistency), whereas real Arm and x86 processors reorder loads and stores for speed (weak memory models). To check hardware memory ordering, Michalis Kokologiannakis and Viktor Vafeiadis (2021) created GenMC at the Max Planck Institute for Software Systems (MPI-SWS) as a stateless model checker for C and C++ programs under the C11 and C++11 memory models.
For floating-point accuracy, Pavel Panchekha, Alex Sanchez-Stern, James R. Wilcox, and Zachary Tatlock created Herbie at the University of Washington (Panchekha et al., 2015) around FPCore, a standardized S-expression (lispy) format from the FPBench project for encoding floating-point benchmarks. In an FPCore record, we specify a formula’s input variables, its IEEE-754 floating-point precision (such as binary64), its input domain preconditions (:pre), its exact real-number mathematical reference (:spec), and the floating-point implementation body to evaluate. Running Herbie on an FPCore file reports each expression’s average error in bits relative to arbitrary-precision real arithmetic across sampled inputs, along with algebraically equivalent rewrites that lower rounding error. You can try this live on the linked Herbie site.
To summarize, here’s our toolset:
| Verifier | Bug class targeted | Guarantee boundary | Complementary check |
|---|---|---|---|
| TLC | Protocol deadlocks, lost wakeups, premature frees | Exhaustive over finite bounds (2 to 3 workers) | TLAPS symbolic induction |
| TLAPS | Unbounded safety invariants across any thread count | Sequential consistency over abstract transitions | GenMC weak-memory checking |
| GenMC | C11 and C++11 weak-memory data races on Arm64 and x86 | Declared atomic contracts in litmus harnesses | Sanitizers and hardware stress runs |
| Herbie | Catastrophic cancellation, overflow, underflow | Average bit error across 128 sampled points | Exact IEEE-754 edge-case unit tests |
All four tools are effective on their own, yet keeping .tla and .fpcore specifications in separate directories invites a recurring maintenance failure. Editing an atomic memory order or refactoring a math routine without updating the external file leads to stale models and vacuous proofs.
Single-source models in detail
Because Nim executes user-defined macros during semantic analysis with access to the typed syntax tree, both the formal model and the production Nim code can be declared inside one block, verified with TLC and Herbie during nim c, and compiled to object code only after every check succeeds.
Anatomy of a concurrency SSM
In one of Weave’s concurrency modules, a singleSourceModel block defines the state machine and the production atomic primitives together. Below is an abridged view of the worker-parking model, EventNotifier, which coordinates multiple producer threads waking one sleeping consumer thread:
singleSourceModel EventNotifier:
model "event_notifiers", extends = [FiniteSets, Naturals, TLC]
constants Producers
assume Producers != {}
vars [consumerState, mutexOwner, generation, ticket,
produced, notified, pending, consumed]
domain ConsumerStates, EventNotifierConsumerState, lowerCamel:
encRunning
encPrepared
encParked
encDone
init:
consumerState == encRunning
mutexOwner == enoNoOwner
generation == 0
ticket == 0
produced == {}
notified == {}
pending == {}
consumed == {}
action enaNotify(p in Producers), strong:
p in difference(produced, notified)
mutexOwner == enoNoOwner
notified <- union(notified, {p})
generation <- generation + 1
consumerState <- (
if consumerState == encParked: encRunning
else: consumerState
)
nim:
template eventNotifierAdvanceGeneration*(generation: untyped): int32 =
generation.fetchAdd(1, moRelease)
invariant eniNoLostWakeup:
consumerState == encParked ==> (
ticket == generation and
mutexOwner == enoNoOwner and
subseteq(pending, difference(produced, notified))
)
property enpTermination:
eventually(consumerState == encDone)
config default:
Producers = {p1, p2, p3}
mutation enmLoseGeneration = "notifier-loses-generation":
action enaNotify:
p in difference(produced, notified)
mutexOwner == enoNoOwner
notified <- union(notified, {p})
generation <- generation
consumerState <- (
if consumerState == encParked: encRunning
else: consumerState
)
To write a concurrency SSM, we compose nine declarative clauses inside singleSourceModel:
model and extends, name the in-memory TLA+ module and import standard TLA+ operator libraries such as FiniteSets, Naturals, and TLC.
constants and assume declare symbolic model parameters (here the set Producers) and preconditions that every configuration must satisfy.
vars lists every mutable state variable tracked from step to step.
domain declares one finite set of states that expands simultaneously into a TLA+ set constant (ConsumerStates) and an exported Nim enum (EventNotifierConsumerState) with identical string values, ensuring that formal state names and runtime enum values match. Mismatches lead to IDE and compiler errors.
With init, we specify the initial-state predicate that holds before any thread takes a step.
action declares one atomic transition, optionally parameterized over a set such as p in Producers. Plain boolean expressions act as enabling guards, <- assigns next-state values (rendered as primed variables such as generation' in TLA+), and any omitted variable is framed automatically as UNCHANGED. Adding weak or strong attaches a TLA+ fairness clause requiring that an enabled action eventually runs so temporal liveness properties can be proved, while an embedded nim: block holds the production atomic template (here generation.fetchAdd(1, moRelease)) emitted into the compiled binary only after TLC succeeds.
With invariant and property, we declare safety predicates that must hold in every reachable state (invariant) and temporal liveness claims (property, such as eventually(consumerState == encDone)).
config binds concrete finite values to constants for TLC exploration (here three producers, {p1, p2, p3}).
Finally, mutation defines a named faulty replacement for one or more actions so we can compile with that mutant enabled and verify that TLC rejects it on the intended invariant.
During compilation, the in-memory TLA+ module is rendered directly from that single Nim block. Below is an excerpt of the actual TLA+ generated from the EventNotifier declaration above:
---------------------------- MODULE event_notifiers ----------------------------
EXTENDS FiniteSets, Naturals, TLC
CONSTANT Producers
ASSUME (Producers # {})
VARIABLES
consumerState, mutexOwner, generation, ticket,
produced, notified, pending, consumed
ConsumerStates ==
{"running", "prepared", "parked", "done"}
Notify(p) ==
/\ (p \in (produced \ notified))
/\ (mutexOwner = "no-owner")
/\ (consumerState' = (IF (consumerState = "parked") THEN "running" ELSE consumerState))
/\ (generation' = (generation + 1))
/\ (notified' = (notified \cup {p}))
/\ UNCHANGED <<mutexOwner, ticket, produced, pending, consumed>>
Before accepting a model, the build runs the generated specification through three complementary verification stages:
Self-audits and formal mutations with TLC
Because a bounded model checker can succeed vacuously when a transition never fires or an invariant is omitted from a configuration, we run three automatic self-audits in TLC on every uncached build:
- Coverage counts from TLC are checked, halting compilation if any declared action records zero executions.
- Each invariant and temporal property is replaced with
FALSEone at a time, requiring TLC to fail naming that exact claim. - Each fairness clause is removed in turn, requiring at least one liveness property to fail without it.
Beyond self-audits, 16 deliberate mutations across the nine modeled modules are used to verify that the invariants actually reject real protocol errors (covering lost notifier generations, premature arena release, premature pool destruction, duplicate dataflow consumers, premature future reclamation, abandoned ordered work, and invalid shutdown claims). For example, compiling the EventNotifier module with -d:WV_FormalMutation:notifier-loses-generation substitutes the broken enaNotify body from the mutation clause above (leaving generation unchanged), runs TLC, and halts compilation with a three-state counterexample trace showing notified = {p1} while generation = 0:
State 1: <Initial predicate>
/\ pending = {} /\ generation = 0 /\ produced = {} /\ notified = {}
State 2: <Publish(p1) line 47>
/\ pending = {p1} /\ generation = 0 /\ produced = {p1} /\ notified = {}
State 3: <Notify(p1) line 53>
/\ pending = {p1} /\ generation = 0 /\ produced = {p1} /\ notified = {p1}
Unbounded inductive proofs with TLAPS
Checking a protocol with two workers and three items in TLC yields quick counterexamples, yet finite checking cannot prove that a counter conservation or idle-certification invariant still holds for 18 or 128 workers. To prove safety over arbitrary finite sets of workers and work items, a parameterized safety model inside singleSourceModel shares one set of TLA+ definitions between a finite TLC sanity check and a symbolic TLAPS induction proof (Cousineau et al., 2012).
Inside the same single-source block, the inductive invariant covers counter conservation across admission, removal, and delayed settlement (Accounting), unique live reference ownership (UniqueOwnership), reclamation only after return (ReclamationSafety), and recursive child-idle certification (IdleCertificateSafety):
invariant psiAccounting:
total == pending + removedUnsettled + settled
invariant psiUniqueOwnership:
forall(
item in Items,
((item in reclaimed) ==> (owner[item] == NoOwner)) and
((item notin reclaimed) ==> (owner[item] in Workers))
)
invariant psiReclamationSafety:
subseteq(reclaimed, returned)
invariant psiIdleCertificateSafety = "IdleCertificateSafety":
forall(
worker in certified,
worker notin busy and
forall(child in Workers, Child(worker, child) ==> (child in certified))
)
Right beside those declarations, structured TLAPS theorems prove that Init implies Invariant, that every action preserves Invariant (BY SMT, discharged by Z3), and that the full specification satisfies \(\Box\,\mathrm{Invariant}\) by propositional temporal logic (BY PTL):
THEOREM InitInvariant ==
(Init => Invariant)
BY SMT DEF Init, Invariant, ConstantAssumptions, Child, Stages,
NoOwner, Owners, TypeOK, Accounting, UniqueOwnership,
ReclamationSafety, IdleCertificateSafety
THEOREM AdmitPreservesInvariant ==
((Invariant /\ Admit) => Invariant')
BY SMT DEF Invariant, ConstantAssumptions, Child, Stages, NoOwner,
Owners, TypeOK, Accounting, UniqueOwnership, ReclamationSafety,
IdleCertificateSafety, Admit
THEOREM ParameterizedSafety ==
(Spec => [](Invariant))
<1>1. ((Invariant /\ UNCHANGED vars) => Invariant')
BY SMT DEF Invariant, ConstantAssumptions, Child, Stages, NoOwner,
Owners, TypeOK, Accounting, UniqueOwnership, ReclamationSafety,
IdleCertificateSafety, vars
<1>2. (Spec => [](Invariant))
BY PTL, InitInvariant, NextPreservesInvariant, <1>1 DEF Spec, vars
<1> QED
BY <1>2
Compiling with -d:WV_CheckTLAPS invokes tlapm --strict directly on the macro-rendered TLA+ file plus those theorem blocks. Because both the finite TLC configuration and the TLAPS proof use the exact same generated TLA+ operators, compiling after any edit to an action or invariant checks both automatically.
- TLC enumerates every reachable state from $S_0$ across finite domains ($N \in \{2, 3\}$) and evaluates every invariant on each state.
- Under a deliberate mutation, TLC halts on a concrete counterexample state ($S_5$) violating the named invariant.
- TLAPS proves the base case ($\mathrm{Init} \Rightarrow \mathrm{Invariant}$) and inductive step ($\mathrm{Inv} \land \mathrm{Next} \Rightarrow \mathrm{Inv}'$) symbolically via Z3.
- Propositional temporal logic closes the theorem ($\Box\,\mathrm{Invariant}$ for all $N$) using the same generated TLA+ operators.
Weak-memory contracts and GenMC litmus harnesses
Neither TLC nor TLAPS models weak hardware memory reordering. Changing an atomic release store to a relaxed store in Nim leaves the TLA+ state machine identical so it still passes both TLC and TLAPS, yet on an Arm64 CPU a consumer thread can observe the published flag before seeing the payload written ahead of it.
To verify weak memory ordering as well, atomic operations, actors, primitives, and memory orders are declared once in a typed protocolSteps table inside the single-slot and multi-producer channel SSMs. Below is the atomic-step table for Weave’s single-slot single-producer single-consumer (SPSC) channel:
protocolSteps SpscSingleSteps, SpscSingleRefinement,
SpscSingleStep, SpscSingleOperation, SpscSingleActor,
SpscSingleLocation, SpscSingleAbstractAction:
sssProducerObserve:
operation ssoTrySend
actor ssaProducer
location sslOccupancy
primitive papLoad
successOrder pmoAcquire
role psrObservation
refines saaNoVisibleEffect
sssProducerPublish:
operation ssoTrySend
actor ssaProducer
location sslOccupancy
primitive papStore
successOrder pmoRelease
role psrPublication
refines saaPublishItem
sssConsumerObserve:
operation ssoTryRecv
actor ssaConsumer
location sslOccupancy
primitive papLoad
successOrder pmoAcquire
role psrObservation
refines saaNoVisibleEffect
sssConsumerRelease:
operation ssoTryRecv
actor ssaConsumer
location sslOccupancy
primitive papStore
successOrder pmoRelease
role psrCleanup
refines saaConsumeItem
From that single table, the build emits both the Nim atomic wrappers and a C++11 contract header containing the exact same memory orders:
namespace weave_spsc_contract {
template <typename Atomic>
inline auto spscProducerObserve(Atomic& occupancy) {
return occupancy.load(std::memory_order_acquire);
}
template <typename Atomic, typename Value>
inline void spscProducerPublish(Atomic& occupancy, Value value) {
occupancy.store(value, std::memory_order_release);
}
template <typename Atomic>
inline auto spscConsumerObserve(Atomic& occupancy) {
return occupancy.load(std::memory_order_acquire);
}
template <typename Atomic, typename Value>
inline void spscConsumerRelease(Atomic& occupancy, Value value) {
occupancy.store(value, std::memory_order_release);
}
} // namespace weave_spsc_contract
The build also emits a small two-thread C++ program (a litmus test) that exercises slot publication and slot reuse through that generated header so GenMC (Kokologiannakis & Vafeiadis, 2021) can exhaustively explore every C++11 weak-memory interleaving:
std::atomic<bool> full;
int payload;
void* producer(void*) {
__VERIFIER_assume(!spscProducerObserve(full));
payload = 101;
spscProducerPublish(full, true);
__VERIFIER_assume(!spscProducerObserve(full));
payload = 202;
spscProducerPublish(full, true);
return nullptr;
}
void* consumer(void*) {
__VERIFIER_assume(spscConsumerObserve(full));
assert(payload == 101);
spscConsumerRelease(full, false);
__VERIFIER_assume(spscConsumerObserve(full));
assert(payload == 202);
spscConsumerRelease(full, false);
return nullptr;
}
Under GenMC on the base contract, every allowed C++11 execution satisfies both payload assertions without a data race. Enabling a weak-memory mutation such as spsc-relaxes-publication (which changes pmoRelease to pmoRelaxed in the generated C++ header while leaving the TLA+ model unchanged) causes GenMC to detect a C++11 data race immediately where the consumer observes full == true without a happens-before edge from payload = 101.
- Producer Core 0 writes payload = 101 into the channel slot before publishing the flag.
- Under the relaxed mutation, Core 0 stores full with no release fence, whereas the verified contract emits a release store.
- On weak-memory hardware, relaxed ordering allows full == true to reach Core 1 before payload = 101, whereas acquire-load pairs with release-store to order prior writes.
- GenMC immediately flags a C++11 data race on the relaxed mutant while proving every allowed execution under release-acquire reads payload == 101.
To avoid repeating unchanged proofs on every build, each rendered model, configuration, and verifier version is hashed into a local proof cache. Verifying the entire runtime from an empty cache - ten TLA+ models with self-audits plus 24 Herbie numerical models and 19 paired mutations - took 110.55 seconds on my test workstation, whereas a warm-cache build completed in 1.83 seconds.1
Anatomy of a numerical SSM
To verify floating-point accuracy without hand-translating Nim formulas into separate FPCore files, generic Nim templates are paired with compile-time symbolic execution inside a singleSourceNumerics block, following the two-path build flow below:
Below is the scaled 3D vector normalization kernel from the double-double math module:
singleSourceNumerics DoubleDouble:
floatingPoint:
precision binary64
rounding nearestEven
subnormals gradual
contraction explicit
template scaledLength3Core*(
x, y, z, scale, multiplyAddOperation, squareRootOperation: untyped
): untyped =
block:
let
scaleValue = scale
scaledX = x / scaleValue
scaledY = y / scaleValue
scaledZ = z / scaleValue
squared = multiplyAddOperation(
scaledX, scaledX,
multiplyAddOperation(scaledY, scaledY, scaledZ * scaledZ)
)
scaleValue * squareRootOperation(squared)
model ddnmScaledNormalize3:
name "dd-scaled-normalize3-component"
category "vector-normalization"
inputs x, y, z
bounds:
x in -1e300 .. 1e300
y in -1e300 .. 1e300
z in -1e300 .. 1e300
x != 0 or y != 0 or z != 0
reference:
x / sqrt(x * x + y * y + z * z)
evaluate:
let
scale = fpMax(fpMax(fpAbs(x), fpAbs(y)), fpAbs(z))
norm = scaledLength3Core(
x, y, z, scale, symbolicRoundedMulAdd, fpSqrt
)
x / norm
proof:
averageErrorBits <= 0.05
mutation:
name "dd-normalize3-squares-before-scaling"
gapBits:
averageErrorBits >= 10.0
evaluate:
x / fpSqrt(x * x + y * y + z * z)
To write a numerical SSM, you combine seven declarative clauses inside singleSourceNumerics:
- With
floatingPoint, you pin the IEEE-754 evaluation model (binary64precision, round-to-nearest-even, gradual underflow for subnormal numbers, and explicit fused multiply-add contraction). - With the generic
template(scaledLength3Core), you write the arithmetic algorithm once. Runtime functions instantiate it with hardwarefloat64orDoubleDoubleoperators, whereas the compile-time model evaluates the exact same template on symbolicFpcoreValuenodes (fpAbs,fpMax,fpSqrt) to record the expression graph directly. - With
inputsandbounds, you declare the free variables and valid input ranges rendered into FPCore’s:preprecondition. - With
reference, you write the exact real-number mathematical formula rendered into FPCore’s:specfield so Herbie has an arbitrary-precision oracle. - With
evaluate, you invoke the production template symbolically to produce the FPCore body under test. - With
proof, you set the maximum permitted average error in bits (averageErrorBits <= 0.05). - With
mutation, you retain a known-bad formula (here unscaled normalization \(x / \sqrt{x^2 + y^2 + z^2}\)) alongside a minimum error gap (gapBits: averageErrorBits >= 10.0), requiring the broken formula to lose at least 10 more bits than the baseline so you know the input bounds actually reproduce the failure.
At compile time, symbolically executing ddnmScaledNormalize3 emits the following FPCore S-expression directly to Herbie 2.3:
(FPCore (x y z)
:name "dd-scaled-normalize3-component"
:precision binary64
:round nearestEven
:pre (and
(and (<= -1e+300 x) (<= x 1e+300))
(and (<= -1e+300 y) (<= y 1e+300))
(and (<= -1e+300 z) (<= z 1e+300))
(or (or (!= x 0) (!= y 0)) (!= z 0)))
:spec (/ x (sqrt (+ (+ (* x x) (* y y)) (* z z))))
(let*
(
[t0 (fabs x)]
[t1 (fabs y)]
[t2 (fmax t0 t1)]
[t3 (fabs z)]
[t4 (fmax t2 t3)]
[t5 (/ x t4)]
[t6 (/ y t4)]
[t7 (/ z t4)]
[t8 (* t7 t7)]
[t9 (* t6 t6)]
[t10 (+ t9 t8)]
[t11 (* t5 t5)]
[t12 (+ t11 t10)]
[t13 (sqrt t12)]
[t14 (* t4 t13)]
[t15 (/ x t14)]
)
t15))
During compilation, Herbie 2.3 runs with a fixed seed (20260719) and 128 sampled points per expression, the JSON report is validated (version, seed, point count, status, and start/end bit error) and cached, and compilation halts if any baseline exceeds its bit budget or any mutation falls below its required error gap. Because 128 sampled points do not cover discrete IEEE-754 corner cases, subnormals, signed zeros, infinities, NaNs, and complex branch cuts are checked in separate runtime unit tests.
Concurrency bugs found with TLA+
Running TLC and memory-order contract checks during compilation uncovered six concurrency bugs in Weave’s inherited runtime and in Nim’s standard atomics wrapper.
Premature memory reclamation during remote frees
In a thread-local memory pool, one worker thread allocates fixed-size memory blocks from a contiguous region (an arena), and another worker thread may later free those blocks remotely by pushing them onto a lock-free queue where many producers append while the owning thread consumes (a multi-producer single-consumer, or MPSC, queue). To track how many blocks were still live, a producer incremented the queue’s approximate counter before linking its freed block onto the tail of the list. If the owning thread subtracted that approximate queue counter from its arena usage counter during that window, it saw a net count of zero and released the entire arena back to the operating system while the remote producer still held a pointer into that arena and was about to write the link pointer.
Modeling the four states of a memory block in TLA+ (running, cached on a remote worker, in transit on the return queue, and returned to its owning pool) with a safety invariant requiring every block in a released arena to be back in its owning pool caused TLC to produce a trace where the owner freed an arena while a block was still in transit. Under the fix, arena reclamation ignores the approximate remote counter and releases an arena only after the owning thread detaches returned nodes from the queue and observes its own local live-block count reach zero. All in-flight remote writes complete before the owning thread can unmap the arena.
- Remote producer increments the approximate queue counter before linking its freed block.
- Before the fix, the owner subtracts that counter and sees zero live blocks, whereas with the fix the remote link completes first.
- Before the fix, the owner unmaps the arena immediately, whereas with the fix the owner detaches the returned node and decrements its own count.
- Before the fix, the delayed pointer write hits unmapped memory, whereas with the fix reclamation runs only when local live blocks reach zero.
Lost wakeups during worker parking
Idle worker threads sleep so they stop polling empty queues, while busy threads wake them when new tasks arrive. On Linux and Windows, the operating system provides a fast sleep primitive that avoids kernel transitions when no thread is waiting (a futex), and Weave originally drove it with a single binary flag that the sleeping worker reset to zero before parking. Two producers waking the worker concurrently could toggle that flag twice before the consumer observed it, or the consumer could overwrite a fresh wakeup while resetting the flag, leaving the worker asleep indefinitely. On macOS, where futexes do not exist, the consumer in the mutex-protected wait queue (a POSIX condition variable) checked for pending work, released its mutex, and only later reacquired the mutex to wait, allowing a producer’s signal to arrive in the gap and disappear before the consumer entered wait.
Modeling the consumer’s states (running, prepared to park, parked, and done) alongside a safety invariant requiring that a parked worker never have an unacknowledged notification pending, plus a liveness property requiring the worker to reach completion, caused TLC to produce a counterexample trace whenever a producer could notify without advancing a monotonic counter or whenever a notification could interleave between preparing and parking. On futex platforms, the binary toggle was replaced with a monotonic 32-bit atomic generation counter that producers increment and consumers compare against their last observed ticket before sleeping. On macOS, the consumer now acquires the condition-variable mutex when preparing to park and holds that mutex uninterrupted until wait atomically releases it, while producers signal under the same mutex.
- Before the fix, the worker checks for work and unlocks, whereas with the fix it holds the mutex from preparation onward.
- Before the fix, a producer signal arrives in the unlocked gap, whereas with the fix the worker enters cond_wait atomically under the mutex.
- Before the fix, the worker reacquires the mutex and sleeps, whereas with the fix the producer increments a monotonic generation counter and signals under the lock.
- Before the fix, the missed signal leaves the worker asleep forever, whereas with the fix the worker wakes because its ticket differs from the generation counter.
Stranded tasks and duplicate drains in event signaling
With dataflow events, a caller attaches dependent tasks to a one-shot event so those tasks run automatically once another thread triggers the event. Under the original handshake, a producer checked the event’s boolean triggered flag, saw false, and prepared to enqueue its task onto the event’s deferred queue. Before the producer finished enqueuing, another thread could set the flag to true and drain the queue, leaving the producer’s newly enqueued task stranded forever with nobody left to drain it. A second race occurred when two threads triggered the same event concurrently, electing two simultaneous consumers on a queue designed for a single consumer.
Modeling two concurrent producers and two concurrent trigger threads in TLA+ with two safety invariants - one requiring that every task be scheduled once all actors finish and another requiring at most one thread in the draining phase at any time - produced interleavings under the original boolean check that violated both invariants. The fix adds two atomic counters tracking how many producers have entered and left the enqueue window, paired with a single atomic compare-and-swap (compare-exchange) that elects exactly one trigger thread. A producer increments the entry counter before rechecking the triggered flag, and the winning trigger thread waits until the exit counter matches the entry counter before draining the deferred queue, guaranteeing that all in-flight producers have either run their tasks directly or finished enqueuing them.
- Before the fix, the producer reads triggered as false with no window counter, whereas with the fix it increments in before checking the flag.
- Before the fix, the trigger thread writes true without electing a unique consumer, whereas with the fix a single CAS transitions the flag from false to true.
- Before the fix, the trigger drains an empty queue immediately, whereas with the fix the winning trigger waits until out equals in.
- Before the fix, the late enqueue strands the task forever, whereas with the fix the producer finishes enqueuing and increments out so the trigger drains every task.
Returning cached tasks into destroyed memory pools
Worker threads cache recently completed task blocks locally to reduce allocator traffic, even when those blocks originally came from another worker’s memory pool. During runtime shutdown, workers tore down their pools as soon as the scheduler detected that no runnable work remained. Because one worker could still be flushing its local cache of borrowed blocks while another worker was already unmapping its memory pool, a late remote free could write into freed memory and crash during exit.
Composing the scheduler-termination model with the memory-pool teardown model in TLA+ under a safety invariant requiring that no memory pool be destroyed while any remote worker still holds a cached reference or has a return in transit caused TLC to produce a shutdown interleaving where worker zero freed its pool immediately after termination detection while worker one still held a cached block belonging to worker zero. Shutdown is now split into two globally synchronized phases separated by a barrier. Workers first flush their local task caches and deliver all remote returns, wait at the global barrier until all workers finish flushing, and destroy their own memory pools only after the barrier opens.
- Shutdown begins once the scheduler detects zero runnable work, and with the fix every worker enters a cache-flush phase first.
- Before the fix, Worker 0 destroys pool_0 immediately, whereas with the fix Worker 1 returns its cached block_0 while pool_0 is still alive.
- Before the fix, Worker 1 flushes block_0 afterward, whereas with the fix all workers synchronize at a global barrier once flushes complete.
- Before the fix, the late remote free writes into destroyed memory, whereas with the fix Worker 0 destroys pool_0 only after the barrier opens.
Dangling stack references and copied futures
When a caller spawns an asynchronous task, the runtime returns a future handle that holds the task’s eventual result. Originally, callers could freely copy those handles, allowing two places in user code to consume or free the same underlying result channel. Worse, in lazy mode the runtime allocated the future’s consumer state directly on the calling function’s stack frame to save an allocation. If a caller returned that future from a function or moved it into a data structure while the background task was still running, the producer later wrote its result into an overwritten stack frame.
Modeling producer and consumer ownership as separate claims in TLA+ with safety invariants requiring that results be read only after publication and that channel storage be reclaimed only after both endpoints release their claims immediately failed the accounting invariant on mutations that dropped a consumer early or let a producer reclaim storage before consumer release. Future handles are now move-only under Nim’s ownership hooks so compilation fails statically on a handle copy, and lazy consumer state lives in the memory pool out of the caller’s stack. Both endpoints share an atomic two-bit ownership mask representing the producer and consumer claims, and whichever endpoint clears the final bit recycles the storage safely even if the consumer detaches early.
- Before the fix, lazy future state lives on the caller's stack frame, whereas with the fix it lives in the memory pool with producer and consumer ownership bits.
- Caller returns the future handle to its caller, and with the fix Nim enforces move-only ownership statically.
- Before the fix, subsequent calls overwrite the returned stack frame, whereas with the fix the worker publishes into pool storage and clears bit P.
- Before the fix, the worker writes into the overwritten stack frame, whereas with the fix the consumer reads the result, clears bit C, and recycles the slot.
An invalid atomic failure order in Nim’s standard library
In C11 and C++11 memory models, an atomic compare-and-swap instruction takes two memory orders, one applied when the exchange succeeds and a second applied when it fails. Because a failed compare-and-swap performs only a load, its failure order cannot include release semantics. In Nim’s standard library, however, the convenience single-order overload of compareExchange forwarded the same order argument to both positions, producing an illegal acquire-release failure order.
Because TLA+ models sequential consistency without hardware memory-order tags, TLC cannot catch this defect. It surfaced when strict C++11 contracts generated from the typed atomic-step table ran on Windows with GCC’s C++ runtime assertions enabled, where libstdc++ aborted immediately on the invalid compare-exchange failure order. The atomic-step specification table now requires every compare-exchange to declare valid success and failure memory orders (such as acquire-release on success paired with acquire on failure), backed by a regression test covering the standard-library bug.
- Before the fix, single-order compareExchange takes moAcqRel, whereas with the fix the atomic table declares explicit success and failure orders.
- Before the fix, Nim forwards acq_rel to both positions, whereas with the fix generated code emits acq_rel on success and acquire on failure.
- Before the fix, libstdc++ rejects the release bit on a load-only failure path, whereas with the fix the failure order is load-only.
- Before the fix, Windows C++ assertions abort with SIGABRT, whereas with the fix both strict C++ contracts and GenMC pass.
Floating-point bugs found with Herbie
Ten bugs in Nim’s standard math library
Following Pavel Panchekha’s (2022) audit of Rust’s standard library, an audit of the composed formulas in Nim 2.2.10’s std/math and std/complex (leaving direct platform libm wrappers such as sqrt and hypot untouched) uncovered ten precision defects. Rerunning every case on Nim 2.4.2 confirmed all ten bugs were still present.
In the chart below, the average input error in binary64 bits measured with Herbie 2.3 across 128 points (seed 20260719; lower error is better) compares each Nim 2.4.2 standard-library formula against the single-source replacement:
On concrete edge inputs executed in Nim 2.4.2, we can see how silent corruption compares against the stabilized formulas:
| Operation | Test input | Nim 2.4.2 stdlib | Weave SSM |
|---|---|---|---|
complex.tan |
\(0.25 + 1000i\) | (nan, nan) |
(0.0, 1.0) |
math.arcsech |
\(10^{-320}\) | inf |
737.5203880715338 |
math.arccsch |
\(10^{-320}\) | inf |
737.5203880715338 |
math.sum |
\([10^{150}, 1, -10^{150}]\) | 0.0 |
1.0 |
complex.sinh |
\(10^{-300} + 0i\) | (0.0, 0.0) |
(1e-300, 0.0) |
complex.arcsinh |
\(10^{308} + 0i\) | (inf, 0.0) |
(709.889355822726, 0.0) |
complex./ |
\((10^{308}+10^{308}i)/(10^{308}+10^{308}i)\) | (nan, nan) |
(1.0, 0.0) |
All ten failures can be traced to three “textbook” formulas (as in: naive implementations that don’t hold precision when implement over IEEE floats). In std/complex, sinh, cosh, and tan are written with \((e^z \pm e^{-z})/2\) and \(\sinh(z)/\cosh(z)\) ratios that cancel tiny inputs to zero and overflow large imaginary parts to NaN, so the replacements use scalar component identities and Kahan’s (1987) scaled tanh. In std/math, arcsech and arccsch compute \(1/x\) before applying the inverse hyperbolic function and overflow finite subnormals, so the logarithm is moved across the quotient:
Finally, std/complex./ and inverse hyperbolics square raw operands before dividing or taking square roots while std/math.sum accumulates without compensation, so the replacements add frexp and scalbn exponent scaling along with compensated summation (Neumaier, 1974).
Two hazards in double-double vector math
Herbie also caught two hazards in my new DoubleDouble code. Unscaled 3D vector normalization had an average error of 25.38 bits on large finite coordinates because intermediate squares overflowed, whereas pre-scaling by \(s = \max(\lvert x \rvert, \lvert y \rvert, \lvert z \rvert)\) reduced the average error to 0.02 bits:
On Linux, GCC also fused cross-product terms across double-double rounding boundaries with implicit FMA contraction, which changed the low-order bits relative to Clang, requiring an explicit association barrier to preserve every modeled rounding step.
Comparative evaluation
Because two-owner atomic handles, pool-backed futures, memory barriers, and scaled math add instructions to hot paths, their runtime cost needs measurement on equal terms. The Weave rewrite was benchmarked against Intel oneTBB and LLVM OpenMP (libomp, which uses per-thread work-stealing deques and avoids GCC libgomp’s central mutex queue) on an 18-core Apple M5 Max running macOS 27.2 with 6 Super cores in hw.perflevel0 and 12 Performance cores in hw.perflevel1.
All three runtimes were compiled with Apple Clang 21.0.0 and identical -O3 -flto flags. Synchronization granularity was also matched by testing both per-child futures (Flowvar) and shared node barriers (syncScope), timing 15 to 50 steady-state runs after warmups at both 6 threads (Weave’s now-default performance-core policy) and 18 threads (all cores).
Task parallelism with Fibonacci and 8-ary tree DFS
Recursive fib(36) (14,930,352, spawning about 25M tiny tasks) measures raw scheduler overhead, while balanced 8-ary tree DFS (dfs(8, 8), 20M tasks and 16.7M leaves) measures wide fanout and join barriers.
Below are the minimum, median, and standard deviation in milliseconds across 15 runs, including lazy futures and per-child Flowvar DFS:
| Benchmark | Runtime | 6t min / med / sd (ms) | 18t min / med / sd (ms) |
|---|---|---|---|
fib(36) |
Weave (eager Flowvar) |
149.8 / 157.9 / 4.9 | 65.5 / 76.9 / 6.8 |
fib(36) |
Weave (lazy Flowvar) |
155.0 / 158.5 / 2.0 | 67.6 / 78.7 / 12.3 |
fib(36) |
LLVM OpenMP (libomp) |
211.1 / 214.2 / 1.7 | 170.1 / 217.0 / 54.5 |
fib(36) |
Intel oneTBB (task_group) |
384.6 / 404.1 / 11.5 | 227.4 / 236.7 / 14.2 |
dfs(8, 8) |
Weave (syncScope) |
66.6 / 69.7 / 1.2 | 31.7 / 36.5 / 2.9 |
dfs(8, 8) |
Weave (eager Flowvar) |
145.0 / 149.5 / 4.7 | 75.6 / 92.7 / 17.0 |
dfs(8, 8) |
LLVM OpenMP (libomp) |
116.0 / 120.4 / 1.9 | 64.5 / 105.4 / 49.0 |
dfs(8, 8) |
Intel oneTBB (task_group) |
94.8 / 96.7 / 0.8 | 43.1 / 46.7 / 2.3 |
On fib(36), Weave with eager futures posted the fastest median time at both thread counts, running 1.36x faster than LLVM OpenMP and 2.56x faster than Intel oneTBB at 6 Super cores (157.9 ms), and scaling down to 76.9 ms at 18 threads (2.82x faster than LLVM OpenMP and 3.08x faster than oneTBB) while LLVM OpenMP stalled past 6 threads under heavy task contention. Moving lazy Flowvar state off the caller’s stack into the memory pool for memory safety kept lazy futures within 0.4% to 2.3% of eager futures (158.5 ms at 6 threads and 78.7 ms at 18 threads).
On 8-ary dfs(8, 8), choosing the matching synchronization primitive mattered far more than the formal safety checks. Allocating eight individual Flowvar channels per interior node was 2.14x slower than using a shared syncScope barrier at 6 threads (149.5 ms vs 69.7 ms). With syncScope, Weave beat both Intel oneTBB and LLVM OpenMP at 6 threads (69.7 ms vs 96.7 ms and 120.4 ms) and at 18 threads (36.5 ms vs 46.7 ms and 105.4 ms). The use of syncScope remains stable, even in my own non-benchmarking code, whereas in the first version of Findsight’s KNN engine, I had to work around odd stalls here.
Data parallelism on hybrid Apple Silicon cores
An earlier post on Apple Silicon core scheduling showed that running tightly synchronized loops across heterogeneous core classes increases tail latency. By default, Weave queries hw.perflevel0.logicalcpu (6 Super cores on this machine) and requests QOS_CLASS_USER_INITIATED, while allowing callers to opt into all 18 cores explicitly.
The data-parallel suite compares 2D tiled matrix transposition (4096 x 4096 float32, 64 x 64 tiles, 134.2 MB moved per iteration, 30 runs) across Weave, LLVM OpenMP, and Intel oneTBB, alongside parallel 3D point transforms (Mat4 on 1,000,000 Vec3 points and DDMat4 on 100,000 DDVec3 points).
On 6 Super cores, Weave reached 27.2 GB/s on tiled transposition (4.53x faster than serial, matching LLVM OpenMP at 27.3 GB/s, and behind oneTBB at 34.9 GB/s), a 4.25x speedup on 1,000,000 Mat4 point transforms (0.794 ms serial to 0.187 ms parallel, 0.040 ms std dev), and a 4.33x speedup on 100,000 prepared DDMat4 transforms (9.839 ms to 2.273 ms, 0.111 ms std dev).
Initial 18-core measurements exposed a severe macOS performance bug where Weave collapsed to 12.0 GB/s (11.19 ms median, 8.99 ms std dev) on transpose and to 7.471 ms (3.731 ms std dev) on DDMat4 transforms. Per-worker profiling isolated two compounding causes. First, the macOS EventNotifier fallback held a pthread_mutex_t across prepareToPark and notify, blocking waking parents whenever a child was entering sleep. Second, the four scheduler wait loops (sync, syncRoot, syncScope, and the worker event loop) spun continuously without cpuRelax or sched_yield, so 16 to 17 spinning threads at QOS_CLASS_USER_INITIATED starved any preempted worker holding remaining work for full 10 ms Mach scheduling quanta.
Replacing the macOS parking backend with Apple’s native userspace futex (os_sync_wait_on_address and os_sync_wake_by_address_any on macOS 14.4+, guarded by __builtin_available for the macOS 11 deployment target) under the same verified EventNotifier single-source TLA+ model, together with adaptive cpuRelax and sched_yield backoff in the four scheduler wait loops, resolved the 18-core collapse completely. Across all 18 cores, Weave’s tiled transposition jumped 4.04x to 48.5 GB/s (2.77 ms median, 0.17 ms std dev, right alongside LLVM OpenMP at 50.2 GB/s and within 14% of oneTBB at 56.7 GB/s), Mat4 transforms dropped to 0.143 ms (0.019 ms std dev, 6.08x over serial), and DDMat4 transforms dropped 5.1x to 1.463 ms (0.103 ms std dev, 6.76x over serial), while also cutting 18-core fib(36) from 159.1 ms to 76.9 ms and dfs(8, 8) from 73.3 ms to 36.5 ms.
- Before the fix, macOS EventNotifier held a pthread mutex across prepareToPark and notify, whereas with the fix Apple's os_sync_wait_on_address wakes workers lock-free.
- One worker holding the final tile of a 2.5 ms loop gets preempted by the macOS scheduler.
- Before the fix, the other 17 workers spin at 100% CPU at QOS_CLASS_USER_INITIATED without yielding, whereas SpinBackoff relaxes briefly and calls sched_yield.
- Before the fix, the preempted worker waits an entire 10 ms Mach quantum (12.0 GB/s), whereas with the fix it resumes in microseconds and finishes cleanly (48.5 GB/s).
At this point I also need to point out that the main insight here is Weave’s correctness at comparable or better speeds. Benchmarks such as these between e.g. TBB and Weave are inherently useless for picking a library in an age where every dev has access to their own bespoke super-optimizer (LLMs). As an anecdotal point, I was recently working on a CPU-based runtime for SPIR-V to allow non-GPU execution of cross-spirv shaders, and while optimizing the dispatch an agent harness using GPT 6.2 Astra started to literally emit Arm64 instructions through hex constants in Nim, it didn’t even want to bother with compiler intrinsics or Weave’s SIMD. However, a toolkit like Weave still leads to both human and machine readable code, and saves tokens end to end. Correct code is cheap code, and obviously correct code is easier to scale.
SIMD and the throughput cost of stable math
With portable Neon SIMD, Mat4 multiplication achieved a 1.71x speedup (10,000 ops, 0.060 ms scalar to 0.035 ms) and DDMat4 multiplication achieved a 1.48x speedup (1,000 ops, 0.586 ms scalar to 0.397 ms) using packed two-lane double-double arithmetic, while Apple Clang auto-vectorized trivial four-lane Vec4 multiply-add loops to match explicit SIMD (0.797 ms vs 0.802 ms).
For the Herbie-verified standard-library replacements, 102,400 operations per run (819,200 elements for sum) were timed across 50 runs after 5 warmups on ordinary finite inputs where both Nim 2.4.2 and the replacements return finite values:
| Operation | Nim 2.4.2 stdlib (ms) | Weave SSM (ms) | Relative time | Error reduction (bits) |
|---|---|---|---|---|
math.arccsch |
1.583 | 0.472 | 0.30x | 62.0 to 0.48 |
complex.tan |
0.808 | 0.592 | 0.73x | 63.9 to 0.00 |
complex.arcsinh |
1.449 | 1.390 | 0.96x | 51.7 to 0.10 |
complex.cosh |
0.628 | 0.797 | 1.27x | 29.3 to 0.02 |
complex.sinh |
0.601 | 0.805 | 1.34x | 58.0 to 0.01 |
math.sum |
0.448 | 0.604 | 1.35x | 61.7 to 0.00 |
math.arcsech |
0.285 | 0.575 | 2.02x | 62.0 to 0.48 |
complex./ |
0.065 | 0.997 | 15.34x | 24.0 to 1.56 |
Three replacements (stableArccsch, stableTan, and stableArcsinh) were both more accurate and faster than Nim’s standard library, with stableArccsch running 3.35x faster while avoiding subnormal overflow. Neumaier compensatedSum, stableSinh, and stableCosh added 27% to 35% runtime in exchange for removing 29 to 62 bits of cancellation error. Exponent-scaled complex division (stableDivide) took 15.34x longer than inline unscaled division because it calls frexp and scalbn - an explicit cost callers pay only when operands can approach \(10^{308}\).
Scope and limits
None of these tools, even combined, and used through SSMs can prove correctness of the complex system that is a runtime executing on real hardware. A discussion about system complexity and applied systems thinking in an age of increasingly unknown and perhaps eventually unknowable software is something I’ll defer to a future article.
For now, and again this is anecdata, SSMs have aided me in eradicating show-stopping bugs from my software, and perhaps you’ll be similarly successful.
Cross-architecture testing and hardware cost
Even with formal models and local tests on one machine, defects that depend on a specific operating system, compiler, or CPU architecture can still slip through. Running the full validation suite across five hosts - testing both C and C++ backends with ARC and ORC under Clang and GCC - surfaced concrete bugs that never appeared on a macOS workstation alone:
| Host | OS and architecture | Toolchains | Platform-specific defects surfaced |
|---|---|---|---|
| Apple Silicon | macOS Arm64 | Apple Clang | Non-futex pthread_cond lost wakeups and 18-core preemption stall |
| Arm64 server | Linux Arm64 | GCC and Clang | GCC attribute-ordering failures for Arm SVE2 and SME |
| EPYC Genoa | Linux AMD64 | GCC and Clang | Implicit GCC FMA contraction altering double-double rounding |
| Xeon Skylake | Linux Intel64 | GCC and Clang | Reinitialization shrinking worker count to one pinned CPU until lead affinity is restored |
| Threadripper PRO | Windows 11 x86-64 | MinGW-w64 GCC | Nim stdlib atomic failure-order abort under C++ and HANDLE affinity FFI mismatch |
Future work with Nim 3 and Nimony
Looking beyond Nim 2, the Nim project is developing a new compiler for Nim 3 called Nimony (Rumpf, 2025), which is not yet stable and has not been tested with Weave or with these single-source model macros. Based on Nimony’s published design - incremental and parallel module compilation, type-checked generics, atomicArc memory management, and a unified concurrency model based on compiler-transformed continuations called passive procedures - two promising directions stand out once Nimony’s compile-time metaprogramming stabilizes.
First, Weave’s scheduler and single-source models align directly with Nimony’s runtime design. In Nim 2, task closures must be packed manually into fixed raw buffers and managed captures rejected at compile time, whereas Nimony lowers passive procedures into explicit continuations and enforces ownership transfer (sink parameters) when a continuation is handed to a cross-thread scheduler. Porting Weave to Nimony in the future could allow its message-passing work-stealing scheduler to execute compiler-checked continuations directly, and Nimony’s parallel module builds could evaluate independent module proof caches concurrently to reduce cold-build times.
Second, although untested so far, single-source models could help during Nimony’s own development. Nimony’s authors are building several subtle runtime subsystems from scratch, including the handoff between thread-affine and cross-thread continuations, atomicArc reference counting with planned cycle collection, parallel build coordination, and a rewritten standard library. Applying TLA+ and GenMC single-source models to Nimony’s continuation scheduler and memory-management protocols could catch lost wakeups, premature coroutine-frame reclamation, and weak-memory ordering bugs before those interfaces stabilize, while applying Herbie numerical models to Nimony’s new standard math modules could prevent Nim 2’s ten floating-point bugs from reappearing in Nim 3.
Closing Remarks
I hope this inspires you to reach for verification tools in your own development. By moving development to “safe” languages, where we can use the type system and compiler guarantees to eliminate classes of fundamental bugs, we’ve come quite far in the past decade. I believe we must broaden and deepen our investment in verification to allow us, and our agents, to move into higher layers of abstraction with less risk. I also believe we need to find better ways to represent those abstractions, so we can guide, review and abstract further with much higher efficiency.
If you have thoughts or ideas, questions or corrections, don’t hesitate to reach out by contacting the email address in the footer.
I also want to thank all Nim maintainers, the original creators of Weave, and everyone who contributed to these projects over the years. I’m more excited than ever to see what’s next for Nim.
References
- Acar, U. A., Chargueraud, A., & Rainey, M. (2013). Scheduling parallel programs by work stealing with private deques. In Proceedings of the 18th ACM SIGPLAN symposium on principles and practice of parallel programming (pp. 219-228). Association for Computing Machinery. https://doi.org/10.1145/2442516.2442538
- Andre-Ratsimbazafy, M. (2019, August 9). Project Picasso - A multithreading runtime for Nim [RFC 160]. GitHub. https://github.com/nim-lang/RFCs/issues/160
- Chase, D., & Lev, Y. (2005). Dynamic circular work-stealing deque. In Proceedings of the seventeenth annual ACM symposium on parallelism in algorithms and architectures (pp. 21-28). Association for Computing Machinery. https://doi.org/10.1145/1073970.1073974
- Cousineau, D., Doligez, D., Lamport, L., Merz, S., Ricketts, D., & Vanzetto, H. (2012). TLA+ proofs. In D. Giannakopoulou & D. Mery (Eds.), FM 2012: Formal methods (pp. 147-154). Springer. https://doi.org/10.1007/978-3-642-32759-9_14
- Dekker, T. J. (1971). A floating-point technique for extending the available precision. Numerische Mathematik, 18(3), 224-242. https://doi.org/10.1007/BF01397083
- Kahan, W. (1987). Branch cuts for complex elementary functions, or much ado about nothing’s sign bit. In A. Iserles & M. J. D. Powell (Eds.), The state of the art in numerical analysis (pp. 165-211). Clarendon Press.
- Kokologiannakis, M., & Vafeiadis, V. (2021). GenMC: A model checker for weak memory models. In A. Silva & K. R. M. Leino (Eds.), Computer aided verification (pp. 427-440). Springer. https://doi.org/10.1007/978-3-030-81685-8_20
- Lamport, L. (2002). Specifying systems: The TLA+ language and tools for hardware and software engineers. Addison-Wesley. https://lamport.azurewebsites.net/tla/book.html
- Lamport, L. (2017, March 17). Introduction to TLA+ [Video]. The TLA+ Video Course. https://lamport.azurewebsites.net/video/intro.html
- Neumaier, A. (1974). Rundungsfehleranalyse einiger Verfahren zur Summation endlicher Summen [Rounding error analysis of some methods for summing finite sums]. Zeitschrift fuer Angewandte Mathematik und Mechanik, 54(1), 39-51. https://doi.org/10.1002/zamm.19740540106
- Panchekha, P. (2022, November 28). Improving Rust with Herbie. https://pavpanchekha.com/blog/herbie-rust.html
- Panchekha, P., Sanchez-Stern, A., Wilcox, J. R., & Tatlock, Z. (2015). Automatically improving accuracy for floating point expressions. In Proceedings of the 36th ACM SIGPLAN conference on programming language design and implementation (pp. 1-11). Association for Computing Machinery. https://doi.org/10.1145/2737924.2737959
- Prell, A. (2016). Embracing explicit communication in work-stealing runtime systems [Doctoral dissertation, University of Bayreuth]. EPub Bayreuth. https://epub.uni-bayreuth.de/2990/1/main_final.pdf
- Rumpf, A. (2025, May 3). Nimony: Design principles. Nim. https://nim-lang.org/araq/nimony.html
- Yu, Y., Manolios, P., & Lamport, L. (1999). Model checking TLA+ specifications. In L. Pierre & T. Kropf (Eds.), Correct hardware design and verification methods (pp. 54-66). Springer. https://doi.org/10.1007/3-540-48153-2_6
Notes
-
Nim 2.4.2 reports an implicit range-conversion warning on one integer literal that Nim 2.2.10 accepted without warning, so that single warning-as-error flag was disabled for the Nim 2.4.2 runs. ↩