From 8c0caeb22645c6a9ba59fe745ea8790abe1591a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Valentin=20Breu=C3=9F?= Date: Sun, 13 Sep 2026 13:58:34 +0200 Subject: [PATCH] chore: slice the mutation tests over parallel jobs The full run on `main` mutates the whole project and takes over two hours in a single job - long enough that the hosted runner was once reclaimed mid-run. Raising Stryker's concurrency changed nothing, because more test runners only contend for the same four vCPUs, so the remaining lever is more machines. Each slice mutates its own patterns minus those of every slice before it, and the last slice mutates whatever the others do not. Their union is the whole source by construction, so a file in a new folder falls into the last slice instead of quietly dropping out of the score. The dashboard job merges the slice reports back into the single report the upload expects, and refuses to publish when a slice is missing or two slices overlap. Pull requests still mutate only their own changes in a single job, so `ci.yml` is unchanged. --- .github/workflows/build.yml | 14 ++- Pipeline/Build.MutationTests.cs | 161 +++++++++++++++++++++++++++++++- 2 files changed, 170 insertions(+), 5 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 3af12af83a..98afabcd90 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -91,9 +91,15 @@ jobs: ./Artifacts/* mutation-tests-main: - name: "Mutation tests (aweXpect)" + name: "Mutation tests (aweXpect, ${{ matrix.slice }})" runs-on: ubuntu-latest - timeout-minutes: 150 + timeout-minutes: 60 + # The whole source is mutated on `main`, which takes more than two hours in a single job. The slices are + # disjoint and cover everything, so the dashboard job can merge their reports back into a single score. + strategy: + fail-fast: false + matrix: + slice: [ collections-enumerable, collections-other, numbers, dates, rest ] env: STRYKER_DASHBOARD_API_KEY: ${{ secrets.STRYKER_DASHBOARD_API_KEY }} DOTNET_NOLOGO: true @@ -108,11 +114,13 @@ jobs: 10.0.3xx - name: Run mutation tests run: ./build.sh MutationTestsMain + env: + MutationSlice: ${{ matrix.slice }} - name: Upload artifacts if: always() uses: actions/upload-artifact@v7 with: - name: MutationTestsMain + name: MutationTestsMain-${{ matrix.slice }} path: | ./Artifacts/* diff --git a/Pipeline/Build.MutationTests.cs b/Pipeline/Build.MutationTests.cs index 22b1abd344..ae5b0dc433 100644 --- a/Pipeline/Build.MutationTests.cs +++ b/Pipeline/Build.MutationTests.cs @@ -5,6 +5,8 @@ using System.Net.Http; using System.Net.Http.Headers; using System.Text; +using System.Text.Json.Nodes; +using System.Threading.Tasks; using Fallout.Common; using Fallout.Common.IO; using Fallout.Common.Tooling; @@ -23,6 +25,33 @@ namespace Build; partial class Build { private static bool DisableMutationTests = false; + + /// + /// Disjoint slices of the mutated source, so that the full run can be spread over parallel jobs. + /// + /// + /// A slice mutates its own patterns minus the patterns of every slice before it, and the last slice mutates + /// everything the others do not. The whole source is therefore covered by construction: a file in a new folder + /// falls into the last slice instead of silently dropping out of the score. + /// The patterns start with **/ because Stryker does not document what its globs are relative to, and end + /// in /*.cs because the subject folders are flat - a nested folder would fall into the last slice. + /// + private static readonly (string Name, string[] Patterns)[] MutationSlices = + [ + ("collections-enumerable", ["**/That/Collections/ThatEnumerable*.cs",]), + ("collections-other", ["**/That/Collections/*.cs",]), + ("numbers", ["**/That/Numbers/*.cs",]), + ("dates", + [ + "**/That/DateOnlys/*.cs", "**/That/DateTimeOffsets/*.cs", "**/That/DateTimes/*.cs", + "**/That/TimeOnlys/*.cs", "**/That/TimeSpans/*.cs", + ]), + ("rest", []), + ]; + + [Parameter("The slice of the source to mutate - when unset, the whole project is mutated")] + readonly string MutationSlice; + AbsolutePath StrykerOutputDirectory => ArtifactsDirectory / "Stryker"; AbsolutePath StrykerToolPath => TestResultsDirectory / "dotnet-stryker"; @@ -123,7 +152,7 @@ await gitHubClient.Issue.Comment.Update("Testably", "aweXpect", { ArtifactsDirectory.CreateDirectory(); await "MutationTestsCore".DownloadArtifactTo(ArtifactsDirectory / "aweXpect.Core", GithubToken); - await "MutationTestsMain".DownloadArtifactTo(ArtifactsDirectory / "aweXpect", GithubToken); + await DownloadMainMutationReport(); Dictionary projects; if (Repository.Branch != "main" && Repository.Tags.Count == 0) @@ -164,6 +193,98 @@ await client.PutAsync( } }); + /// + /// Collects the aweXpect mutation report into the single-report layout that the dashboard upload expects. + /// + /// + /// The full run is sliced over parallel jobs, so the slice reports have to be merged back together. Pull requests + /// mutate only their own changes and stay unsliced, which is why a single artifact is still accepted. + /// + private async Task DownloadMainMutationReport() + { + AbsolutePath projectDirectory = ArtifactsDirectory / "aweXpect"; + List<(string Name, AbsolutePath Report)> sliceReports = []; + foreach ((string name, string[] _) in MutationSlices) + { + AbsolutePath sliceDirectory = projectDirectory / name; + await $"MutationTestsMain-{name}".DownloadArtifactTo(sliceDirectory, GithubToken); + AbsolutePath report = sliceDirectory / "Stryker" / "reports" / "mutation-report.json"; + if (File.Exists(report)) + { + sliceReports.Add((name, report)); + } + } + + if (sliceReports.Count == 0) + { + Log.Information("Found no mutation slices, so the run was not sliced"); + await "MutationTestsMain".DownloadArtifactTo(projectDirectory, GithubToken); + return; + } + + if (sliceReports.Count != MutationSlices.Length) + { + // Publishing now would drop the mutants of the missing slices and report a score for a subset of the source. + Assert.Fail( + $"Only {sliceReports.Count} of {MutationSlices.Length} mutation slices reported: " + + $"{string.Join(", ", sliceReports.Select(slice => slice.Name))}"); + } + else + { + File.Copy(projectDirectory / sliceReports[0].Name / "BranchName.txt", + projectDirectory / "BranchName.txt", true); + MergeMutationReports(sliceReports, projectDirectory); + } + } + + /// + /// Merges the into a single mutation report, by combining their files. + /// + private static void MergeMutationReports(List<(string Name, AbsolutePath Report)> sliceReports, + AbsolutePath projectDirectory) + { + JsonObject merged = null; + JsonObject mergedFiles = new(); + int totalMutants = 0; + foreach ((string name, AbsolutePath report) in sliceReports) + { + JsonObject slice = JsonNode.Parse(File.ReadAllText(report))!.AsObject(); + merged ??= slice; + int sliceMutants = 0; + foreach (KeyValuePair file in slice["files"]!.AsObject()) + { + int mutants = file.Value?["mutants"]?.AsArray().Count ?? 0; + sliceMutants += mutants; + if (!mergedFiles.TryGetPropertyValue(file.Key, out JsonNode existing)) + { + mergedFiles[file.Key] = file.Value?.DeepClone(); + continue; + } + + if (mutants > 0 && existing?["mutants"]?.AsArray().Count > 0) + { + // Both slices mutated the file, so its mutants would be counted twice in the score. + Assert.Fail($"The mutation slices overlap in '{file.Key}'"); + } + else if (mutants > 0) + { + mergedFiles[file.Key] = file.Value?.DeepClone(); + } + } + + totalMutants += sliceMutants; + Log.Information("The slice '{Slice}' contributed {Mutants} mutants", name, sliceMutants); + } + + merged!["files"] = mergedFiles; + AbsolutePath mergedReport = projectDirectory / "Stryker" / "reports" / "mutation-report.json"; + mergedReport.Parent.CreateDirectory(); + File.WriteAllText(mergedReport, merged.ToJsonString()); + // Compare this against the mutant count of an unsliced run to verify that the slices still cover every file. + Log.Information("Merged {SliceCount} slices into {FileCount} files with {Mutants} mutants", + sliceReports.Count, mergedFiles.Count, totalMutants); + } + private void ExecuteMutationTest(Project project, Project[] testProjects) { AbsolutePath toolPath = TestResultsDirectory / "dotnet-stryker"; @@ -194,6 +315,16 @@ private void ExecuteMutationTest(Project project, Project[] testProjects) File.WriteAllText(ArtifactsDirectory / "BranchName.txt", branchName); + string mutateSection = ""; + if (!string.IsNullOrEmpty(MutationSlice)) + { + string[] patterns = GetMutatePatterns(MutationSlice); + Log.Information("Mutate the slice '{MutationSlice}': {Patterns}", MutationSlice, + string.Join(" ", patterns)); + mutateSection = $"\"mutate\": [\n\t\t\t{string.Join(",\n\t\t\t", + patterns.Select(pattern => $"\"{pattern}\""))}\n\t\t],\n\t\t"; + } + string configText = $$""" { "stryker-config": { @@ -215,7 +346,7 @@ private void ExecuteMutationTest(Project project, Project[] testProjects) ] }, "concurrency": {{Environment.ProcessorCount}}, - "mutation-level": "Advanced" + {{mutateSection}}"mutation-level": "Advanced" } } """; @@ -295,4 +426,30 @@ string CreateMutationCommentBody(string projectName) static string PathForJson(Project project) => $"\"{project.Path.ToString().Replace(@"\", @"\\")}\""; + + /// + /// The Stryker mutate patterns for the slice: its own patterns, minus the + /// patterns of every slice declared before it. + /// + /// + /// The last slice declares no patterns of its own, so it is left with nothing but exclusions - which Stryker + /// reads as "mutate every file that does not match one of them". + /// + static string[] GetMutatePatterns(string sliceName) + { + int index = Array.FindIndex(MutationSlices, slice => slice.Name == sliceName); + if (index < 0) + { + throw new ArgumentException( + $"Unknown mutation slice '{sliceName}'. Use one of: {string.Join(", ", MutationSlices.Select(slice => slice.Name))}", + nameof(sliceName)); + } + + return + [ + ..MutationSlices[index].Patterns, + ..MutationSlices.Take(index).SelectMany(slice => slice.Patterns) + .Select(pattern => "!" + pattern), + ]; + } }