Repository navigation
Add a BenchmarkDotNet suite for solve hot paths - #104
Merged
Merged
Conversation
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
There was a problem hiding this comment.
🟡 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); | ||
| } |
Member
Author
MikeEvansLarah
approved these changes
Oct 27, 2026
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>
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.

Adds a
Z3.Linq.Benchmarksproject - 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
SolveBenchmarksruns end-to-endSolve/Optimizeover six environment shapes, each against atheorem Z3 decides in microseconds. That is deliberate: with the solver's own work negligible,
the time and - more usefully - the
MemoryDiagnoserAllocatedcolumn are dominated by thelibrary'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.
ScalarSymbols(baseline)Symbols<int,int>ValueTupleNestedObjectCollectionWideSymbolsSymbols<int,int,int,int,int>)OptimizeEach theorem is built once in
[GlobalSetup]; the benchmark measures only the solve, and returnsthe result so the JIT cannot eliminate the call.
It already points somewhere
A first
--job dryrun (allocation is meaningful even in Dry; the DryMeanis not) - relative tothe flat-symbol baseline:
ValueTupleScalarSymbolsNestedObjectOptimizeWideSymbolsCollectionThe 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
Allocated/Meancolumns say which shape to look at.GetProperties/GetCustomAttributesreflection, boxing of value-type members).RatioandAlloc Ratioagainst the baseline show the movement.JSON export plus the
bdnatool tracks regressions across commits, as the README and the endjinguidelines describe.
Wiring
solutions/Z3.Linq.Benchmarks/(Exe,IsPackable=false), referencingZ3.Linq.BenchmarkDotNet0.15.8 added to central package management; the project references itversion-less like every other package here.
Z3.Linq.slnx, so it builds with the solution (validated) but - being a plain Exe, nota test project - is not run by
dotnet test.CS1591suppressed as on the test/examples/demo projects; a[Benchmark]method is a toolsurface, not an API.
BenchmarkDotNet.Artifacts/was already in.gitignore; no artifacts are committed.Verification
dotnet build solutions/Z3.Linq.slnx -c Release- clean,TreatWarningsAsErrorsanddocumentation generation on
dotnet run -c Release --project solutions/Z3.Linq.Benchmarks -- --filter '*' --job dryexecuted all six benchmarks and produced the memory table above
./build.ps1 -Configuration Release- 46 tasks, 0 errors, 0 warnings, with the new project inthe 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