Skip to content

Add a BenchmarkDotNet suite for solve hot paths - #104

Merged
HowardvanRooijen merged 1 commit into
feature/solve-limit-fixesfrom
feature/benchmarks
Oct 28, 2026
Merged

HowardvanRooijen merged 1 commit into
feature/solve-limit-fixesfrom
feature/benchmarks

Conversation

@HowardvanRooijen

@HowardvanRooijen HowardvanRooijen commented Sep 2, 2026 •

Copy link
Copy Markdown
Member

Adds a Z3.Linq.Benchmarks project - a BenchmarkDotNet suite,
following the endjin BenchmarkDotNet guidelines, for finding performance and memory hot paths in
the library and confirming an optimisation actually helped. It measures; it changes no library
code.

What it measures, and why it's the right thing

SolveBenchmarks runs end-to-end Solve/Optimize over six environment shapes, each against a
theorem Z3 decides in microseconds. That is deliberate: with the solver's own work negligible,
the time and - more usefully - the MemoryDiagnoser Allocated column are dominated by the
library's per-solve work: building the environment by reflection, translating the constraint
expression trees, and marshalling the model back onto the CLR members. Nothing is cached across
solves today, so re-solving the same theorem re-does all of it - which is exactly what these numbers
can be used to change.

Benchmark Exercises
ScalarSymbols (baseline) a flat Symbols<int,int>
ValueTuple the value-tuple environment path
NestedObject recursive marshalling of a nested object
Collection the array element loop
WideSymbols more members to reflect and translate (Symbols<int,int,int,int,int>)
Optimize the optimiser's own solve path

Each theorem is built once in [GlobalSetup]; the benchmark measures only the solve, and returns
the result so the JIT cannot eliminate the call.

It already points somewhere

A first --job dry run (allocation is meaningful even in Dry; the Dry Mean is not) - relative to
the flat-symbol baseline:

Shape Allocated vs baseline
ValueTuple 4.5 KB 0.4x
ScalarSymbols 11.6 KB 1.0x
NestedObject 20.1 KB 1.7x
Optimize 24.6 KB 2.1x
WideSymbols 24.7 KB 2.1x
Collection 26.3 KB 2.3x

The collection path allocates over twice the flat baseline, and the nested/wide/optimise shapes
around twice - the marshalling loop (ArrayList + ToArray, boxing), the recursive marshalling,
and the per-solve reflection. That is the map an optimisation would follow; this PR just draws it.

The loop it enables

  1. Run the suite; the Allocated/Mean columns say which shape to look at.
  2. Change the allocation in the library (the marshalling loop, the per-solve GetProperties /
    GetCustomAttributes reflection, boxing of value-type members).
  3. Re-run the same filter; Ratio and Alloc Ratio against the baseline show the movement.

JSON export plus the bdna tool tracks regressions across commits, as the README and the endjin
guidelines describe.

Wiring

  • New solutions/Z3.Linq.Benchmarks/ (Exe, IsPackable=false), referencing Z3.Linq.
  • BenchmarkDotNet 0.15.8 added to central package management; the project references it
    version-less like every other package here.
  • Added to Z3.Linq.slnx, so it builds with the solution (validated) but - being a plain Exe, not
    a test project - is not run by dotnet test.
  • CS1591 suppressed as on the test/examples/demo projects; a [Benchmark] method is a tool
    surface, not an API.
  • BenchmarkDotNet.Artifacts/ was already in .gitignore; no artifacts are committed.

Verification

  • dotnet build solutions/Z3.Linq.slnx -c Release - clean, TreatWarningsAsErrors and
    documentation generation on
  • The suite runs: dotnet run -c Release --project solutions/Z3.Linq.Benchmarks -- --filter '*' --job dry
    executed all six benchmarks and produced the memory table above
  • 322/322 tests unchanged - this PR adds no library code
  • ./build.ps1 -Configuration Release - 46 tasks, 0 errors, 0 warnings, with the new project in
    the build

Release note

No library or public-API change - a developer tool that ships with the source, not the package.
Releases remain on hold under #60 regardless.

🤖 Generated with Claude Code

A new Z3.Linq.Benchmarks project, following the endjin BenchmarkDotNet
guidelines, to find performance and memory hot paths in the library and
confirm an optimisation helped.

SolveBenchmarks runs end-to-end Solve/Optimize over six environment
shapes - flat symbols, a value tuple, a nested object, a collection, a
wider symbol set, and an optimisation - each against a theorem Z3 decides
in microseconds, so the time and the MemoryDiagnoser Allocated column are
dominated by the library's own per-solve work (reflection env-building,
expression translation, marshalling) rather than the solver. Nothing is
cached across solves today, so those numbers are what an optimisation can
move.

