From 90dfa63ed2fd7eccb15f8bed8ef3dbd879fb8f58 Mon Sep 17 00:00:00 2001 From: Martijn Laarman Date: Thu, 19 Nov 2026 18:56:45 +0100 Subject: [PATCH] Make counter-examples and edge files safe on a shared constant base A Gen.Const base is one MockFileSystem, and axes run at the same time. FileWorld's name counter was not atomic and its file-system edits were unlocked, so two threads could create the same symlink; a given counter-example was applied once per axis. The counter is now atomic, draws lock the file system, and a counter-example given to AutoTest runs once per base under a lock on it. Co-Authored-By: Claude Sonnet 5.5 --- .../FileWorld.cs | 21 +++++++++- .../README.md | 1 + src/Nullean.Entities.CsCheck/AutoTest.cs | 39 ++++++++++++++++++- .../FileWorldTests.cs | 26 +++++++++++++ 4 files changed, 84 insertions(+), 3 deletions(-) diff --git a/src/Nullean.Entities.CsCheck.FileSystem/FileWorld.cs b/src/Nullean.Entities.CsCheck.FileSystem/FileWorld.cs index be5e330..bef8cc8 100644 --- a/src/Nullean.Entities.CsCheck.FileSystem/FileWorld.cs +++ b/src/Nullean.Entities.CsCheck.FileSystem/FileWorld.cs @@ -76,7 +76,7 @@ public FileWorld() : this(new MockFileSystem(), 0) /// A world over a file system a baseline value already has; names start high so they cannot replace the baseline's own files. public FileWorld(MockFileSystem fileSystem, int firstName = 10_000) { - _counter = Counters.GetValue(fileSystem, _ => new StrongBox(firstName)); + _counter = Counters.GetValue(fileSystem, _ => new StrongBox(firstName - 1)); FileSystem = fileSystem; Root = OperatingSystem.IsWindows() ? @"C:\docs" : "/docs"; Outside = OperatingSystem.IsWindows() ? @"C:\elsewhere" : "/elsewhere"; @@ -92,7 +92,7 @@ public FileWorld(MockFileSystem fileSystem, int firstName = 10_000) private string Combine(params string[] parts) => FileSystem.Path.Combine(parts); - private string NextName(PCG pcg) => $"{Words[(int)pcg.Next((uint)Words.Length)]}-{_counter.Value++}"; + private string NextName(PCG pcg) => $"{Words[(int)pcg.Next((uint)Words.Length)]}-{Interlocked.Increment(ref _counter.Value)}"; private string Folder(PCG pcg) { @@ -100,7 +100,16 @@ private string Folder(PCG pcg) return folder.Length == 0 ? Root : Combine(Root, folder.Replace('/', FileSystem.Path.DirectorySeparatorChar)); } + // Axes of one test run at the same time over a constant base, so its file system is shared: each draw changes it under a lock on it. public IFileInfo File(PCG pcg, FileKind kind) + { + lock (FileSystem) + { + return FileCore(pcg, kind); + } + } + + private IFileInfo FileCore(PCG pcg, FileKind kind) { var name = NextName(pcg); switch (kind) @@ -172,6 +181,14 @@ public IFileInfo File(PCG pcg, FileKind kind) } public IDirectoryInfo Directory(PCG pcg, DirectoryKind kind) + { + lock (FileSystem) + { + return DirectoryCore(pcg, kind); + } + } + + private IDirectoryInfo DirectoryCore(PCG pcg, DirectoryKind kind) { switch (kind) { diff --git a/src/Nullean.Entities.CsCheck.FileSystem/README.md b/src/Nullean.Entities.CsCheck.FileSystem/README.md index 9d44879..37285e3 100644 --- a/src/Nullean.Entities.CsCheck.FileSystem/README.md +++ b/src/Nullean.Entities.CsCheck.FileSystem/README.md @@ -86,6 +86,7 @@ where `valid` is one `Docset` whose files all satisfy the rules (for example, a - The root is `/docs` (`C:\docs` on Windows) and the outside folder is `/elsewhere` (`C:\elsewhere`). A rule that depends on other paths needs a hand-built baseline. - `MockFileSystem` is in-memory, so rules about permissions, locks or real disk behaviour are not exercised. - Rules whose counter-examples need a structure the generator cannot draw (for example a specific folder name your rule looks for) still need one written by hand. +- A `Gen.Const` base is one `MockFileSystem` shared by every axis, and axes run at the same time. A counter-example given to `AutoTest` runs once per base, under a lock on it, and later axes reuse the result; the file system is not cloned, so a counter-example should add files rather than edit the base's own. - It reaches the file-system members through AutoGen's reflection; do not reference it from an AOT-published app. ## Learn more diff --git a/src/Nullean.Entities.CsCheck/AutoTest.cs b/src/Nullean.Entities.CsCheck/AutoTest.cs index f076f35..2f22755 100644 --- a/src/Nullean.Entities.CsCheck/AutoTest.cs +++ b/src/Nullean.Entities.CsCheck/AutoTest.cs @@ -7,6 +7,7 @@ // exposes each axis as a named method. Report() runs every axis and records what each did; Run() does the same and throws when any failed; Cases lists the // axes the type actually declares, one per test, for a test framework's data source. An axis the type declares no rule for is reported, never passed in silence. +using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using CsCheck; @@ -198,7 +199,43 @@ private AutoTest( /// edge value where a single property breaks it alone; the others (sequential rules, Idempotent, cross-property rules) need one here, and axis 09 fails without it. /// public AutoTest CounterExamples(IReadOnlyDictionary> counterExamples) => - new(this, counterExamples: _counterExamples.Concat(counterExamples).GroupBy(kv => kv.Key).ToDictionary(g => g.Key, g => g.Last().Value)); + new( + this, + counterExamples: _counterExamples + .Concat(counterExamples.Select(kv => new KeyValuePair>(kv.Key, AppliedOncePerBase(kv.Value)))) + .GroupBy(kv => kv.Key) + .ToDictionary(g => g.Key, g => g.Last().Value) + ); + + /// + /// A constant generator (Gen.Const) hands every axis the same base object, and the axes run at the same time. A counter-example that changes the world its base holds + /// (adds a file to a MockFileSystem) would collide with itself, so it runs once per base, under a lock on that base; later applications get the value the first one made. + /// + private static Func AppliedOncePerBase(Func breakIt) + { + if (typeof(T).IsValueType) + { + return breakIt; + } + var made = new ConditionalWeakTable>(); + return value => + { + if (value is null) + { + return breakIt(value); + } + lock (value) + { + if (made.TryGetValue(value, out var box)) + { + return box.Value!; + } + var result = breakIt(value); + made.Add(value, new StrongBox(result)); + return result; + } + }; + } /// /// The counter-example for one rule, named by the rule itself rather than by a string: a rename cannot orphan it and a typo does not compile. diff --git a/tests/Nullean.Entities.CsCheck.FileSystem.Tests/FileWorldTests.cs b/tests/Nullean.Entities.CsCheck.FileSystem.Tests/FileWorldTests.cs index a8ac362..ac4fbfb 100644 --- a/tests/Nullean.Entities.CsCheck.FileSystem.Tests/FileWorldTests.cs +++ b/tests/Nullean.Entities.CsCheck.FileSystem.Tests/FileWorldTests.cs @@ -120,6 +120,32 @@ public void The_laws_hold_for_the_file_rules_with_counter_examples_built_in_the_ Rules.Laws(valid, examples).Results.Should().HaveCount(6); } + [Test] + public async Task A_counter_example_that_adds_a_file_survives_axes_running_at_once_on_one_constant_base() + { + // a Gen.Const base is one MockFileSystem; TUnit runs the Invariant and Vacancy cases at the same time, and both apply the counter-example to it + for (var attempt = 0; attempt < 30; attempt++) + { + var valid = Draw(AutoMode.Plausible, 40).First(d => d.Images.Count > 0); + var test = AutoTest + .For(Rules, Gen.Const(valid)) + .Options(o => o.UseFileSystem()) + .CounterExamples(new Dictionary> + { + ["ImagesAreNotSymlinks"] = d => + { + ((MockFileSystem)d.FileSystem).AddFile("/docs/real.png", "x"); + d.FileSystem.File.CreateSymbolicLink("/docs/link.png", "/docs/real.png"); + return d with { Images = [d.FileSystem.FileInfo.New("/docs/link.png")] }; + } + }); + + var results = await Task.WhenAll(Task.Run(test.InvariantAsync), Task.Run(test.VacancyAsync)); + + results.OfType().Select(f => f.ToString()).Should().BeEmpty(); + } + } + [Test] public void Without_UseFileSystem_the_error_says_which_package_and_call_to_use() {