tazel
A build system for C, C++, Objective-C, Objective-C++ and Zig, with C# project files.
Clonegit clone https://git.progmasoft.com/tazel
feat(lock): add order-independent Z3ModuleResolver (#53)
- Commit
60f630944ea69cd2f327a9f34dbdb6de2f783f7f- Author
- Leitwolf ·
- Committer
- GitHub
- Parents
99b7aa14afea
Changes
.github/workflows/ci.yml | 20 + CHANGELOG.md | 1 + THIRD-PARTY-NOTICES.md | 1 + src/Progmasoft.Tazel/Cli/LicenseText.cs | 1 + src/Progmasoft.Tazel/Lock/Z3ModuleResolver.cs | 569 ++++++++++++++++++++++++ src/Progmasoft.Tazel/Lock/Z3NativeLibrary.cs | 219 +++++++++ src/Progmasoft.Tazel/Progmasoft.Tazel.csproj | 2 + tests/Progmasoft.Tazel.Tests/Z3ResolverTests.cs | 118 +++++ 8 files changed, 931 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index df7383b..180e3c2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -54,6 +54,19 @@ jobs: tar -xJf "$RUNNER_TEMP/zig.tar.xz" -C "$RUNNER_TEMP/zig" --strip-components=1 echo "$RUNNER_TEMP/zig" >> "$GITHUB_PATH" + # Official Microsoft.Z3 NuGet does not bundle linux-x64 or osx-arm64 native binaries. + - name: Install libz3 (Linux) + if: runner.os == 'Linux' + shell: bash + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends libz3-4 + + - name: Install libz3 (macOS) + if: runner.os == 'macOS' + shell: bash + run: brew install z3 + # clang on Windows takes the headers and libraries of MSVC from the environment vcvars64 sets. - name: Load the MSVC environment if: runner.os == 'Windows' @@ -310,6 +323,13 @@ jobs: dotnet test --project tests/Progmasoft.Tazel.Tests -c Release --no-build --output Detailed --filter-class Progmasoft.Tazel.Tests.WorkspaceTests + - name: Test Z3ResolverTests (macOS) + if: runner.os == 'macOS' + timeout-minutes: 10 + run: >- + dotnet test --project tests/Progmasoft.Tazel.Tests -c Release --no-build --output Detailed + --filter-class Progmasoft.Tazel.Tests.Z3ResolverTests + - name: Test # A test that hangs is named and dumped at 15 minutes, and the run stops itself at 20, before the step's own # limit, so the job ends with its log and its files kept instead of being cancelled at the job's limit. diff --git a/CHANGELOG.md b/CHANGELOG.md index 79c479e..9647810 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ ## Unreleased +- Added `Z3ModuleResolver` (`Microsoft.Z3`) for order-independent lexicographic dependency resolution with unreachable-module elimination, yanked-version handling, cycle detection, and subset-minimal UNSAT conflict cores. - Added `Progmasoft.Tazel.Lock` (`LOCK.sqlite3`) deterministic SQLite lockfile reader, writer (`VACUUM INTO`, fixed page size, sorted inserts), JSON exporter, semantic diff/Markdown formatter, and verifier. - Added `tazel_registries.txt` lexer and parser (`Progmasoft.Tazel.Dsl.Registries`), error code `E0510`, fuzz target `registries`, and structured priority/URL reporting in `tazel log registries`. diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md index 26de833..5812bdf 100644 --- a/THIRD-PARTY-NOTICES.md +++ b/THIRD-PARTY-NOTICES.md @@ -15,6 +15,7 @@ Tazel ships with the libraries below. Their licenses are in [LICENSES/](LICENSES | [BouncyCastle.Cryptography](https://github.com/bcgit/bc-csharp) | MIT | Copyright (c) 2000-2026 The Legion of the Bouncy Castle Inc. | | [Microsoft.Data.Sqlite](https://github.com/dotnet/efcore) | MIT | Copyright (c) .NET Foundation and Contributors | | [SQLitePCLRaw](https://github.com/ericsink/SQLitePCL.raw) (with SQLite, public domain) | Apache-2.0 | Copyright (c) Eric Sink | +| [Microsoft.Z3](https://github.com/Z3Prover/z3) | MIT | Copyright (c) Microsoft Corporation | The libraries that only build and test Tazel (xUnit, CsCheck, Snapshooter, Coverlet, BenchmarkDotNet, SharpFuzz, DocFX) are not part of what is shipped. diff --git a/src/Progmasoft.Tazel/Cli/LicenseText.cs b/src/Progmasoft.Tazel/Cli/LicenseText.cs index dc78700..4fca749 100644 --- a/src/Progmasoft.Tazel/Cli/LicenseText.cs +++ b/src/Progmasoft.Tazel/Cli/LicenseText.cs @@ -21,6 +21,7 @@ internal static class LicenseText new("BouncyCastle.Cryptography", "MIT", "https://github.com/bcgit/bc-csharp"), new("Microsoft.Data.Sqlite", "MIT", "https://github.com/dotnet/efcore"), new("SQLitePCLRaw (with SQLite, public domain)", "Apache-2.0", "https://github.com/ericsink/SQLitePCL.raw"), + new("Microsoft.Z3", "MIT", "https://github.com/Z3Prover/z3"), ]; /// <summary>Formats Tazel's license and shipped third-party notices in <paramref name="kind"/>.</summary> diff --git a/src/Progmasoft.Tazel/Lock/Z3ModuleResolver.cs b/src/Progmasoft.Tazel/Lock/Z3ModuleResolver.cs new file mode 100644 index 0000000..e761e30 --- /dev/null +++ b/src/Progmasoft.Tazel/Lock/Z3ModuleResolver.cs @@ -0,0 +1,569 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using NuGet.Versioning; + +namespace Progmasoft.Tazel.Lock; + +/// <summary>One candidate version of a module available to the Z3 dependency resolver.</summary> +/// <param name="Group">The module group.</param> +/// <param name="Module">The module name.</param> +/// <param name="Version">The parsed SemVer version.</param> +/// <param name="Yanked">Whether this version has been yanked in its registry.</param> +/// <param name="Dependencies">Direct dependencies required when this version is chosen.</param> +/// <param name="SourceKind">One of <c>registry</c>, <c>local</c>, or <c>directory</c>.</param> +/// <param name="Registry">The registry name when <paramref name="SourceKind"/> is <c>registry</c>.</param> +/// <param name="ArchiveSha256">SHA-256 hex digest of the archive.</param> +/// <param name="ManifestSha256">SHA-256 hex digest of the manifest.</param> +/// <param name="LocalPath">Relative path for local/directory modules.</param> +public sealed record CandidateModuleVersion( + string Group, + string Module, + NuGetVersion Version, + bool Yanked, + IReadOnlyList<LockEdge> Dependencies, + string SourceKind, + string? Registry, + string ArchiveSha256, + string ManifestSha256, + string? LocalPath) +{ + /// <summary>Canonical <c>group:module</c> key.</summary> + public string Key => $"{Group}:{Module}"; +} + +/// <summary>Exception thrown when Z3 module resolution fails (unsatisfiable, cycle, or resource limit).</summary> +public sealed class ResolutionException : Exception +{ + /// <summary>Subset-minimal conflicting request descriptions when the problem is unsatisfiable.</summary> + public IReadOnlyList<string> Conflicts { get; } + + /// <summary>Creates a resolution failure without a conflict core.</summary> + /// <param name="message">The diagnostic message.</param> + public ResolutionException(string message) : base(message) => Conflicts = []; + + /// <summary>Creates a resolution failure carrying a subset-minimal conflict core.</summary> + /// <param name="message">The diagnostic message.</param> + /// <param name="conflicts">The minimal conflicting requests.</param> + public ResolutionException(string message, IReadOnlyList<string> conflicts) : base(message) => + Conflicts = conflicts ?? []; +} + +/// <summary> +/// Order-independent Z3 dependency resolver: minimizes the number of selected modules (eliminating unreachable modules) +/// and then lexicographically maximizes versions in canonical <c>group:module</c> order. +/// </summary> +public static class Z3ModuleResolver +{ + /// <summary>Default deterministic Z3 resource limit.</summary> + public static uint DefaultResourceLimit { get; } = 2_000_000; + + /// <summary>Default wall-clock backstop timeout in milliseconds (60 seconds).</summary> + public static uint DefaultTimeoutMilliseconds { get; } = 60_000; + + /// <summary>Resolves root requests against <paramref name="catalog"/> using default Z3 limits.</summary> + /// <param name="tazelVersion">Tazel version recorded in the resulting lockfile.</param> + /// <param name="rootGroup">Root module group.</param> + /// <param name="rootModule">Root module name.</param> + /// <param name="rootVersion">Root module version.</param> + /// <param name="requests">Root dependency requests.</param> + /// <param name="catalog">Available module versions keyed by <c>group:module</c>.</param> + public static LockDocument Resolve( + string tazelVersion, + string rootGroup, + string rootModule, + string rootVersion, + IReadOnlyList<LockRequest> requests, + IReadOnlyDictionary<string, IReadOnlyList<CandidateModuleVersion>> catalog) => + Resolve(tazelVersion, rootGroup, rootModule, rootVersion, requests, catalog, + new HashSet<string>(StringComparer.Ordinal), DefaultResourceLimit, DefaultTimeoutMilliseconds); + + /// <summary>Resolves root requests against <paramref name="catalog"/> with locked-yanked allowlist and Z3 limits.</summary> + /// <param name="tazelVersion">Tazel version recorded in the resulting lockfile.</param> + /// <param name="rootGroup">Root module group.</param> + /// <param name="rootModule">Root module name.</param> + /// <param name="rootVersion">Root module version.</param> + /// <param name="requests">Root dependency requests.</param> + /// <param name="catalog">Available module versions keyed by <c>group:module</c>.</param> + /// <param name="alreadyLockedKeys">Set of <c>group:module@version</c> strings already locked (keeps yanked versions eligible).</param> + /// <param name="rlimit">Deterministic Z3 resource limit.</param> + /// <param name="timeoutMs">Wall-clock backstop timeout in milliseconds.</param> + public static LockDocument Resolve( + string tazelVersion, + string rootGroup, + string rootModule, + string rootVersion, + IReadOnlyList<LockRequest> requests, + IReadOnlyDictionary<string, IReadOnlyList<CandidateModuleVersion>> catalog, + IReadOnlySet<string> alreadyLockedKeys, + uint rlimit, + uint timeoutMs) + { + ArgumentNullException.ThrowIfNull(requests); + ArgumentNullException.ThrowIfNull(catalog); + ArgumentNullException.ThrowIfNull(alreadyLockedKeys); + + Z3Native.EnsureInitialized(); + + var orderedKeys = CollectCanonicalKeys(requests, catalog); + var eligible = FilterAndSortCandidates(orderedKeys, catalog, alreadyLockedKeys); + + var cfg = Z3Native.Z3_mk_config(); + Z3Native.Z3_set_param_value(cfg, "rlimit", rlimit.ToString(CultureInfo.InvariantCulture)); + Z3Native.Z3_set_param_value(cfg, "timeout", timeoutMs.ToString(CultureInfo.InvariantCulture)); + var ctx = Z3Native.Z3_mk_context(cfg); + Z3Native.Z3_del_config(cfg); + + try + { + var intSort = Z3Native.Z3_mk_int_sort(ctx); + var (selectedIndices, _) = SolveOptimal(ctx, intSort, orderedKeys, eligible, requests, rootGroup, rootModule); + var (modules, edges) = ExtractSelection(selectedIndices, orderedKeys, eligible, requests, rootGroup, rootModule); + CheckForCycles(rootGroup, rootModule, edges); + return new LockDocument(tazelVersion, rootGroup, rootModule, rootVersion, requests, modules, edges); + } + finally + { + Z3Native.Z3_del_context(ctx); + } + } + + private static List<string> CollectCanonicalKeys( + IReadOnlyList<LockRequest> requests, + IReadOnlyDictionary<string, IReadOnlyList<CandidateModuleVersion>> catalog) + { + var keys = new HashSet<string>(catalog.Keys, StringComparer.Ordinal); + foreach (var req in requests) + { + keys.Add(req.Key); + } + + foreach (var list in catalog.Values) + { + foreach (var cand in list) + { + foreach (var edge in cand.Dependencies) + { + keys.Add($"{edge.ToGroup}:{edge.ToModule}"); + } + } + } + + return [.. keys.OrderBy(k => k, StringComparer.Ordinal)]; + } + + private static Dictionary<string, List<CandidateModuleVersion>> FilterAndSortCandidates( + List<string> orderedKeys, + IReadOnlyDictionary<string, IReadOnlyList<CandidateModuleVersion>> catalog, + IReadOnlySet<string> alreadyLockedKeys) + { + var result = new Dictionary<string, List<CandidateModuleVersion>>(StringComparer.Ordinal); + foreach (var key in orderedKeys) + { + if (!catalog.TryGetValue(key, out var raw)) + { + result[key] = []; + continue; + } + + var usable = raw + .Where(c => !c.Yanked || alreadyLockedKeys.Contains($"{c.Key}@{c.Version.ToNormalizedString()}")) + .OrderBy(c => c.Version) + .ToList(); + result[key] = usable; + } + + return result; + } + + private sealed record TrackedConstraint(string Label, IntPtr Formula); + + private static (Dictionary<string, int> Selection, Dictionary<string, IntPtr> Vars) SolveOptimal( + IntPtr ctx, + IntPtr intSort, + List<string> orderedKeys, + Dictionary<string, List<CandidateModuleVersion>> eligible, + IReadOnlyList<LockRequest> requests, + string rootGroup, + string rootModule) + { + var vars = CreateVariables(ctx, intSort, orderedKeys); + var opt = Z3Native.Z3_mk_optimize(ctx); + Z3Native.Z3_optimize_inc_ref(ctx, opt); + try + { + var constraints = BuildConstraints(ctx, intSort, orderedKeys, eligible, vars, requests, rootGroup, rootModule); + AddDomainBounds(ctx, intSort, opt, orderedKeys, eligible, vars); + foreach (var c in constraints) + { + Z3Native.Z3_optimize_assert(ctx, opt, c.Formula); + } + + AddObjectives(ctx, intSort, opt, orderedKeys, vars); + var status = Z3Native.Z3_optimize_check(ctx, opt, 0, null); + if (status == Z3Native.LTrue) + { + return (EvaluateSelection(ctx, opt, orderedKeys, vars), vars); + } + + if (status == Z3Native.LUndef) + { + throw new ResolutionException( + "Z3 dependency resolution reached its resource or time limit; try narrowing dependency version ranges."); + } + + var conflicts = ComputeMinimalConflictCore(ctx, intSort, orderedKeys, eligible, vars, constraints); + var detail = string.Join("; ", conflicts); + throw new ResolutionException($"dependency resolution failed (a minimal set of conflicting requests): {detail}", conflicts); + } + finally + { + Z3Native.Z3_optimize_dec_ref(ctx, opt); + } + } + + private static Dictionary<string, int> EvaluateSelection( + IntPtr ctx, IntPtr opt, List<string> orderedKeys, Dictionary<string, IntPtr> vars) + { + var model = Z3Native.Z3_optimize_get_model(ctx, opt); + Z3Native.Z3_model_inc_ref(ctx, model); + try + { + var selection = new Dictionary<string, int>(StringComparer.Ordinal); + foreach (var key in orderedKeys) + { + var value = 0; + var ok = Z3Native.Z3_model_eval(ctx, model, vars[key], modelCompletion: true, out var evaluated) + && Z3Native.Z3_get_numeral_int(ctx, evaluated, out value); + selection[key] = ok ? value : 0; + } + + return selection; + } + finally + { + Z3Native.Z3_model_dec_ref(ctx, model); + } + } + + private static Dictionary<string, IntPtr> CreateVariables(IntPtr ctx, IntPtr intSort, List<string> orderedKeys) + { + var vars = new Dictionary<string, IntPtr>(StringComparer.Ordinal); + for (var i = 0; i < orderedKeys.Count; i++) + { + var sym = Z3Native.Z3_mk_string_symbol(ctx, $"m_{i}"); + vars[orderedKeys[i]] = Z3Native.Z3_mk_const(ctx, sym, intSort); + } + + return vars; + } + + private static void AddDomainBounds( + IntPtr ctx, IntPtr intSort, IntPtr opt, List<string> orderedKeys, + Dictionary<string, List<CandidateModuleVersion>> eligible, Dictionary<string, IntPtr> vars) + { + var zero = Z3Native.Z3_mk_int(ctx, 0, intSort); + foreach (var key in orderedKeys) + { + var max = Z3Native.Z3_mk_int(ctx, eligible[key].Count, intSort); + Z3Native.Z3_optimize_assert(ctx, opt, Z3Native.Z3_mk_ge(ctx, vars[key], zero)); + Z3Native.Z3_optimize_assert(ctx, opt, Z3Native.Z3_mk_le(ctx, vars[key], max)); + } + } + + private static void AddObjectives(IntPtr ctx, IntPtr intSort, IntPtr opt, List<string> orderedKeys, Dictionary<string, IntPtr> vars) + { + if (orderedKeys.Count == 0) + { + return; + } + + var zero = Z3Native.Z3_mk_int(ctx, 0, intSort); + var one = Z3Native.Z3_mk_int(ctx, 1, intSort); + var indicators = orderedKeys + .Select(k => Z3Native.Z3_mk_ite(ctx, Z3Native.Z3_mk_gt(ctx, vars[k], zero), one, zero)) + .ToArray(); + var sum = indicators.Length == 1 + ? indicators[0] + : Z3Native.Z3_mk_add(ctx, (uint)indicators.Length, indicators); + Z3Native.Z3_optimize_minimize(ctx, opt, sum); + + foreach (var key in orderedKeys) + { + Z3Native.Z3_optimize_maximize(ctx, opt, vars[key]); + } + } + + private static List<TrackedConstraint> BuildConstraints( + IntPtr ctx, + IntPtr intSort, + List<string> orderedKeys, + Dictionary<string, List<CandidateModuleVersion>> eligible, + Dictionary<string, IntPtr> vars, + IReadOnlyList<LockRequest> requests, + string rootGroup, + string rootModule) + { + var list = new List<TrackedConstraint>(); + var rootLabel = $"{rootGroup}:{rootModule}"; + + foreach (var req in requests.OrderBy(r => r.Key, StringComparer.Ordinal)) + { + var match = BuildRangeMatch(ctx, intSort, vars[req.Key], eligible[req.Key], req.VersionRange); + list.Add(new TrackedConstraint($"{rootLabel} -> {req.Key} {req.VersionRange}", match)); + } + + foreach (var key in orderedKeys) + { + var candidates = eligible[key]; + for (var idx = 0; idx < candidates.Count; idx++) + { + var cand = candidates[idx]; + var isSelected = Z3Native.Z3_mk_eq(ctx, vars[key], Z3Native.Z3_mk_int(ctx, idx + 1, intSort)); + foreach (var edge in cand.Dependencies.OrderBy(e => $"{e.ToGroup}:{e.ToModule}", StringComparer.Ordinal)) + { + var targetKey = $"{edge.ToGroup}:{edge.ToModule}"; + var match = BuildRangeMatch(ctx, intSort, vars[targetKey], eligible[targetKey], edge.VersionRange); + var label = $"{key}@{cand.Version.ToNormalizedString()} -> {targetKey} {edge.VersionRange}"; + list.Add(new TrackedConstraint(label, Z3Native.Z3_mk_implies(ctx, isSelected, match))); + } + } + } + + return list; + } + + private static IntPtr BuildRangeMatch( + IntPtr ctx, IntPtr intSort, IntPtr targetVar, List<CandidateModuleVersion> candidates, string rangeText) + { + var range = ParseRange(rangeText); + var options = new List<IntPtr>(); + for (var idx = 0; idx < candidates.Count; idx++) + { + if (range.Satisfies(candidates[idx].Version)) + { + options.Add(Z3Native.Z3_mk_eq(ctx, targetVar, Z3Native.Z3_mk_int(ctx, idx + 1, intSort))); + } + } + + return options.Count switch + { + 0 => Z3Native.Z3_mk_false(ctx), + 1 => options[0], + _ => Z3Native.Z3_mk_or(ctx, (uint)options.Count, [.. options]), + }; + } + + private static VersionRange ParseRange(string rangeText) + { + if (NuGetVersion.TryParseStrict(rangeText, out var exact)) + { + return new VersionRange(exact, includeMinVersion: true, exact, includeMaxVersion: true); + } + + if (VersionRange.TryParse(rangeText, out var parsed)) + { + return parsed; + } + + throw new ResolutionException($"invalid SemVer version or range '{rangeText}'"); + } + + private static List<string> ComputeMinimalConflictCore( + IntPtr ctx, + IntPtr intSort, + List<string> orderedKeys, + Dictionary<string, List<CandidateModuleVersion>> eligible, + Dictionary<string, IntPtr> vars, + List<TrackedConstraint> constraints) + { + var solver = Z3Native.Z3_mk_solver(ctx); + Z3Native.Z3_solver_inc_ref(ctx, solver); + try + { + ConfigureCoreMinimize(ctx, solver); + AssertSolverDomainBounds(ctx, intSort, solver, orderedKeys, eligible, vars); + var assumptions = AssertGuardedConstraints(ctx, solver, constraints); + + var allGuards = assumptions.Select(a => a.Guard).ToArray(); + if (Z3Native.Z3_solver_check_assumptions(ctx, solver, (uint)allGuards.Length, allGuards) != Z3Native.LFalse) + { + return constraints.Select(c => c.Label).ToList(); + } + + var coreSet = ReadUnsatCoreHandles(ctx, solver); + var active = assumptions.Where(a => coreSet.Contains(a.Guard)).ToList(); + MinimizeByDeletion(ctx, solver, active); + return active.Select(a => a.Constraint.Label).ToList(); + } + finally + { + Z3Native.Z3_solver_dec_ref(ctx, solver); + } + } + + private static void ConfigureCoreMinimize(IntPtr ctx, IntPtr solver) + { + var p = Z3Native.Z3_mk_params(ctx); + Z3Native.Z3_params_inc_ref(ctx, p); + try + { + Z3Native.Z3_params_set_bool(ctx, p, Z3Native.Z3_mk_string_symbol(ctx, "core.minimize"), true); + Z3Native.Z3_solver_set_params(ctx, solver, p); + } + finally + { + Z3Native.Z3_params_dec_ref(ctx, p); + } + } + + private static void AssertSolverDomainBounds( + IntPtr ctx, IntPtr intSort, IntPtr solver, List<string> orderedKeys, + Dictionary<string, List<CandidateModuleVersion>> eligible, Dictionary<string, IntPtr> vars) + { + var zero = Z3Native.Z3_mk_int(ctx, 0, intSort); + foreach (var key in orderedKeys) + { + Z3Native.Z3_solver_assert(ctx, solver, Z3Native.Z3_mk_ge(ctx, vars[key], zero)); + Z3Native.Z3_solver_assert(ctx, solver, Z3Native.Z3_mk_le(ctx, vars[key], Z3Native.Z3_mk_int(ctx, eligible[key].Count, intSort))); + } + } + + private static List<(IntPtr Guard, TrackedConstraint Constraint)> AssertGuardedConstraints( + IntPtr ctx, IntPtr solver, List<TrackedConstraint> constraints) + { + var boolSort = Z3Native.Z3_mk_bool_sort(ctx); + var assumptions = new List<(IntPtr Guard, TrackedConstraint Constraint)>(constraints.Count); + for (var i = 0; i < constraints.Count; i++) + { + var guard = Z3Native.Z3_mk_const(ctx, Z3Native.Z3_mk_string_symbol(ctx, $"req_{i}"), boolSort); + Z3Native.Z3_solver_assert(ctx, solver, Z3Native.Z3_mk_implies(ctx, guard, constraints[i].Formula)); + assumptions.Add((guard, constraints[i])); + } + + return assumptions; + } + + private static HashSet<IntPtr> ReadUnsatCoreHandles(IntPtr ctx, IntPtr solver) + { + var coreVec = Z3Native.Z3_solver_get_unsat_core(ctx, solver); + Z3Native.Z3_ast_vector_inc_ref(ctx, coreVec); + try + { + var count = Z3Native.Z3_ast_vector_size(ctx, coreVec); + var coreSet = new HashSet<IntPtr>(); + for (uint i = 0; i < count; i++) + { + coreSet.Add(Z3Native.Z3_ast_vector_get(ctx, coreVec, i)); + } + + return coreSet; + } + finally + { + Z3Native.Z3_ast_vector_dec_ref(ctx, coreVec); + } + } + + private static void MinimizeByDeletion(IntPtr ctx, IntPtr solver, List<(IntPtr Guard, TrackedConstraint Constraint)> active) + { + for (var i = active.Count - 1; i >= 0; i--) + { + var trial = active.Where((_, idx) => idx != i).Select(a => a.Guard).ToArray(); + if (Z3Native.Z3_solver_check_assumptions(ctx, solver, (uint)trial.Length, trial) == Z3Native.LFalse) + { + active.RemoveAt(i); + } + } + } + + private static (List<LockModule> Modules, List<LockEdge> Edges) ExtractSelection( + Dictionary<string, int> selection, + List<string> orderedKeys, + Dictionary<string, List<CandidateModuleVersion>> eligible, + IReadOnlyList<LockRequest> requests, + string rootGroup, + string rootModule) + { + var aliasByKey = requests.ToDictionary(r => r.Key, r => r.Alias, StringComparer.Ordinal); + var modules = new List<LockModule>(); + var edges = new List<LockEdge>(); + + foreach (var req in requests) + { + edges.Add(new LockEdge(rootGroup, rootModule, req.Group, req.Module, req.VersionRange)); + } + + foreach (var key in orderedKeys) + { + var val = selection[key]; + if (val <= 0) + { + continue; + } + + var chosen = eligible[key][val - 1]; + aliasByKey.TryGetValue(key, out var alias); + modules.Add(new LockModule( + chosen.Group, chosen.Module, chosen.Version.ToNormalizedString(), alias, + chosen.SourceKind, chosen.Registry, chosen.ArchiveSha256, chosen.ManifestSha256, chosen.LocalPath)); + edges.AddRange(chosen.Dependencies); + } + + return (modules, edges); + } + + private static void CheckForCycles(string rootGroup, string rootModule, List<LockEdge> edges) + { + var adj = new Dictionary<string, List<string>>(StringComparer.Ordinal); + foreach (var e in edges) + { + var from = $"{e.FromGroup}:{e.FromModule}"; + var to = $"{e.ToGroup}:{e.ToModule}"; + if (!adj.TryGetValue(from, out var list)) + { + list = []; + adj[from] = list; + } + + list.Add(to); + } + + var state = new Dictionary<string, int>(StringComparer.Ordinal); + var stack = new List<string>(); + var root = $"{rootGroup}:{rootModule}"; + DfsCycle(root, adj, state, stack); + } + + private static void DfsCycle( + string node, Dictionary<string, List<string>> adj, Dictionary<string, int> state, List<string> stack) + { + state[node] = 1; + stack.Add(node); + if (adj.TryGetValue(node, out var neighbors)) + { + foreach (var next in neighbors) + { + var nextState = state.GetValueOrDefault(next, 0); + if (nextState == 1) + { + var startIdx = stack.IndexOf(next); + var chain = string.Join(" -> ", stack.Skip(startIdx).Append(next)); + throw new ResolutionException($"module dependency cycle detected: {chain}"); + } + + if (nextState == 0) + { + DfsCycle(next, adj, state, stack); + } + } + } + + stack.RemoveAt(stack.Count - 1); + state[node] = 2; + } +} diff --git a/src/Progmasoft.Tazel/Lock/Z3NativeLibrary.cs b/src/Progmasoft.Tazel/Lock/Z3NativeLibrary.cs new file mode 100644 index 0000000..ae28132 --- /dev/null +++ b/src/Progmasoft.Tazel/Lock/Z3NativeLibrary.cs @@ -0,0 +1,219 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Threading; + +namespace Progmasoft.Tazel.Lock; + +/// <summary> +/// Registers a <see cref="NativeLibrary"/> fallback resolver for <c>libz3</c> and exposes the minimal architecture-independent +/// Z3 C API bindings required by <see cref="Z3ModuleResolver"/> (works on x64 and arm64 across Linux, macOS, Windows, and BSDs). +/// </summary> +internal static class Z3Native +{ + internal const int LFalse = -1; + internal const int LUndef = 0; + internal const int LTrue = 1; + + private static int _initialized; + + private static readonly string[] LinuxAndBsdCandidates = + [ + "libz3.so.4", + "libz3.so", + "/usr/lib/x86_64-linux-gnu/libz3.so.4", + "/usr/lib/aarch64-linux-gnu/libz3.so.4", + "/usr/lib/libz3.so.4", + "/usr/lib/libz3.so", + "/usr/local/lib/libz3.so", + ]; + + private static readonly string[] MacOsCandidates = + [ + "/opt/homebrew/lib/libz3.dylib", + "/usr/local/lib/libz3.dylib", + "libz3.dylib", + ]; + + internal static void EnsureInitialized() + { + if (Interlocked.Exchange(ref _initialized, 1) != 0) + { + return; + } + + NativeLibrary.SetDllImportResolver(typeof(Z3Native).Assembly, Resolve); + } + + private static IntPtr Resolve(string libraryName, Assembly assembly, DllImportSearchPath? searchPath) + { + if (!libraryName.Contains("z3", StringComparison.OrdinalIgnoreCase)) + { + return IntPtr.Zero; + } + + if (NativeLibrary.TryLoad(libraryName, assembly, searchPath, out var handle)) + { + return handle; + } + + var candidates = OperatingSystem.IsMacOS() + ? MacOsCandidates + : OperatingSystem.IsWindows() + ? Array.Empty<string>() + : LinuxAndBsdCandidates; + + foreach (var candidate in candidates) + { + if (NativeLibrary.TryLoad(candidate, out handle)) + { + return handle; + } + } + + return IntPtr.Zero; + } + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] + internal static extern IntPtr Z3_mk_config(); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] + internal static extern void Z3_del_config(IntPtr c); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] + internal static extern void Z3_set_param_value(IntPtr c, [MarshalAs(UnmanagedType.LPUTF8Str)] string paramId, [MarshalAs(UnmanagedType.LPUTF8Str)] string paramValue); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + internal static extern IntPtr Z3_mk_context(IntPtr c); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + internal static extern void Z3_del_context(IntPtr c); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + internal static extern IntPtr Z3_mk_int_sort(IntPtr c); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + internal static extern IntPtr Z3_mk_bool_sort(IntPtr c); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + internal static extern IntPtr Z3_mk_string_symbol(IntPtr c, [MarshalAs(UnmanagedType.LPUTF8Str)] string s); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + internal static extern IntPtr Z3_mk_const(IntPtr c, IntPtr sym, IntPtr sort); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + internal static extern IntPtr Z3_mk_int(IntPtr c, int v, IntPtr sort); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + internal static extern IntPtr Z3_mk_false(IntPtr c); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + internal static extern IntPtr Z3_mk_eq(IntPtr c, IntPtr l, IntPtr r); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + internal static extern IntPtr Z3_mk_ge(IntPtr c, IntPtr t1, IntPtr t2); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + internal static extern IntPtr Z3_mk_le(IntPtr c, IntPtr t1, IntPtr t2); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + internal static extern IntPtr Z3_mk_gt(IntPtr c, IntPtr t1, IntPtr t2); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + internal static extern IntPtr Z3_mk_ite(IntPtr c, IntPtr t1, IntPtr t2, IntPtr t3); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + internal static extern IntPtr Z3_mk_implies(IntPtr c, IntPtr t1, IntPtr t2); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + internal static extern IntPtr Z3_mk_add(IntPtr c, uint numArgs, IntPtr[] args); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + internal static extern IntPtr Z3_mk_or(IntPtr c, uint numArgs, IntPtr[] args); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + internal static extern IntPtr Z3_mk_optimize(IntPtr c); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + internal static extern void Z3_optimize_inc_ref(IntPtr c, IntPtr o); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + internal static extern void Z3_optimize_dec_ref(IntPtr c, IntPtr o); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + internal static extern void Z3_optimize_assert(IntPtr c, IntPtr o, IntPtr a); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + internal static extern uint Z3_optimize_minimize(IntPtr c, IntPtr o, IntPtr t); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + internal static extern uint Z3_optimize_maximize(IntPtr c, IntPtr o, IntPtr t); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + internal static extern int Z3_optimize_check(IntPtr c, IntPtr o, uint numAssumptions, IntPtr[]? assumptions); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + internal static extern IntPtr Z3_optimize_get_model(IntPtr c, IntPtr o); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + internal static extern void Z3_model_inc_ref(IntPtr c, IntPtr m); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + internal static extern void Z3_model_dec_ref(IntPtr c, IntPtr m); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + [return: MarshalAs(UnmanagedType.I1)] + internal static extern bool Z3_model_eval(IntPtr c, IntPtr m, IntPtr t, [MarshalAs(UnmanagedType.I1)] bool modelCompletion, out IntPtr v); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + [return: MarshalAs(UnmanagedType.I1)] + internal static extern bool Z3_get_numeral_int(IntPtr c, IntPtr v, out int i); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + internal static extern IntPtr Z3_mk_solver(IntPtr c); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + internal static extern void Z3_solver_inc_ref(IntPtr c, IntPtr s); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + internal static extern void Z3_solver_dec_ref(IntPtr c, IntPtr s); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + internal static extern IntPtr Z3_mk_params(IntPtr c); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + internal static extern void Z3_params_inc_ref(IntPtr c, IntPtr p); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + internal static extern void Z3_params_dec_ref(IntPtr c, IntPtr p); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + internal static extern void Z3_params_set_bool(IntPtr c, IntPtr p, IntPtr k, [MarshalAs(UnmanagedType.I1)] bool v); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + internal static extern void Z3_solver_set_params(IntPtr c, IntPtr s, IntPtr p); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + internal static extern void Z3_solver_assert(IntPtr c, IntPtr s, IntPtr a); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + internal static extern int Z3_solver_check_assumptions(IntPtr c, IntPtr s, uint numAssumptions, IntPtr[] assumptions); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + internal static extern IntPtr Z3_solver_get_unsat_core(IntPtr c, IntPtr s); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + internal static extern void Z3_ast_vector_inc_ref(IntPtr c, IntPtr v); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + internal static extern void Z3_ast_vector_dec_ref(IntPtr c, IntPtr v); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + internal static extern uint Z3_ast_vector_size(IntPtr c, IntPtr v); + + [DllImport("libz3", CallingConvention = CallingConvention.Cdecl)] + internal static extern IntPtr Z3_ast_vector_get(IntPtr c, IntPtr v, uint i); +} diff --git a/src/Progmasoft.Tazel/Progmasoft.Tazel.csproj b/src/Progmasoft.Tazel/Progmasoft.Tazel.csproj index 7365ff1..51571d1 100644 --- a/src/Progmasoft.Tazel/Progmasoft.Tazel.csproj +++ b/src/Progmasoft.Tazel/Progmasoft.Tazel.csproj @@ -24,6 +24,8 @@ <PackageReference Include="Lzma.Net" /> <PackageReference Include="BouncyCastle.Cryptography" /> <PackageReference Include="Microsoft.Data.Sqlite" /> + <!-- Exclude x64-only managed Microsoft.Z3.dll (breaks ARM64); keep build assets for Windows libz3.dll. --> + <PackageReference Include="Microsoft.Z3" ExcludeAssets="compile;runtime" /> </ItemGroup> <ItemGroup> <ProjectReference Include="../Progmasoft.Tazel.Packaging/Progmasoft.Tazel.Packaging.csproj" /> diff --git a/tests/Progmasoft.Tazel.Tests/Z3ResolverTests.cs b/tests/Progmasoft.Tazel.Tests/Z3ResolverTests.cs new file mode 100644 index 0000000..ba41019 --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/Z3ResolverTests.cs @@ -0,0 +1,118 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using NuGet.Versioning; +using Progmasoft.Tazel.Lock; +using Xunit; + +namespace Progmasoft.Tazel.Tests; + +public sealed class Z3ResolverTests +{ + private static CandidateModuleVersion Cand( + string group, string module, string version, + IReadOnlyList<LockEdge>? deps = null, bool yanked = false) => + new(group, module, NuGetVersion.Parse(version), yanked, deps ?? [], + "registry", "portal-modules", $"sha-{module}-{version}", $"msha-{module}-{version}", null); + + [Fact] + public void ResolvesDiamondDeterministicallyRegardlessOfRequestOrder() + { + var catalog = new Dictionary<string, IReadOnlyList<CandidateModuleVersion>>(StringComparer.Ordinal) + { + ["com.a:a"] = + [ + Cand("com.a", "a", "1.0.0", [new LockEdge("com.a", "a", "com.c", "c", "[1.0.0, 2.0.0)")]), + ], + ["com.b:b"] = + [ + Cand("com.b", "b", "1.0.0", [new LockEdge("com.b", "b", "com.c", "c", "[1.2.0, 1.5.0)")]), + ], + ["com.c:c"] = + [ + Cand("com.c", "c", "1.0.0"), + Cand("com.c", "c", "1.4.0"), + Cand("com.c", "c", "2.0.0"), + ], + ["com.unused:stray"] = + [ + Cand("com.unused", "stray", "9.0.0"), + ], + }; + + var reqA = new LockRequest("com.a", "a", "1.0.0", null, "portal-modules"); + var reqB = new LockRequest("com.b", "b", "1.0.0", null, "portal-modules"); + + var doc1 = Z3ModuleResolver.Resolve("0.5.0", "com.root", "app", "0.1.0", [reqA, reqB], catalog); + var doc2 = Z3ModuleResolver.Resolve("0.5.0", "com.root", "app", "0.1.0", [reqB, reqA], catalog); + + Assert.Equal(Lockfile.ExportJson(doc1), Lockfile.ExportJson(doc2)); + Assert.Equal(3, doc1.Modules.Count); + Assert.DoesNotContain(doc1.Modules, m => m.Key == "com.unused:stray"); + Assert.Contains(doc1.Modules, m => m.Key == "com.c:c" && m.Version == "1.4.0"); + } + + [Fact] + public void ExcludesYankedVersionsUnlessAlreadyLocked() + { + var catalog = new Dictionary<string, IReadOnlyList<CandidateModuleVersion>>(StringComparer.Ordinal) + { + ["com.a:lib"] = + [ + Cand("com.a", "lib", "1.0.0"), + Cand("com.a", "lib", "1.1.0", yanked: true), + ], + }; + + var req = new LockRequest("com.a", "lib", "[1.0.0, 2.0.0)", null, "portal-modules"); + var fresh = Z3ModuleResolver.Resolve("0.5.0", "com.root", "app", "0.1.0", [req], catalog); + Assert.Single(fresh.Modules); + Assert.Equal("1.0.0", fresh.Modules[0].Version); + + var lockedAllow = new HashSet<string>(StringComparer.Ordinal) { "com.a:lib@1.1.0" }; + var kept = Z3ModuleResolver.Resolve("0.5.0", "com.root", "app", "0.1.0", [req], catalog, + lockedAllow, Z3ModuleResolver.DefaultResourceLimit, Z3ModuleResolver.DefaultTimeoutMilliseconds); + Assert.Equal("1.1.0", kept.Modules[0].Version); + } + + [Fact] + public void DetectsModuleCycles() + { + var catalog = new Dictionary<string, IReadOnlyList<CandidateModuleVersion>>(StringComparer.Ordinal) + { + ["com.a:a"] = [Cand("com.a", "a", "1.0.0", [new LockEdge("com.a", "a", "com.b", "b", "1.0.0")])], + ["com.b:b"] = [Cand("com.b", "b", "1.0.0", [new LockEdge("com.b", "b", "com.a", "a", "1.0.0")])], + }; + + var req = new LockRequest("com.a", "a", "1.0.0", null, "portal-modules"); + var ex = Assert.Throws<ResolutionException>(() => + Z3ModuleResolver.Resolve("0.5.0", "com.root", "app", "0.1.0", [req], catalog)); + Assert.Contains("cycle", ex.Message, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public void ReportsSubsetMinimalUnsatConflictCore() + { + var catalog = new Dictionary<string, IReadOnlyList<CandidateModuleVersion>>(StringComparer.Ordinal) + { + ["com.a:a"] = [Cand("com.a", "a", "1.0.0", [new LockEdge("com.a", "a", "com.c", "c", "[1.0.0, 2.0.0)")])], + ["com.b:b"] = [Cand("com.b", "b", "1.0.0", [new LockEdge("com.b", "b", "com.c", "c", "[2.0.0, 3.0.0)")])], + ["com.c:c"] = [Cand("com.c", "c", "1.0.0"), Cand("com.c", "c", "2.0.0")], + ["com.ok:ok"] = [Cand("com.ok", "ok", "1.0.0")], + }; + + var requests = new[] + { + new LockRequest("com.a", "a", "1.0.0", null, "portal-modules"), + new LockRequest("com.b", "b", "1.0.0", null, "portal-modules"), + new LockRequest("com.ok", "ok", "1.0.0", null, "portal-modules"), + }; + + var ex = Assert.Throws<ResolutionException>(() => + Z3ModuleResolver.Resolve("0.5.0", "com.root", "app", "0.1.0", requests, catalog)); + Assert.NotEmpty(ex.Conflicts); + Assert.DoesNotContain(ex.Conflicts, c => c.Contains("com.ok:ok", StringComparison.Ordinal)); + } +}