A first dry run already shows the shape of it: the collection case
allocates ~2.3x the flat-symbol baseline, and the nested, wide and
optimise cases ~2x - the marshalling loop, recursive marshalling and
per-solve reflection.

The project is not packable, suppresses CS1591 like the other non-library
projects, and is wired into the solution and central package management.
BenchmarkDotNet.Artifacts is already gitignored. The README documents the
run commands, the optimise/re-measure loop, and JSON export for bdna
regression tracking.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PipoHZJsgydrV3JC3fQN6Q
@github-actions

github-actions Bot commented Sep 2, 2026

Copy link
Copy Markdown

Test Results

  1 files  ±0    1 suites  ±0   11s ⏱️ -1s
309 tests ±0  309 ✅ ±0  0 💤 ±0  0 ❌ ±0 
322 runs  ±0  322 ✅ ±0  0 💤 ±0  0 ❌ ±0 

Results for commit a4b7859. ± Comparison against base commit d018cd2.

@HowardvanRooijen
HowardvanRooijen marked this pull request as ready for review October 27, 2026 07:53
Copilot AI balanced review requested due to automatic review settings October 27, 2026 07:53

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The optimisation benchmark includes objective-expression construction in its measured work, skewing the intended solve-only timing and allocation comparisons.

1 open issue
What changed in this PR

Adds a source-only BenchmarkDotNet suite to measure Z3.Linq solve performance and allocations without changing library code or public APIs.

Changes:

  • Adds six benchmarks covering scalar, tuple, nested-object, collection, wide-symbol, and optimisation paths.
  • Integrates the non-packable benchmark executable into the solution and central package management.
  • Documents running benchmarks and comparing results across optimisations and commits.
File Description
solutions/​Z3.Linq.slnx Includes the benchmark project in solution builds.
solutions/​Z3.Linq.Benchmarks/​Z3.Linq.Benchmarks.csproj Defines the non-packable executable and dependencies.
solutions/​Z3.Linq.Benchmarks/​SolveBenchmarks.cs Adds six solve benchmarks with memory diagnostics.
solutions/​Z3.Linq.Benchmarks/​README.md Documents benchmark execution and comparison workflows.
solutions/​Z3.Linq.Benchmarks/​Program.cs Enables command-line benchmark selection.
solutions/​Directory.Packages.props Adds the central BenchmarkDotNet version.

Review effort: Balanced

