Repository navigation
Conversation
* Migrate build from Endjin.RecommendedPractices.Build to ZeroFailed
Replaces the Endjin.RecommendedPractices.Build bootstrap in build.ps1 with
the ZeroFailed equivalent, moving all build configuration out into
.zf/config.ps1 as per the ZeroFailed convention.
- build.ps1 is now a thin bootstrap (ZeroFailed 1.0.6, InvokeBuild 5.14.22)
that dots into .zf/config.ps1. The existing parameter surface is unchanged.
- .zf/config.ps1 declares the ZeroFailed.Build.DotNet extension and carries
the build configuration previously inline in build.ps1. SkipTest remains
true as the solution still has no test project.
- The old $ExcludeFilesFromCodeCoverage placeholder becomes ZeroFailed's
Include/ExcludeAssembliesInCodeCoverage properties.
- .gitignore excludes the .zf/extensions/ download cache.
- The CI publish source env var is renamed BUILDVAR_NuGetPublishSource ->
ZF_NUGET_PUBLISH_SOURCE. BUILDVAR_ is an Endjin.RecommendedPractices.Build
convention that ZeroFailed does not read, so without this the publish
stage would silently fall back to the local feed default.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* Update ZeroFailed to 1.0.7 and InvokeBuild to 5.14.23
Both were a single patch release behind the latest stable on the PowerShell
Gallery. Verified locally: the build bootstraps on ZeroFailed 1.0.7 and
completes with 35 tasks, 0 errors, 0 warnings.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* Fix garbled comment in the ZeroFailed extension declaration
The scaffolded wording ('use latest version from main will be downloaded')
reads as two half-sentences spliced together. Same meaning, in one sentence.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
* Modernise solution: .NET 10, Central Package Management, .slnx - Converts the solution to the .slnx format via 'dotnet sln migrate', and adds a Solution Items folder for the shared props files. - Adds solutions/Directory.Packages.props enabling Central Package Management; version attributes are removed from the PackageReference items. - Adds solutions/Directory.Build.props hoisting everything the three projects duplicated: TargetFramework (now net10.0), ImplicitUsings, Nullable, PlatformTarget (x64, required by Microsoft.Z3's native binaries), TreatWarningsAsErrors, and the shared package metadata. Also enables SourceLink and deterministic CI builds. - Points $SolutionToBuild at the .slnx and bumps CI netSdkVersion to 10.x. MiaPlaza.ExpressionUtils is deliberately held at 1.2.0: 1.3.x removes the general PartialEval(Expression, IExpressionEvaluator) overload in favour of a LambdaExpression-constrained generic, which ExpressionVisitor.cs relies on. Microsoft.Z3 4.12.2 is already the newest published to nuget.org. Verified: builds clean on net10.0 with TreatWarningsAsErrors (0 warnings), the demo app solves all examples correctly, and the full ZeroFailed build packages both libraries as lib/net10.0. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * Run the release workflow's GitVersion step on the .NET 10 SDK auto_release.yml installed the .NET 6 SDK solely to give 'dotnet tool install' something to run under; the GitVersion step never compiles the solution. .NET 6 is long out of support, and build.yml is now on 10.x, so the two workflows were pinned to different SDKs for no reason. GitVersion.Tool 5.8.0 is unaffected by the change: it ships "rollForward": "LatestMajor" in its runtimeconfig.json, so it binds to whatever the newest installed runtime is rather than requiring .NET 5/6. Verified on a machine with no .NET 5 or 6 runtime installed (only 8.0.30, 9.0.19, 10.0.8, 10.0.11): a fresh 'dotnet tool install GitVersion.Tool --version 5.8.0' under SDK 10.0.400 succeeds, COREHOST_TRACE confirms it selects Microsoft.NETCore.App 10.0.11, and it returns MajorMinorPatch 2.0.2 - the variable this workflow consumes for the release tag. The GitVersion version itself is deliberately unchanged. Moving to GitVersion 6 is breaking here: it rejects next-version "2.0" and needs "2.0.0", and GitVersion.yml is generated by the pr-autoflow codeops mechanism, so that fix belongs in endjin-codeops rather than this repo. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * Correct the package metadata comment in Directory.Build.props Z3.Linq uses Description but Z3.Linq.Examples uses PackageDescription, so naming only the former misdirects the next person adding a packable project. Verified that PackageDescription does populate the nuspec <description>. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * Update the README and notebook for .NET 10 The headline still described the library as .NET 8.0 bindings, and the Polyglot Notebook referenced bin/Debug/net8.0 paths that the build no longer produces - so anyone following the README's 'run it locally' route hit missing assemblies. The History entries naming .NET 4.5, 6.0 and 8.0 are left alone; they record what those contributors did at the time. A 2026 entry is added for this work. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
…ange (#47) 1.3.x removes PartialEvaluator.PartialEval's Expression-taking overloads, leaving only PartialEval<TExpression>(TExpression, IExpressionEvaluator) constrained to LambdaExpression. ExpressionVisitor fed it the output of ParameterSubstituter.SubstituteParameter, which is the selector's body and so not a lambda, giving CS0311 on upgrade. The body is now wrapped in a lambda for the call and unwrapped afterwards, which is the supported equivalent of the removed overload. The theorem's own parameter stays free in the wrapper; the evaluator folds only closed subtrees and leaves parameter-dependent ones alone, so the result is unchanged. This affects Z3Methods.Distinct(collection.Select(...).ToArray()). Nothing in the repository exercises that branch - the Sudoku theorems build their Distinct arguments as a NewArrayExpression, which takes the other path - so it was verified with a purpose-built probe covering satisfiable, unsatisfiable, constant-folded and two-symbol selectors. All four produce byte-identical results before and after the upgrade: multipliers-sat: X1=11, X2=12 duplicate-unsat: <unsat> folded-sat: X1=7, X2=0 two-symbols-sat: X1=4, X2=9 The demo app's output is also unchanged, and the full ZeroFailed build passes (35 tasks, 0 errors, 0 warnings under TreatWarningsAsErrors). Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
…jin#61) * Update Microsoft.Z3 to 5.1.0 to get Linux and arm64 native binaries Microsoft.Z3 4.12.2 contains native binaries for win-x64 and osx-x64 only. On Linux the managed assembly therefore loads and then fails at the first solve, either with DllNotFoundException or - where the machine happens to have an unrelated system libz3, as the GitHub Actions runner image does - with EntryPointNotFoundException against a solver we never pinned. That is why the build goes red as soon as a stage actually executes a theorem. 5.1.0 ships linux-x64, linux-arm64, osx-x64, osx-arm64, win-x64 and win-arm64. Verified by running the solution on Ubuntu 24.04 (glibc 2.39, matching ubuntu-latest) as well as Windows, and by diffing the full demo output between 4.12.2 and 5.1.0: the Sudoku, oil purchase and warehouse results are identical, and Missionaries & Cannibals still reaches the same optimum under both Optimize() and orderby. Only the unoptimised Solve() picks a different valid model, which is expected where the constraints admit many. The Z3 project stopped publishing to nuget.org after 4.12.2 and now ships the package as a GitHub release asset, so it is fetched into a local folder feed before restore. The download is pinned by SHA-256 and only moved into the feed once it matches, so an interrupted or substituted download cannot become a package that restore consumes. PlatformTarget is dropped now that arm64 binaries exist - pinning x64 would shut those machines out. NOTE: this is not yet safe to publish. The packed Z3.Linq declares a dependency on Microsoft.Z3 5.1.0, which does not exist on nuget.org, so a consumer restoring Z3.Linq from nuget.org fails with NU1102. The published package's dependency has to be settled before this is released. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * Hold releases while Microsoft.Z3 5.1.0 is off nuget.org The packed Z3.Linq declares a dependency on Microsoft.Z3 5.1.0, which is not published to nuget.org, so a consumer restoring from nuget.org with a clean cache fails with NU1102. NuGet gives a package no way to tell consumers where its dependencies live, so no feed we control can fix that - only an upstream publish can. $SkipPublish keeps a tagged build from shipping an unrestorable package in the meantime. Verified: FullBuildAndPublish reports "Publish skipped" and still completes the package stage. See endjin#60 for what lifts the hold, and Z3Prover/z3#10711 upstream. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * Document the platform support that Microsoft.Z3 5.1.0 brings The README told everyone to target x64, which stops being true with this change: 5.1.0 carries native binaries for x64 and arm64 on all three platforms, so AnyCPU resolves the right one. The note is there because the advice does not apply to anything on nuget.org yet. Published versions depend on Microsoft.Z3 4.12.2, which has no Linux or arm64 binaries, so on those platforms they restore and then throw DllNotFoundException on the first solve - a failure worth naming, since it looks like a bug in this library rather than a missing native. Releases are paused until upstream publishes (endjin#60). Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
* Add Z3.Linq.Tests covering the Distinct partial-evaluation path Adds the repository's first test project, following the endjin .NET testing framework guidelines: MSTest 4.0 on Microsoft.Testing.Platform via the MSTest SDK, with Shouldly for assertions. - global.json selects the MTP runner and pins MSTest.Sdk 4.3.3, which is how .NET 10 enables MTP mode (the older TestingPlatformDotnetTestSupport property is obsolete). - AssemblyInfo.cs carries [assembly: Parallelize(Workers = 0, Scope = ExecutionScope.MethodLevel)], required by MSTest 4.0 to avoid MSTEST0001. - TestingExtensionsProfile=Default brings in the code coverage and TRX report extensions. - Shouldly is added to Directory.Packages.props. No PackageVersion is added for Microsoft.Testing.Extensions.CodeCoverage: the MSTest SDK injects its own under CPM and a second one trips NU1506. - NSubstitute is deliberately omitted; there is nothing to substitute in these tests, and the guidelines say to mock only what is used. - .zf/config.ps1 stops skipping the Test and TestReport stages, so the ZeroFailed build now runs tests and produces coverage. The coverage assembly filters added earlier (+Z3.Linq*;-Z3.Linq*.Tests*) apply as-is. - .gitignore excludes the TRX and Cobertura output the run leaves behind. The 16 tests cover Z3Methods.Distinct in both of its visitor branches: the Select(...).ToArray() form that reaches PartialEvaluator.PartialEval, and the inline NewArrayExpression form that does not, including cases asserting the two forms agree. Two of them exist specifically to pin the partial-evaluation step. The arithmetic-only cases turned out to pass with partial evaluation removed, because Z3 folds constant arithmetic itself, so they do not actually guard the change. The host-method cases do: the selector calls an ordinary C# method that the visitor cannot translate, so it only reaches Z3 as a constant if the substituted body is partially evaluated first. Verified by mutation - removing the PartialEval call fails exactly those two tests with "NotSupportedException: Unknown method call: Int32 Get(Int32)", and passes the other 14. Full ZeroFailed build: 45 tasks, 0 errors, 0 warnings, 16/16 tests passing, 31.5% line coverage on Z3.Linq. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * Pin Microsoft.Testing.Extensions.CodeCoverage to 18.10.0 The MSTest SDK adds this package implicitly and defaults it to 18.9.0, which left the coverage extension a release behind the dotnet-coverage collector that the ZeroFailed test task runs (18.10.0). The reference is injected from a .targets file imported after the project body, so a per-project PackageReference Update would be a no-op; setting MicrosoftTestingExtensionsCodeCoverageVersion in Directory.Build.props is the supported override. No PackageVersion is added in Directory.Packages.props - under CPM the SDK derives its own from this property, and a second one trips NU1506. With this, 'dotnet list package --outdated' reports no updates for any of the four projects. Full ZeroFailed build: 45 tasks, 0 errors, 16/16 tests passing. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
* Add core solve and composition tests (test suite phase A) First phase of broadening Z3.Linq's test coverage beyond the Distinct paths. 23 new tests take the suite from 16 to 39 and line coverage from 31.5% to 38.8%. - GlobalUsings.cs centralises the common imports. Note the Z3Environment alias: a global 'using Z3.Linq' makes the bare name Environment bind to Z3.Linq.Environment rather than System.Environment, which is a surprising shadowing failure the alias makes explicit. - TheoremSolveTests covers satisfiable and unsatisfiable outcomes, repeated solves, and integer round-tripping including Int32 boundaries. - TheoremCompositionTests covers Where immutability and accumulation, Theorem.ToString, the Z3Context.Log seam, Dispose being a harmless no-op, the NewTheorem(dummy) overload, and Symbols.ToString formatting. Assertions follow a determinism rule stated in the test doc comments: exact values are asserted only where the constraints admit exactly one model, otherwise the test asserts a model-independent invariant. Z3 does not promise which satisfying model it returns and Dependabot bumps NuGet packages daily. Unsatisfiable cases are kept trivially contradictory, because Solve returns default for both UNSATISFIABLE and UNKNOWN, so a merely slow theorem would otherwise pass an "is unsatisfiable" assertion. Writing these found a previously unknown defect: any symbol not referenced by a constraint makes Solve throw InvalidCastException, because model.Eval defaults to completion:false and an unreferenced constant evaluates to itself. Raised as endjin#51 and pinned by two characterisation tests rather than fixed, per the agreed approach of documenting defects for a later PR. Verified by mutation: making Where drop its new constraint fails 20+ tests across the suite, including these. Issues raised for the defects found by this review: endjin#51 unconstrained symbols, endjin#52 culture-sensitive MkReal, endjin#53 collection-typed fields, endjin#54 float round-trip, endjin#55 decimal arrays, endjin#56 DateTime timezone, endjin#57 value-type unsat ambiguity, endjin#58 Optimize nullability. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * Correct the Environment name-resolution comment and drop the unused alias The comment claimed the bare name Environment is CS0104-ambiguous between System.Environment and Z3.Linq.Environment. It is not: these tests live in namespace Z3.Linq.Tests, so the enclosing Z3.Linq namespace is searched before any using directive and the name binds to Z3.Linq.Environment. Verified - a bare Environment.NewLine gives CS0117 ('Environment' does not contain a definition for 'NewLine'), not CS0104. The Z3Environment alias the wrong explanation justified was never used, so it goes with it rather than being kept alive by a corrected comment. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
…hapes (endjin#65) * Add type marshalling tests for symbols, collections and environment shapes Phase B of the test plan, covering the layer that turns a Z3 model back into a CLR object. 39 tests -> 87; line coverage 38.8% -> 62.9%, branch 52.1%. Writing these found that four of the types the library presents as supported do not work at all, none of which any example exercises: - short throws InvalidCastException before it reaches the solver, and would throw ArgumentException on the way back even if that were fixed (endjin#63, new) - every collection element type except int fails translation with a Z3 sort error - long, bool, double, decimal and string (endjin#64, new) - float solves and then fails to marshal (endjin#54) - a real constant is written to Z3 using the current culture, so a comma-decimal culture produces a parser error (endjin#52) Each is pinned by a characterisation test naming the issue, per the standing decision to document rather than fix defects in this work. endjin#55 turned out to be unreachable and has been annotated: decimal arrays die at translation long before the element-evaluation bug it describes can be observed. The culture test runs its work on a dedicated thread rather than setting CurrentCulture on the test's own. These run in parallel at method level on pooled threads, so mutating culture in place could leak into whatever ran next. DateTime is asserted in a form that holds in any time zone: the instant round trips correctly, but the value returns as Kind=Local, so comparing it to the UTC value supplied fails by exactly the local offset (endjin#56). Mutation-checked: reading Int64 model values through .Int fails 3 tests, and reading every array element from index 0 fails 3 tests. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * Bound the joins on the culture test threads An unbounded Join means a solver that never returns hangs the entire run with no indication of which test stopped. A bounded one fails that test and lets the rest finish. The limit is 30 seconds against work that takes single-digit milliseconds, so it is slack rather than a tuned value. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
…ndjin#67) * Add optimisation tests for Optimize, OrderBy and OrderByDescending Phase C of the test plan. 87 tests -> 102; line coverage 62.9% -> 69.9%, branch 52.1% -> 54.7%. The whole optimisation surface was previously untested despite being the feature the README leads with. Covers both directions, the orderby operators and their equivalence to the Optimize calls they delegate to, deferred execution, objectives over several symbols, reuse of a theorem across calls, and the oil purchase linear program from the README - whose optimum is a single vertex, 2200 and 3100 barrels for $90,500, so the cost is safe to assert exactly. Pins endjin#58: an unsatisfiable Optimize returns default! through a non-nullable T. Solve returns T? and makes the caller check; Optimize promises a value and then hands back a null the compiler has been told cannot exist, so the caller dereferences it somewhere else entirely. Deferred execution is asserted through the Z3Context.Log seam rather than by timing or by relying on a theorem that throws: an eager OrderBy would have written its asserted constraints to the log before Solve was called. Mutation-checked, including the mutation that matters most here - never attaching the objective to the optimiser, so Optimize degenerates into Solve, fails 5 tests. Swapping Minimize and Maximize fails 9; mapping OrderBy to Maximize fails 2. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * Use the API spelling in optimisation test names Two test names used -ise while the rest of the file, and the Optimization enum they describe, use -ize. Someone grepping for Minimize would have missed them. Identifiers now follow the API; comment prose stays as it is. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Phase D of the test plan. 102 tests -> 120; line coverage 69.9% -> 76.2%, branch 54.7% -> 68.7%. Branch coverage moves most here because throw sites are branches, and none of them had ever been executed. UnsupportedExpressionTests pins the boundary of the translator: Distinct called outside a query, ternaries, unrecognised method calls, unsupported casts, char, uint and nullable properties, and two levels of object collections. These matter as much as the supported cases - a change that quietly stops rejecting something does not fail loudly, it produces a theorem meaning something other than what was written. RewriterTests covers both extension points, which were public API and entirely unverified. The tests assert what a rewrite did rather than that one ran: a global rewriter appends a constraint no query mentions, and another discards a contradiction so an unsatisfiable theorem becomes satisfiable. A predicate rewriter turns a call the visitor would reject into Z3Methods.Distinct, checked both for being accepted and for meaning something - the unsatisfiable case would still pass if the rewrite were built and then dropped. Assertions are on exception type, not message. Several messages are misspelled or malformed; pinning them would turn a typo fix into a test failure. Also found that enums fail exactly as short does, same Convert defect, same fix - recorded on endjin#63. Mutation-checked: discarding the global rewriter's return value fails the 2 effect-based tests, and removing its interface check fails 1. Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
…n#71) * Add acceptance tests for the Sudoku and river crossing samples Phase E of the test plan, and the last of it. 120 tests -> 133. These are the only tests that exercise the library at realistic size - 81 symbols, 27 Distinct constraints and a global rewriter in one theorem - so they are where a translation regression that only appears at scale would surface. Sudoku puzzle B is published and uniquely solvable, so its grid is asserted cell by cell. Puzzle A has 21 givens and almost certainly several solutions, so it is asserted by invariant: the givens survive and every row, column and box is a permutation of 1-9. Missionaries and Cannibals is checked against the rules of the puzzle at every step, not just its length, so an optimiser that reached the optimum by violating the safety rule would still fail. Measured before classifying, per the plan. Two of its numbers were wrong: the optimal crossing is 12 states rather than 11, and the smallest feasible maxLength is 13 rather than 12 - the goal requires Length < maxLength, so a bound equal to the optimum is one short. Both boundaries are now pinned. No test is tagged Slow because none needs to be. After dropping one pathological case the whole suite runs in 946ms and the slowest test is 443ms, so the category and the AdditionalTestArgs filter are both skipped as the plan directed. That dropped case was a Sudoku with no givens. It solved correctly but took 25 seconds - fifty times the next slowest test - because an unconstrained grid gives Z3 nothing to propagate from. It proved only that the constraints are satisfiable alone, which the two real puzzles already establish while also checking an answer, and tagging it slow would have left a test that never runs. Coverage is 75.8% line and 69.3% branch. The line percentage is a shade below Phase D's 76.2% only because Z3.Linq.Examples now falls inside the coverage filter: covered lines went from 555 to 627 against a denominator that grew by 99. Mutation-checked: making Distinct assert nothing fails 11 tests, and reading every collection element from index 0 fails 6. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * Strengthen the acceptance assertions Two gaps found in review, both real. The puzzle A test constrained 21 givens and asserted 8 of them, under a comment claiming the givens survive the solve. A regression that dropped or mistranslated some but not all of the constraints would have passed. All 21 are now asserted - that failure mode is the whole reason for testing at this size. AssertIsValidCrossing checked how many people moved per step but not which way they went. The sample alternates by parity - from an even step the boat leaves the near bank, from an odd step it returns - so a plan that crossed twice in the same direction without the boat coming back would have satisfied a magnitude-only check. The direction is now asserted per step. Verified the new check has teeth: inverting its parity fails 3 tests. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
* Populate symbols the solver leaves uninterpreted A Z3 model is partial: it assigns values only to the constants the solver actually needed. Marshalling a solution evaluated every symbol without asking for model completion, so a symbol the model did not interpret evaluated to the term itself - an IntExpr rather than an IntNum - and the cast failed. The condition is not "no constraint mentions it" but "the model does not interpret it": a tautology the solver discards as it is asserted leaves its symbol uninterpreted just the same. All four evaluation sites now route through one EvaluateWithCompletion helper, so the invariant is stated and enforced in one place rather than repeated four times - which is how the omission came to exist at all. The helper is appended at the end of the class so that no line moves and the ~23 Theorem.cs:NNN citations in the test comments stay accurate. Fixes endjin#51. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * Document why the evaluation helper takes a nullable term The signature is deliberate rather than an oversight, but nothing said so. It now records that Environment.Expr is nullable, that the anonymous-type branch passes it unguarded, that the resulting NullReferenceException is reachable and pre-existing, and that endjin#75 tracks a better fix than a defensive guard would be. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Thirty-two tests carried a constraint - usually .Where(t => t.X2 == 0) - whose only purpose was to keep the second symbol referenced, because an unreferenced one made Solve throw. With endjin#51 fixed they are noise, and they were actively misleading: a reader could not tell which constraints were part of a test's subject and which were there to work around a defect. Removing them turns those tests into regression coverage for the fix. Reverting the completion flag now fails 51 tests rather than 12. Constraints whose value a test actually asserts are kept - the point stands only where the symbol was genuinely incidental. Also captures the exception on the invariant-culture thread. That solve ran on a bare Thread with no try/catch, so an exception there was unhandled and killed the test host: the run reported "zero tests ran" instead of one failure, which made the mutation check above impossible to read. Its sibling pin already did this. Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
* Render real constants invariantly ExpressionVisitor handed real constants to Z3 with the current culture, so a comma-decimal culture produced "1,5" and Z3's parser rejected it. Measured over the 606 specific cultures installed on this machine, 301 of them - about half - could not solve a theorem containing a real literal. The two culture tests move out of SymbolTypeMarshallingTests into a file of their own, joined by coverage for the negative-sign and non-comma-separator cases that a naive fix would miss. Fixes endjin#52. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * Let the culture harness time out cleanly The solve threads were foreground, so one that outlived its bounded Join would hold the test host open indefinitely - measured: a process whose Main has returned does not exit at all while a foreground thread is still running. That turned the timeout from a clean failure into a stalled run. SolveOn now takes the resolved CultureInfo rather than a name, so the control test names the invariant culture instead of passing an empty string, and the timeout message has something to say for it. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Working out how many elements to marshal cast the FieldInfo itself rather than the collection it points at, so every environment with a collection in a public field threw InvalidCastException. Scalar fields were unaffected; the property branch beside it was already correct. Fixing it makes the element-materialisation loop reachable through a field for the first time, so the tests walk that whole path rather than stopping at the one case in the issue. Fixes endjin#53. Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
TypeCode.Single parsed the model value with double.Parse, so a solved float symbol was boxed as a double and reflection refused to write it to a float member. Translation, solving and the model were all correct; only the last step lost the answer. Parsing straight to float rounds once rather than parsing to double and narrowing. The array element arm carried the same defect and is corrected with it, though no test can reach it while endjin#64 stands. Fixes endjin#54. Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
* Read the decimal element the loop selected The decimal arm of the array element loop evaluated subEnv.Expr - the whole array constant - instead of numValExpr, the element the loop had just selected with MkSelect. Every other arm of that loop uses numValExpr. Casting an ArrayExpr to RatNum can never succeed, so the arm always threw InvalidCastException rather than giving every element the same value, which is what the issue predicted as the alternative. endjin#64 recorded this code as unreachable. That holds only for a constraint naming a decimal constant, which fails during translation. With the elements left free the theorem solves and the loop runs, which is how the three new tests observe the fix. Fixes endjin#55. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * Remove a duplicated remarks tag The rewritten remarks on the decimal array pin ended with </remarks>, and the original closing tag below it was left in place, so the comment closed twice. Raised by the Copilot review on endjin#81. The build did not catch it because no project sets GenerateDocumentationFile, so the compiler never parses the XML - see endjin#82. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
The write path encodes a DateTime with ToFileTimeUtc; the read path decoded it with FromFileTime, whose result is local time. A DateTime symbol therefore came back shifted by the machine's UTC offset, so the same theorem answered differently on different machines and identically to the input only on a machine running in UTC - which is why CI never saw it. Both read sites now use FromFileTimeUtc, the actual inverse of what the write path uses. The alternative the issue offers - ToFileTime on the write path - was measured and does not work: for a DateTime whose kind is Utc the two write conversions are identical, so the issue's own repro stays broken. Fixes endjin#56.
* Report satisfiability separately from the solution Solve reports "no solution" by returning default(T). For a value-type environment that is a fully populated all-zero instance, which is also the answer to plenty of satisfiable theorems, and which cannot even be compared against null - the comparison is error CS0037. So an unsatisfiable theorem over a value tuple was indistinguishable from a solved one. TrySolve and TryOptimize return the status alongside the solution, for every environment type; SolveOrNull and OptimizeOrNull lift a value-type environment to Nullable<T> so the usual null checks apply. Solve is unchanged, so existing callers keep compiling. Optimize now returns T? rather than a non-nullable T it was filling with default!, which turned six unchecked dereferences in the optimisation tests into compiler errors. The workaround the original report suggested - declaring the environment as (int a, int b)? - was measured and does not work: it returns null when unsatisfiable but throws when there is a solution to write. Fixes endjin#57. Fixes endjin#58. * Say what OrderBy actually returns Both operators return an ISolveable<T> - a deferred optimisation - but their returns docs described the solution instead, which is what Solve on that value eventually produces. OrderByDescending's summary also called it OrderBy. No compiler setting would have caught this: the XML is well formed and every cref resolves, the sentence is simply about the wrong thing. Checked the rest of the way while here - with GenerateDocumentationFile temporarily on, the whole solution compiles with no CS1570 and no CS1574, verified against a deliberately broken cref to confirm the check reports one. The project change was reverted; it belongs to endjin#82. * Count the dereferences the signature change caught The remark on Optimize_WithUnsatisfiableTheorem_ReturnsNull said the endjin#58 signature change turned "six unchecked dereferences" in the file into compiler errors. Six is the number of tests; the number of dereferences is ten. Measured by deleting the ten ShouldNotBeNull guards the fix added and building: ten CS8602s, one per guard. The sentence exists to say that the compiler found the callers, so the count carrying it should be the one a reader can reproduce. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
A short symbol could not be solved at all, and neither could an enum. Two defects in series, either of which hid the other. Translation: C# widens short to int for a comparison, and an enum's TypeCode is that of its underlying type, so both arrive at the Int32 arm of the conversion switch - which assumed the target type told it the operand's Z3 sort and cast an IntExpr to RealExpr. The arm now checks the operand: a value already at integer sort passes through, and only a real goes to MkReal2Int. The Char arm three lines below already did exactly this. Marshalling: TypeCode.Int16 shared the Int32 arm and handed reflection an int, which a short member rejects. It gets its own arm with a checked cast. Checked, not plain: the symbol is an unbounded MkIntConst, so Z3 can pick a value no short can hold, and an unchecked cast wraps 40000 to -25536 - a wrong answer that looks like a right one. Raised as endjin#87, which would bound the symbol so the situation cannot arise. Enums need nothing on the marshalling side. endjin#63 predicted a second defect there; reflection converts an int to an enum member on its own, measured rather than assumed. Also removes a switch on the operand type whose only cases were empty breaks, and drops the two characterisation pins these replace. Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Only an int collection could be solved. Every other element type declared a Z3 array whose domain or range contradicted how its elements were constrained and read back: bool and string were indexed by their own type while every element is read with an integer index; long, DateTime, float, double and decimal declared bit-vector or floating-point ranges while their constraints translated to integer and real terms. Only the int row was consistent with itself. The collection mapping is gone. There is now one function from CLR type to sort, and a collection is an array from Int to whatever that function says a scalar of the element type is. The two cannot disagree because there is nothing else to consult - reverting a single row of the shared mapping fails scalar and collection tests together. The array-element read for short gets the checked cast the scalar arm has had since endjin#63; the arm was unreachable until now and is covered for the first time. Object collections - Holder[] with scalar properties - remain unusable in every shape, which is a different mechanism raised as endjin#89; their per-property arrays are declared through the same mapping so that part is settled. Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
An anonymous environment holding a nested object threw a bare NullReferenceException from inside the native interop. A nested environment has no handle of its own, and the anonymous-type branch of GetSolution evaluated the handle before looking at the type, so the null went straight to Model.Eval. The three sites in ConvertZ3Expression guard against exactly that; this fourth one did not. The fourth site is gone. The branch carried a marshaller of its own that handled bool and int and refused everything else; it now calls ConvertZ3Expression like every other environment shape, so an anonymous environment supports every type a named one does, nested objects included - the nested object is materialised by the recursion in there rather than evaluated here. Measured across eleven shapes, all of which threw before. A collection is the one thing the shared path cannot do for an anonymous type, because the element count is read from the instance and the instance is created uninitialised. It is refused by name, with the reason, rather than left to fail on the null count. EvaluateWithCompletion takes a non-nullable Expr again. It was made nullable in endjin#51 for this one caller, and the paragraph explaining that goes with it. Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
A double symbol could not be compared against a float variable. C# widens the float, and the visitor read the Convert node's target type as telling it what the operand was: every conversion to double was integer-to-real, so a real operand was cast to IntExpr and failed. The same assumption meant two symbols of different real types could not be related at all, and long, float and decimal had no arm whatever - a long symbol could not be compared to an int one. A numeric conversion is one of three things in Z3, decided by the sorts: nothing when both types map to the same sort, integer-to-real, or real-to-integer. The visitor now asks TryGetSymbolSort - the one mapping the symbols are declared with, internal from here - for the target sort and decides from that and the operand. The arm endjin#63 added for short and enums was this rule for one row and is subsumed; its tests still fail when the rule is wrong. The pin that recorded (long)t.X1 as unsupported is repointed at (byte), which the mapping genuinely has no row for, so the catch-all stays covered. Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
A collection symbol takes its length from the collection already on the solution instance, and read it with no null check: an environment that declared a collection without initialising it threw a bare NullReferenceException naming nothing. A value tuple could never hold a collection at all - the instance is built with Activator.CreateInstance, and a tuple has nowhere to put an initialiser. The instance passed to NewTheorem(T) is now the template for the solution. It was a parameter named dummy that the method discarded; its collections now give the solution's collections their length, ahead of any initialiser on the type, and it is carried through Where and into the optimiser. Nothing else about it is read. A collection with no length from either source is rejected by name, with the reason. That is what lets a tuple carry a collection, and an anonymous type too - the guard endjin#75 added for anonymous collections is gone, since the template is exactly the initialised instance it was missing. Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
No project set GenerateDocumentationFile, so the compiler never parsed a doc comment and the package shipped no documentation file. A malformed comment reached endjin#81 and was caught by a reviewer rather than the build, despite TreatWarningsAsErrors. The setting now goes on in Directory.Build.props for every project. Malformed XML and unresolvable crefs are build errors from here, and the packable projects ship their documentation. CS1591 - a public member with no comment - is enforced for Z3.Linq only; the test, examples and demo projects suppress it, each saying why in its project file. Turning it on found three defects this stack had already introduced: the documentation for GetSolution<T> had come loose from its method when two helpers were inserted between them, and was reporting a typeparam and three params that its new host does not have. It is back on the method, with the template parameter it gained in endjin#78. The 21 public members that had no comment - Environment and its members, ExpressionVisitor, the two rewriter interfaces and the three attributes, and Optimization - are documented. Two negative controls confirm the guard has teeth: a broken cref is error CS1574, and a duplicated closing tag in a test remark is error CS1570. Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
A DateTime travelled through Z3 as a Windows file time, which counts from 1601-01-01 and cannot express anything earlier. A constant before that threw out of ToFileTimeUtc during translation, and a satisfiable theorem whose models lay before it - t.X1 < 1601 - solved and then threw while its solution was read, blaming a fileTime parameter no caller had supplied. Two thirds of the type's range was unusable. It now travels as its ticks, which cover the whole range. The kind convention from endjin#56 is kept exactly: a Local value is converted to UTC on the way in, Unspecified is taken as UTC, and everything is read back as UTC. An unconstrained symbol now completes to DateTime.MinValue rather than 1601-01-01; nothing asserted the old value. The read is guarded. The symbol is an unbounded integer, so a constraint like t.X1 > DateTime.MaxValue still has a model in Z3, and the guard turns that into an OverflowException naming the symbol and the range instead of the constructor's complaint about a parameter. The same trade-off as the checked read of a short, and endjin#87 applies here too. Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Z3Context built its native context from a fixed configuration and offered nothing to add to it: no timeout, no resource limit, no CancellationToken. A theorem Z3 cannot decide - nonlinear integer arithmetic is undecidable in general - ran until the process was killed. And because nothing could bound a solve, Status.UNKNOWN was unreachable and was reported as unsatisfiable. Z3Context gains Timeout and ResourceLimit, applied as parameters on each solver and optimizer so they can change between solves. Every entry point takes an optional CancellationToken, wired to Context.Interrupt; the token is also inspected before the check, because an interrupt that arrives before Z3 starts is lost - measured on the raw API. An UNKNOWN is now an exception. A cancelled token throws OperationCanceledException; anything else - a limit reached, or Z3 giving up - throws TheoremUndecidedException with Z3's reason. The reason strings cannot distinguish the two (the optimizer says "canceled" for both), so the token decides. TrySolve returning false now means only that the theorem was proved to have no solution, which closes the wrinkle endjin#57 raised and endjin#86 had to leave open. Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
A short, int, long or DateTime symbol travels through Z3 as an unbounded integer, and nothing told Z3 the range. A constraint no value of the type could satisfy - a short equal to 40000, a DateTime after MaxValue - still had a model, and the failure came on the way out, as an OverflowException from the checked read. And optimising such a symbol with no other bound returned an arbitrary value, measured as zero, rather than the extreme of the type. AssertConstraints now walks the environment and asserts low <= symbol <= high for every scalar whose type has a range, descending into nested objects. So the impossible constraint is unsatisfiable, which is the true answer, and the optimisation returns short.MaxValue, int.MaxValue and so on. This also closes the int route endjin#87 called unreachable, which endjin#76 had since opened. Only scalars are bounded. A collection's length is not known when the constraints are asserted, and bounding every element would take a quantifier that can cost Z3 its completeness, so an element keeps the checked read and the loud OverflowException. Enum membership is a separate rule, raised as endjin#97. Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
…djin#99) The expression-tree layer had three rough edges. A ternary (Conditional node) had no case and threw "Unsupported expression node type"; it now maps onto Z3's if-then-else. Integer bitwise & | ^ and real % were translated by an unconditional cast that assumed the operand sort from the node - so bool & bool worked but int & int, and real %, crashed with an InvalidCastException from inside Z3, naming neither the operator nor the reason. The operators now choose by the operands' sort, the way the Convert case was taught to in endjin#63/endjin#76. Boolean operands still give the logical operators; an integer bitwise op and a real modulo are refused with a message that says a bit-vector representation would be needed, and that Z3 has no real remainder. Genuine bitwise support needs bit-vector symbols, which is a separate feature. Also cached the three reflected MethodInfos the Distinct translation looked up on every visit (Z3Methods.Distinct and two Enumerable methods), and removed the commented-out VisitParameter and a dead Debugger.Break branch. Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
ExpressionVisitor was a public static class that threaded the Z3 context, the environment, and the constraint lambda's parameter through every method - four arguments on each, of which three are invariant for the whole translation. It is now an internal sealed class that holds those three as readonly fields, set once by a static Translate entry point, so the Visit* methods take only the node they translate. The dispatch lambdas still take the context, so they stay non-capturing and compiler-cached rather than allocating per node. Behaviour is unchanged - the 290 tests pass as before; this is a shape and visibility change, the visibility being the point: the class was public "for historical reasons" with no supported reason to call it, and the .NET 10 major version is the moment to stop shipping it as API. Nothing outside the assembly referenced it. Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
The second endjin#99 follow-up: give integer-like symbols the operators an unbounded integer cannot carry - bitwise & | ^ ~, shifts, and wrapping arithmetic with unsigned comparison - by mapping uint and ulong to Z3 bit-vectors of their width (32 and 64). Purely additive: those types were rejected before. The operator dispatch now chooses by the operands' sort - a bit-vector gets the BV form, an int or real the arithmetic form, a bool the logical one - so & | ^ and ~ work on bit-vectors, are refused clearly on plain integers (Z3's integer sort has no bitwise ops), and still do Boolean logic on bools. Shifts convert their int amount to the value's width; comparisons are unsigned, matching uint/ulong. byte and ushort are deliberately left unsupported: C# promotes them to int in every expression, so such a symbol could never keep its bit-vector sort through a constraint - mapping them would be a trap, not a feature. Measured while building this; documented on BitVectorWidth. Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
The sub-int integer types could not be used as symbols. They cannot be bit-vectors like uint and ulong, because C# promotes them to int in every expression and the promotion would strip a bit-vector sort - so they map to the integer sort instead, bounded to their range, exactly the way short already works. Mapping them to int makes the promotion a no-op in Z3 terms, which is what lets short work and now lets these. They support equality, ordering and arithmetic, and the endjin#87 range bounds keep an out-of-range constraint unsatisfiable rather than read back wrong; they do not support bitwise operators, which need uint or ulong. Every enum underlying type is now a supported type, so a byte-backed enum round-trips like an int-backed one - the pin that expected it to throw becomes a positive test, and the unmapped-cast pin moves from (byte) to (nint), whose TypeCode is Object and which the mapping genuinely has no row for. This is the fix for a byte or ushort member on an environment type a caller cannot rewrite to uint - the case the bit-vector work left with no workaround. Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Both were introduced with the timeout/resource-limit work. The Params object carrying the limits is native-backed and IDisposable, but it was assigned to the solver and dropped without disposing - a native leak on every solve that set a limit. It is now a using, disposed when the check returns, by which point the solver has taken what it needs. A sub-millisecond timeout truncated to zero: (uint)TimeSpan.TotalMillis- econds of 0.5ms is 0, and Z3 reads timeout 0 as no timeout, so a caller asking for a tiny timeout silently got none and would hang on an undecidable theorem. The value now rounds up, so any positive timeout is at least one millisecond. A third review finding - that maximising an unsigned bit-vector might use signed ordering - was measured and does not hold: Z3's MkMaximize on a bit-vector is unsigned, so a uint in [2e9, 3e9] maximises to 2999999999. Claude-Session: https://claude.ai/code/session_01PipoHZJsgydrV3JC3fQN6Q Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
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. Claude-Session: https://claude.ai/code/session_01PipoHZJsgydrV3JC3fQN6Q Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
…jin#105) The benchmark suite showed every Solve/Optimize re-doing reflection whose answer is fixed for the life of the environment type, and the collection marshaller double-allocating. This caches the per-type reflection and fills the collection array in place, cutting managed allocation per solve by ~18-26% across every environment shape, with no behaviour change (322 tests still green). - Cache the TheoremVariableTypeMappingAttribute lookup per type: the environment builder, the bounds asserter and the marshaller each asked for it - three times per member per solve - allocating an attribute array each time. Absence is cached as cheaply as presence. - Cache the public instance property and field arrays per type, which GetProperties/GetFields otherwise reallocate on every solve. - Guard the global- and predicate-rewriter attribute lookups with IsDefined, so the common no-rewriter path allocates no attribute array. The predicate lookup is hit once per call node in every constraint. - Replace the CompilerGenerated .GetCustomAttributes(...).Any() anonymous-type check with IsDefined, which allocates nothing. - Fill the collection element array in place instead of an ArrayList that keeps a boxed object[] backing store and is then copied into a typed array by ToArray. Measured with the Z3.Linq.Benchmarks suite (BenchmarkDotNet, short job, MemoryDiagnoser). Allocation is deterministic; the Mean times are dominated by native Z3 context creation per solve and sit within short-job noise, so no time claim is made. | Shape | Before | After | |---------------|---------|---------| | ScalarSymbols | 4.48 KB | 3.32 KB | | ValueTuple | 4.51 KB | 3.39 KB | | NestedObject | 6.44 KB | 4.93 KB | | Collection | 5.59 KB | 4.60 KB | | WideSymbols | 8.05 KB | 6.23 KB | | Optimize | 5.44 KB | 4.30 KB | Claude-Session: https://claude.ai/code/session_01PipoHZJsgydrV3JC3fQN6Q Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
* Modernise the solve path with C# 14 idioms
Small, behaviour-preserving cleanups that lean on language features now
available on net10.0 (C# 14 is the default language version). No public API,
behaviour or allocation change - 322 tests unchanged, and the changes are on
paths the benchmark suite already covers.
- Z3Context.Timeout / ResourceLimit use the C# 14 `field` keyword, so the
validating setters no longer need a pair of hand-rolled backing fields;
CreateLimits reads the properties instead of the removed fields.
- GetSolution's property/field marshalling loop becomes a pattern switch,
dropping the `is X` followed by `as X` plus null-guard dance - the member
is only ever a PropertyInfo or a FieldInfo, and each is now bound once.
- Collection expressions replace `new List<T>()` / `new T[] { x }` /
`new object[] { x }` where the intent is a throwaway or empty collection
(the empty-constraint constructors, the single-constraint append in Where,
the reflection argument arrays, the member-hierarchy list). The one list
built with a capacity hint keeps its `new List<T>(count)`.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PipoHZJsgydrV3JC3fQN6Q
* Convert two more dispatches to pattern matching
Continues the modernisation with the two remaining spots where a type test
was still written as an enum switch plus a cast, or as a returning switch
statement that a switch expression states more directly.
- VisitConstantValue becomes a switch expression on the constant's TypeCode,
with `or` patterns grouping the integer and real cases. The type code is
read once rather than a second time inside the bit-vector arm.
- VisitMember's captured-constant walk uses type patterns (PropertyInfo /
FieldInfo) instead of switching on MemberType and casting.
Behaviour-preserving: 322 tests unchanged, and allocation unchanged, confirmed
with the benchmark suite (every shape within run-to-run rounding of its prior
figure). Both are on paths the tests already cover.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PipoHZJsgydrV3JC3fQN6Q
* Fold the remaining null checks into ?? and ?.
Completes the modernisation with the null-guard shapes the codebase had not
yet moved to null-coalescing / null-conditional form. Each is behaviour-
identical.
- The two mapped-type constructor lookups in ConvertZ3Expression become
`GetConstructor(...) ?? throw`, dropping the separate `if (ctor == null)`.
- The collection element type becomes `(... ? GetElementType() : ...) ?? throw`,
which also removes a null-forgiving `!` that was suppressing the very null the
next line then tested for.
- VisitMember's captured-constant tail becomes
`VisitConstantValue(val ?? throw ...)`.
- The type-mapping assignment becomes `mapping?.RegularType ?? parameterType`
in both GetEnvironment and ConvertZ3Expression - matching SymbolType, which
already reads this way; GetEnvironment no longer needs the temporary at all.
- Z3Context.LogWriteLine becomes `Log?.WriteLine(s)`, which also reads Log once
rather than across a check-then-use gap.
Behaviour-preserving: 322 tests unchanged, allocation unchanged (these are
control-flow null checks, and the benchmark suite confirms every shape within
run-to-run rounding of its prior figure).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PipoHZJsgydrV3JC3fQN6Q
---------
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
The `member switch { PropertyInfo => .PropertyType, FieldInfo => .FieldType,
_ => throw }` shape appeared verbatim in three places - SymbolType, the
environment builder and the marshaller. One private helper now owns it, so the
"a symbol is a property or a field, and its type is one or the other" rule has
a single name and a single definition.
Pure extraction: 322 tests unchanged, and allocation cannot change - the tiny
helper is a static method the JIT inlines back to the switch it replaced.
Claude-Session: https://claude.ai/code/session_01PipoHZJsgydrV3JC3fQN6Q
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
A theorem is checked with either a Solver or an Optimize, held as a Z3Object, and both AssertConstraints and AssertBounds switched on which one to call the matching Assert. That identical block now lives in one private helper, so adding a term to assert reads as `Assert(approach, term)` and the Solver-or-Optimize dispatch has a single home. The other per-approach operations (Check, ReasonUnknown, applying the limits) are distinct and stay where they are - two of them are already switch expressions. Pure extraction: 322 tests unchanged, allocation cannot change. Claude-Session: https://claude.ai/code/session_01PipoHZJsgydrV3JC3fQN6Q Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Reading a solved symbol back from the model was written twice - once for a scalar member, once per collection element - as two ~35-line switch statements that were arm-for-arm identical: the same casts, the same checked conversions, the same decimal-string handling, differing only in which Expr they read and which "unsupported type" message they threw. One `ReadZ3Value` now owns the reader, and a small `ParseZ3Decimal` owns the shared trailing-'?' decimal parse. Net -64 lines, and a type that reads back wrong now has one place to fix rather than two to keep in step. The element path passes its element type so the array-specific diagnostic is preserved; a null there selects the scalar message. The collection loop reads its element type code once now, rather than on every element. Behaviour-preserving: - 322 tests unchanged. - A mutation of the shared Int32 arm (+1) fails 111 tests, across both the scalar and the collection paths - the reader is exercised, and a regression in it is caught. - Allocation unchanged (the per-arm boxing is the same), confirmed with the benchmark suite: every shape within run-to-run rounding of its prior figure. Claude-Session: https://claude.ai/code/session_01PipoHZJsgydrV3JC3fQN6Q Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
* Convert the demos to single-file Spectre.Console apps Replaces the Z3.Linq.Demo project - a single Program.cs that wrote its output with Console.WriteLine - with a series of standalone .NET file-based apps (`dotnet run demos/<name>.cs`) that render the same problems with Spectre.Console: figlet banners, rules, panels, tables, and a 9x9 Sudoku grid. Each demo is one file that declares its own dependencies at the top (`#:package Spectre.Console`, `#:project` the Z3.Linq and Z3.Linq.Examples projects), so it needs no solution entry and builds against local source. Z3.Linq.Examples is untouched - it is the reusable theorem library the demos consume, not a presentation concern. Demos, one file each: - river-crossing.cs - Missionaries & Cannibals; Solve (any plan) vs Optimize/orderby (the shortest), as a crossing table plus a comparison. - sudoku.cs - two puzzles on a rendered grid, clues driven through expression-tree constraints so the puzzle array is the single source of truth. - boolean-logic.cs - x XOR y over an anonymous type, a value tuple and a record. - linear-systems.cs - small integer systems incl. Bart's TechEd 2012 example. - oil-purchase.cs / warehouse.cs - least-cost linear programs. - menu.cs - a Spectre SelectionPrompt launcher that runs the others. Non-ASCII is limited to the Sudoku box-drawing; the maths and logic are ASCII, so the demos render in any terminal and degrade to plain text when redirected. - Removed solutions/Z3.Linq.Demo and its .slnx entry; README now points at demos/, and demos/README.md lists and explains each one. - Each of the six content demos verified with `dotnet run`; menu.cs builds. - `./build.ps1 -Configuration Release` - 46 tasks, 0 errors, 0 warnings, with the Demo project gone. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PipoHZJsgydrV3JC3fQN6Q * Silence nullable-dereference warnings in the demos Theorem<T>.Solve() returns T?, so dereferencing the result of a reference-type environment without a guard warned CS8602. Value-type environments (the tuples) were already fine, and the guarded demos (river-crossing, sudoku) already were too. Null-forgive the reference-type solves - boolean-logic's anonymous-type and record rows, and linear-systems' two Symbols<...> sections - since XOR and those small systems are always satisfiable. All six demos now build with zero warnings and run unchanged. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PipoHZJsgydrV3JC3fQN6Q * Update the README for the Polyglot Notebooks deprecation ".NET Interactive" is now "Polyglot Notebooks", and Microsoft deprecated both in early 2026 and archived dotnet/interactive (read-only since April 2026). No community-maintained fork has been established - only discussed. Renames the reference, adds a sourced deprecation note, and leads the Examples section with the single-file demos as the maintained, tooling-free way to run the examples. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PipoHZJsgydrV3JC3fQN6Q * Remove the Polyglot Notebook Microsoft deprecated and archived Polyglot Notebooks / .NET Interactive, so the examples/z3-problems.dib notebook and every reference to it are removed: the Examples section now points only to the maintained single-file demos, the "For Polyglot Notebooks" getting-started subsection is dropped, and the stale notebook link in the project history is removed. The examples/ folder held only the notebook, so it is gone too. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PipoHZJsgydrV3JC3fQN6Q --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
…ir latest (endjin#115) * Update MSTest.Sdk to 4.5.1 and code coverage to 18.12.0 MSTest.Sdk brings MSTest 4.5.1, Microsoft.Testing.Platform 2.5.1 and the TrxReport extension with it. The CodeCoverage pin moves to 18.12.0 to stay in step with the dotnet-coverage collector, which a fresh CI runner installs at its latest version. Every other package is already current: MiaPlaza.ExpressionUtils 1.3.1, Shouldly 4.3.0, BenchmarkDotNet 0.15.8, and Spectre.Console 0.57.2 in the demos. Microsoft.Z3 stays at 5.1.0 from the local feed (endjin#60). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Re5MY9updX4YgSSeQtwWYS * Update Microsoft.Z3 to 5.3.2 5.3.2 fixes incorrect sat results for some derived-array equalities in the SMT array solver, which Z3.Linq relies on to encode collections. It also makes the LP kernel honour timeouts and resource limits and stay usable after a cancellation, and speeds up linear real arithmetic. The package is still not on nuget.org, so it comes from the GitHub release into the local feed, as 5.1.0 did. The pinned SHA-256 matches the digest GitHub publishes for the release asset. It ships the same six native runtimes as 5.1.0 (linux, osx and win, each x64 and arm64). Releases stay on hold under endjin#60. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Re5MY9updX4YgSSeQtwWYS --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* 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 endjin#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 endjin#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 endjin#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 endjin#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 endjin#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 endjin#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 endjin#88 (narrowing) and endjin#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 endjin#105. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
VisitConvert translated a conversion from double, float or decimal to an integer type with MkReal2Int, which is a floor. C# truncates toward zero, so the two disagree for every negative non-integral operand: `(int)t.X1` with X1 == -2.5 solved to -3 where C# gives -2. Positive values and whole numbers were unaffected, which is why the existing test, written with a positive operand, passed. A negative operand is now negated, floored and negated back, which is its ceiling: ite(x >= 0, real2int(x), -real2int(-x)). The new tests cover 2.5, -2.5, -2.0, -0.5 and 0.0 for double to int, and 7.75 and -7.75 for decimal to long, with the expected value computed by C# from the returned symbol. Before the change the three negative non-integral cases failed and the rest passed. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Two ways a constraint naming a value, rather than a symbol, failed in VisitMember. A static field or property threw "Unknown parameter encountered". A const is folded by the compiler, but a static readonly field is not - DateTime.MaxValue, MinValue and UnixEpoch are all static readonly - and nor is a static property, so the tree carries a member access with no instance, which the visitor had no case for. So `t.X1 == DateTime.MaxValue` could not be written inline, and the existing DateTime tests got round it by copying the boundary into a local. A chain that starts at a static member is now read and translated as a constant, like one that starts at a captured variable. It is read when the theorem is solved, as a captured local is. A chain of members on a captured variable threw TargetException. `holder.In.Value` is three members starting at the closure constant, and the loop read each of them from the closure instead of from the previous member's value, so any chain longer than one failed. Each member is now read from the value before it, and a link that is null is refused with a message naming it. Inline `t.X1 > DateTime.MaxValue` now reaches Z3 and has no solution, because the symbol is bounded to the DateTime range (endjin#98). Reported by jsboige on endjin#110. jsboige's endjin#113 fixes the DateTime fields on feature/datetime-ticks; this covers every static field and property. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Resynchronize the CoursIA fork on endjin 964f177 while retaining downstream collection, witness, solver, Pseudo-Boolean, Rational and constructor-initialized environment capabilities. Resolve the captured-null conflict by translating the original constraint when host partial evaluation leaves an ExceptionClosure marker, preserving upstream's named refusal. Keep lazy template reads and select Solve(CancellationToken) by signature in the reflection test. Refresh net10.0 .deploy artifacts, including Microsoft.Z3 5.3.2 and native libz3. Build Release net8.0/net10.0: 0 warnings, 0 errors. MSTest/MTP: 471 passed, 0 failed. Update the dated divergence mapping without importing fork PR #43. See jsboige/CoursIA#19237 Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Lane: myia-po-2023:CoursIA
Twenty consumer notebooks executed with 235/235 cells and no errors. The mapped conversion defect reproduces on upstream main and is proposed as endjin#129. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Lane: myia-po-2023:CoursIA
Code Coverage Summary Report - Linux (No TFM)Summary
CoverageZ3.Linq - 90.7%
Z3.Linq.Examples - 48.9%
|
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.
Grain: DEEP/notebook-dotnet — lane myia-po-2023:CoursIA — prev: MED/notebook-python #27309
Summary
Merge current
endjin/main964f17704e38399e6ad15a971d3d5aee61fcfb32into the fork without rebasing forkmain. Keep the CoursIA-only extensions and consumer contracts, adopt upstream behavior where it covers the same mechanism, and document the remaining measured divergences.92f8ff104e1a0df348036c4d396bed6ab191e35a(a0477d9c594433671af51759b8fdc71fb37c5df0+964f17704e38399e6ad15a971d3d5aee61fcfb32).5071d6f— 20 consumer notebooks and the measured G4 follow-up.Z3.Linq.dll, Microsoft.Z35.3.2.0, nativelibz3.dll, and unchangedExpressionUtils.dll.Build and tests
Measured on the merged code at
92f8ff1:The later
5071d6fcommit changes onlyDIVERGENCE_STATUS.md.Consumer execution
All 20 CoursIA notebooks in
MyIA.AI.Notebooks/SymbolicAI/SMT/Z3-Linq2Z3were executed through MCP Papermill on isolated copies, in their actual directory, against the rebuilt.deployartifacts:Output review: notebooks 03, 04 and 11 are identical after removing bootstrap HTML and obsolete CS1701 warnings. Notebook 07 differs only in Ciqual load time. Other differences are alternate SAT/regex witnesses accepted by each notebook's constraints, timing/processor/runtime changes, the Microsoft.Z3 assembly version change (
4.12.2.0to5.3.2.0), different measured solver timings, and an upstream exception-message wording change. No genuine output was replaced by a fallback message and no notebook output was hand-edited.No source notebook was changed, so no execution-output commit is included.
G4 follow-up
964f177:VisitConvertthrewNotImplementedExceptionfor(ExactReal)2.5.main, with four targeted green tests and 372/372 tests on net10.0. Its net8.0 validation is explicitly still pending in that PR.See jsboige/CoursIA#19237. The CoursIA gitlink bump follows the fork merge.
🤖 Generated with Claude Code