Comment on lines +115 to +119
[Benchmark]
public Symbols<int, int>? Optimize()
{
return this.optimizeSource.Optimize(Optimization.Maximize, t => t.X1);
}

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct. Fixed in ba5e915 (#116). The objective is now an Expression<Func<...>> field built once, like the constraints in Setup.

@HowardvanRooijen HowardvanRooijen added no_release Suppresses auto_release functionality and removed pending_release labels Oct 27, 2026
@HowardvanRooijen
HowardvanRooijen merged commit 6b31b95 into main Oct 28, 2026
12 checks passed
@HowardvanRooijen
HowardvanRooijen deleted the feature/benchmarks branch October 28, 2026 07:38
HowardvanRooijen added a commit that referenced this pull request Oct 28, 2026
* Pin the true arm in the false-branch ternary test

The test pinned X1 to -1 and asserted `(X1 > 0 ? X2 : 9) == 9`, leaving
X2 free. A translation that always took the true arm would still find a
model - X2 = 9 - so the test could not tell the two arms apart, and it
was the only ternary test exercising the false arm. X2 is now pinned to
0, which makes the true arm unsatisfiable.

Checked by mutation: with the ternary translated as its true arm alone,
this test now fails and the other three ternary tests still pass.

Found by Copilot review on #99.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Build the Optimize benchmark's objective once

Optimize takes an expression tree, so the inline `t => t.X1` built a new
tree on every measured invocation and charged its construction and
allocation to the solve. Every other benchmark builds its expressions in
Setup; the objective is now a field built once, so the Optimize figures
measure the same thing as the rest.

Found by Copilot review on #104.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Say what the template's collections are for

"whose collections give the solution's their length" lost its noun. The
template's collections set the lengths of the solution's collections;
both GetSolution overloads now say so.

Found by Copilot review on #94.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Tell the demos README to populate the Z3 feed first

The Microsoft.Z3 version the library needs is not on nuget.org, so
restore finds it only in the local _z3-feed folder, which the build
script fills. `dotnet run demos/<file>.cs` does not run the build
script, so on a clean clone the first demo run fails with NU1102. The
README now says to run scripts/Install-Z3Package.ps1 first.

Reproduced with an empty _z3-feed and an empty NUGET_PACKAGES folder:
restoring demos/sudoku.cs fails with "NU1102: Unable to find package
Microsoft.Z3 with version (>= 5.3.2)".

Found by Copilot review on #110.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Read a template member only where its value is used

The marshaller read every member of the template passed to NewTheorem,
scalars included, and handed the value down - but only a collection
(for its length) and a nested environment (for its own collections)
use it. A scalar getter that threw failed a solve that only needed the
setter, and a getter with side effects ran for nothing.

ConvertZ3Expression now takes the template instance and reads the
member from it in the collection and nested-object branches only. The
type is normalised through its TheoremVariableTypeMapping before the
branch is chosen, so a mapped scalar is skipped too.

The new test counts reads of a scalar getter on the template: one before
the change, none after.

Found by Copilot review on #93.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fix three bit-vector translations that disagreed with C#

All three were introduced with the uint/ulong bit-vector symbols.

Shift counts were not masked. C# uses only the low five bits of the
count for a uint and the low six for a ulong, so `1u << 32` is 1; Z3
shifts by the whole count and gives 0. The count is now ANDed with the
width minus one before the shift. A negative count reaches the mask in
two's complement, since the int-to-bit-vector conversion is modulo
2^width, so it matches C# too.

A uint beside a ulong threw NotImplementedException. C# widens the uint
implicitly, so `t.X1 == t.X2` over Symbols<uint, ulong> was unusable.
VisitConvert now zero-extends from 32 to 64 bits, and an explicit
`(uint)` cast on a ulong keeps the low 32 bits, as an unchecked cast
does.

Checked arithmetic wrapped. AddChecked, SubtractChecked and
MultiplyChecked shared the wrapping bit-vector form, so
`checked(t.X1 + 1u) == 0u` returned uint.MaxValue, a value for which the
C# predicate throws OverflowException. These are now refused with a
NotSupportedException that says so; overflow checking is not translated.
Checked arithmetic on int and real symbols is unchanged.

The shift tests take the count as a symbol, so the solver cannot fold
it, and compute the expected value with C# from the returned symbols.

Found by Copilot review on #101.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Wrap narrowing integer casts, and refuse conversion operators

Two ways VisitConvert returned a model the C# predicate rejects, both
because it chose the translation from the sorts alone.

A narrowing cast between integer types was a no-op. Every integer type
but uint and ulong is an unbounded integer in Z3, so `(int)t.X1` on a
long symbol kept the long value: `(int)4294967295L` came out as
4294967295 where C# gives -1, and against a bounded int symbol the
theorem was reported unsatisfiable. The cast now wraps into the target
range, ((x - low) mod n) + low, which is the unchecked C# result for
signed and unsigned targets and negative operands alike. A widening
cast, and any cast to long, is still a no-op. A checked cast is a
ConvertChecked node, which is not translated.

A user-defined conversion operator was dropped. For a type mapped to
float whose explicit operator to float doubles its value,
`(float)t.X1 == 6f` returned a symbol holding 6, which the operator
turns into 12. A conversion that calls an operator method is now
refused with a NotSupportedException naming the operator, except
decimal's built-in conversions, which are operator methods on decimal.
A cast to a type with no sort still throws NotImplementedException, as
before.

The wrap reuses Theorem.GetBounds, which becomes internal, so a
conversion and a symbol agree about a type's range.

Found by Copilot review on #88 (narrowing) and #92 (operators).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Let a collectible environment type unload

The per-type reflection caches - type mappings, public properties and
public fields - were static ConcurrentDictionary instances keyed on
Type, so they held every environment type they had seen for the life
of the library. A host loading environments from a collectible assembly
(a plugin it reloads, a script it compiles) could never unload one.

They are now ConditionalWeakTable instances, which drop an entry when
nothing else holds the type. A cached PropertyInfo or FieldInfo refers
back to its declaring type, which a weak table tolerates without
keeping the key alive. A weak table's value cannot be null, so an
absent mapping is cached as an entry holding null.

The new test emits an environment type into a RunAndCollect assembly,
solves with it, drops its references and checks that the type is
collected. It fails with the dictionaries and passes with the weak
tables, so nothing else in the solve path keeps the type alive.

Measured with the benchmark suite (--job short), before and after:
allocations are identical in every shape (3.3 KB to 6.2 KB per solve),
and the differences in mean time are inside the run-to-run noise of a
roughly 15 ms solve that Z3 dominates.

Found by Copilot review on #105.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

no_release Suppresses auto_release functionality

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants