From 6a37a8e9cc674f8b61ce7bc84c97603239cc84d5 Mon Sep 17 00:00:00 2001 From: Chrison Simtian Date: Tue, 30 Jun 2026 21:53:06 +1200 Subject: [PATCH 1/3] Reset per-run global state at the end of Execute (FT-1, cross-invocation leaks) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit BuildManager.Execute leaked process-global state across invocations, so a second build in the same process (tests, hosted/reentrant scenarios) inherited the first's residue: - Console.CancelKeyPress / ToolOptions.Created handlers were re-subscribed every call and never removed (accumulating); - the CancellationHandler list kept each run's Finish (capturing a stale build); - Logging.InMemorySink.Instance carried log events over; - ValueInjectionUtility's value cache and the NuGet/Npm tool-path resolver config persisted. Fix (non-breaking): the two global handlers are now held in locals and the finally undoes exactly what the run set — unsubscribes both, removes Finish from the cancellation list, and resets the carried-over state (InMemorySink.Clear, ValueInjectionUtility.ClearCache, NuGet/NpmToolPathResolver.Reset). Build creation moved ahead of the subscriptions so a failed `new T()` leaks nothing. Groundwork for the BuildContext foundation (FT-2). Full build + test suite green; reentrancy is verified by FT-9. --- src/Fallout.Build/Execution/BuildManager.cs | 21 +++++++++++++++++-- .../Execution/ValueInjectionUtility.cs | 3 +++ src/Fallout.Build/Logging.cs | 8 ++++++- src/Fallout.Tooling/NpmToolPathResolver.cs | 6 ++++++ src/Fallout.Tooling/NuGetToolPathResolver.cs | 9 ++++++++ 5 files changed, 44 insertions(+), 3 deletions(-) diff --git a/src/Fallout.Build/Execution/BuildManager.cs b/src/Fallout.Build/Execution/BuildManager.cs index 5925fceca..3fd62a459 100644 --- a/src/Fallout.Build/Execution/BuildManager.cs +++ b/src/Fallout.Build/Execution/BuildManager.cs @@ -8,6 +8,7 @@ using Fallout.Common.Tooling; using Fallout.Common.Utilities; using Fallout.Common.Utilities.Collections; +using Fallout.Common.ValueInjection; using Serilog; #pragma warning disable CA2255 @@ -38,11 +39,17 @@ public static int Execute(Expression>[] defaultTargetExpressi { Console.OutputEncoding = Encoding.UTF8; Console.InputEncoding = Encoding.UTF8; - Console.CancelKeyPress += (_, _) => s_cancellationHandlers.ForEach(x => x()); - ToolOptions.Created += (options, _) => VerbosityMapping.Apply((ToolOptions)options); var build = new T(); + // Hold the per-run global subscriptions in locals so the finally can undo exactly them — + // otherwise each Execute in the same process (tests, hosted scenarios) accumulates handlers. + // FT-1 / #306. + ConsoleCancelEventHandler onCancelKeyPress = (_, _) => s_cancellationHandlers.ForEach(x => x()); + EventHandler onToolOptionsCreated = (options, _) => VerbosityMapping.Apply((ToolOptions)options); + Console.CancelKeyPress += onCancelKeyPress; + ToolOptions.Created += onToolOptionsCreated; + try { Logging.Configure(build); @@ -88,6 +95,16 @@ public static int Execute(Expression>[] defaultTargetExpressi { Finish(); Log.CloseAndFlush(); + + // FT-1 (#306): undo this run's process-global state so a subsequent Execute in the same + // process starts clean — no accumulated handlers, no carried-over log events / caches / config. + CancellationHandler -= Finish; + Console.CancelKeyPress -= onCancelKeyPress; + ToolOptions.Created -= onToolOptionsCreated; + Logging.InMemorySink.Instance.Clear(); + ValueInjectionUtility.ClearCache(); + NuGetToolPathResolver.Reset(); + NpmToolPathResolver.Reset(); } void Finish() diff --git a/src/Fallout.Build/Execution/ValueInjectionUtility.cs b/src/Fallout.Build/Execution/ValueInjectionUtility.cs index 8d637a3e9..06e424523 100644 --- a/src/Fallout.Build/Execution/ValueInjectionUtility.cs +++ b/src/Fallout.Build/Execution/ValueInjectionUtility.cs @@ -12,6 +12,9 @@ internal static class ValueInjectionUtility { private static readonly Dictionary s_valueCache = new(); + /// Clears the per-run injected-value cache so a subsequent build in the same process re-injects. FT-1 / #306. + internal static void ClearCache() => s_valueCache.Clear(); + public static T TryGetValue(Expression> parameterExpression) where T : class { diff --git a/src/Fallout.Build/Logging.cs b/src/Fallout.Build/Logging.cs index 9d99f5052..139572a69 100644 --- a/src/Fallout.Build/Logging.cs +++ b/src/Fallout.Build/Logging.cs @@ -228,10 +228,16 @@ public void Emit(LogEvent logEvent) _logEvents.Add(logEvent); } - public void Dispose() + /// Drops accumulated events so a subsequent build in the same process starts clean. FT-1 / #306. + public void Clear() { _logEvents.Clear(); } + + public void Dispose() + { + Clear(); + } } internal class ExecutingTargetLogEventEnricher : ILogEventEnricher diff --git a/src/Fallout.Tooling/NpmToolPathResolver.cs b/src/Fallout.Tooling/NpmToolPathResolver.cs index d94f91d66..1ec405e29 100644 --- a/src/Fallout.Tooling/NpmToolPathResolver.cs +++ b/src/Fallout.Tooling/NpmToolPathResolver.cs @@ -8,6 +8,12 @@ public static class NpmToolPathResolver { public static AbsolutePath NpmPackageJsonFile; + /// Resets the per-run package.json location so a subsequent build in the same process starts from defaults. FT-1 / #306. + public static void Reset() + { + NpmPackageJsonFile = null; + } + public static string GetNpmExecutable(string npmExecutable) { Assert.FileExists(NpmPackageJsonFile); diff --git a/src/Fallout.Tooling/NuGetToolPathResolver.cs b/src/Fallout.Tooling/NuGetToolPathResolver.cs index 78e335480..6df96e92a 100644 --- a/src/Fallout.Tooling/NuGetToolPathResolver.cs +++ b/src/Fallout.Tooling/NuGetToolPathResolver.cs @@ -16,6 +16,15 @@ public static class NuGetToolPathResolver public static string NuGetAssetsConfigFile; public static string PaketPackagesConfigFile; + /// Resets the per-run package-location config so a subsequent build in the same process starts from defaults. FT-1 / #306. + public static void Reset() + { + EmbeddedPackagesDirectory = null; + NuGetPackagesConfigFile = null; + NuGetAssetsConfigFile = null; + PaketPackagesConfigFile = null; + } + public static string GetPackageExecutable(string packageId, string packageExecutable, string version = null, string framework = null) { Assert.True(packageId != null && packageExecutable != null); From 3ef9983c7045319f3343210a769097e8919f69d6 Mon Sep 17 00:00:00 2001 From: Chrison Simtian Date: Wed, 1 Jul 2026 13:51:30 +1200 Subject: [PATCH 2/3] Rename s_cancellationHandlers field to cancellationHandlers Drop the `s_` prefix on the private static field in BuildManager, per CSharpGuidelines AV1705 (no `_`/`m_`/`g_`/`s_` field prefixes) and AV1702 (camelCase private fields). Localized cleanup while we are in this file for FT-1; a repo-wide naming rule is handled separately. Co-Authored-By: Claude Opus 4.8 (1M context) --- src/Fallout.Build/Execution/BuildManager.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Fallout.Build/Execution/BuildManager.cs b/src/Fallout.Build/Execution/BuildManager.cs index 3fd62a459..eff09ba6c 100644 --- a/src/Fallout.Build/Execution/BuildManager.cs +++ b/src/Fallout.Build/Execution/BuildManager.cs @@ -18,12 +18,12 @@ internal static class BuildManager { private const int ErrorExitCode = -1; - private static readonly LinkedList s_cancellationHandlers = new(); + private static readonly LinkedList cancellationHandlers = new(); public static event Action CancellationHandler { - add => s_cancellationHandlers.AddFirst(value); - remove => s_cancellationHandlers.Remove(value); + add => cancellationHandlers.AddFirst(value); + remove => cancellationHandlers.Remove(value); } [ModuleInitializer] @@ -45,7 +45,7 @@ public static int Execute(Expression>[] defaultTargetExpressi // Hold the per-run global subscriptions in locals so the finally can undo exactly them — // otherwise each Execute in the same process (tests, hosted scenarios) accumulates handlers. // FT-1 / #306. - ConsoleCancelEventHandler onCancelKeyPress = (_, _) => s_cancellationHandlers.ForEach(x => x()); + ConsoleCancelEventHandler onCancelKeyPress = (_, _) => cancellationHandlers.ForEach(x => x()); EventHandler onToolOptionsCreated = (options, _) => VerbosityMapping.Apply((ToolOptions)options); Console.CancelKeyPress += onCancelKeyPress; ToolOptions.Created += onToolOptionsCreated; From e72d72b23c33bc13668e59e26d7df66c0a639015 Mon Sep 17 00:00:00 2001 From: Chrison Simtian Date: Tue, 7 Jul 2026 21:57:44 +1200 Subject: [PATCH 3/3] Cover the FT-1 per-run reset hooks with tests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds tests for the cross-invocation reset entry points BuildManager.Execute's finally now calls, so the leak-removal behaviour is pinned: - ToolPathResolverResetSpecs: NuGet/NpmToolPathResolver.Reset() null every package-location field. Shares the resolvers' static state with ToolTasksToolPathSpecs, so both sit in a non-parallelized collection. - InMemorySinkSpecs: InMemorySink.Clear() (and Dispose(), which delegates to it) drop accumulated events. - ValueInjectionUtilitySpecs: a value is cached on first read; ClearCache() forces re-injection — made observable with a counting injection attribute. The full reentrant Execute run stays with the FT-9 harness. Tooling.Specs 66, Build.Specs 108, all green. Co-Authored-By: Claude Opus 4.8 (1M context) --- .../Fallout.Build.Specs/InMemorySinkSpecs.cs | 67 ++++++++++++++++++ .../ValueInjectionUtilitySpecs.cs | 65 ++++++++++++++++++ .../ToolPathResolverResetSpecs.cs | 68 +++++++++++++++++++ .../ToolTasksToolPathSpecs.cs | 1 + 4 files changed, 201 insertions(+) create mode 100644 tests/Fallout.Build.Specs/InMemorySinkSpecs.cs create mode 100644 tests/Fallout.Build.Specs/ValueInjectionUtilitySpecs.cs create mode 100644 tests/Fallout.Tooling.Specs/ToolPathResolverResetSpecs.cs diff --git a/tests/Fallout.Build.Specs/InMemorySinkSpecs.cs b/tests/Fallout.Build.Specs/InMemorySinkSpecs.cs new file mode 100644 index 000000000..77723743b --- /dev/null +++ b/tests/Fallout.Build.Specs/InMemorySinkSpecs.cs @@ -0,0 +1,67 @@ +using System; +using FluentAssertions; +using Fallout.Common.Execution; +using Serilog.Events; +using Serilog.Parsing; +using Xunit; + +namespace Fallout.Common.Specs; + +/// +/// Covers 's reset added in FT-1 / #306. The sink is a +/// process-wide singleton, so BuildManager.Execute's finally calls Clear() to +/// stop one run's warnings/errors bleeding into the next build in the same process; Dispose() +/// delegates to the same reset. +/// +public class InMemorySinkSpecs +{ + private static readonly Logging.InMemorySink Sink = Logging.InMemorySink.Instance; + + public InMemorySinkSpecs() + { + // Normalize the shared singleton before each case — prior runs (or a real logging pipeline) + // may have left events behind. + Sink.Clear(); + } + + [Fact] + public void Clear_drops_accumulated_events() + { + Sink.Emit(CreateLogEvent("first")); + Sink.Emit(CreateLogEvent("second")); + Sink.LogEvents.Should().HaveCount(2); + + Sink.Clear(); + + Sink.LogEvents.Should().BeEmpty(); + } + + [Fact] + public void Dispose_drops_accumulated_events() + { + Sink.Emit(CreateLogEvent("only")); + Sink.LogEvents.Should().ContainSingle(); + + Sink.Dispose(); + + Sink.LogEvents.Should().BeEmpty(); + } + + [Fact] + public void Clear_on_an_empty_sink_is_a_no_op() + { + Sink.LogEvents.Should().BeEmpty(); + + Sink.Clear(); + + Sink.LogEvents.Should().BeEmpty(); + } + + private static LogEvent CreateLogEvent(string message) => + new( + timestamp: DateTimeOffset.UnixEpoch, + level: LogEventLevel.Warning, + exception: null, + messageTemplate: new MessageTemplateParser().Parse(message), + properties: Array.Empty()); +} diff --git a/tests/Fallout.Build.Specs/ValueInjectionUtilitySpecs.cs b/tests/Fallout.Build.Specs/ValueInjectionUtilitySpecs.cs new file mode 100644 index 000000000..f84480d12 --- /dev/null +++ b/tests/Fallout.Build.Specs/ValueInjectionUtilitySpecs.cs @@ -0,0 +1,65 @@ +using System.Reflection; +using FluentAssertions; +using Fallout.Common.ValueInjection; +using Xunit; + +namespace Fallout.Common.Specs; + +/// +/// Covers added in FT-1 / #306. The injected-value +/// cache is keyed by member and lives for the process, so BuildManager.Execute's finally +/// clears it — otherwise a second build in the same process would re-serve the first run's injected +/// values instead of re-computing them. +/// +/// A counting attribute makes the cache observable: the injected value is the running call count, so +/// a cached read repeats the previous value while a post-ClearCache read re-injects a fresh one. +/// +public class ValueInjectionUtilitySpecs +{ + [Fact] + public void Value_is_cached_after_the_first_injection() + { + ValueInjectionUtility.ClearCache(); + CountingInjectionAttribute.Reset(); + var subject = new Subject(); + + var first = ValueInjectionUtility.TryGetValue(() => subject.Value); + var second = ValueInjectionUtility.TryGetValue(() => subject.Value); + + first.Should().Be("1"); + second.Should().Be("1", "the second read is served from the cache, not re-injected"); + CountingInjectionAttribute.Invocations.Should().Be(1); + } + + [Fact] + public void ClearCache_forces_re_injection_on_the_next_read() + { + ValueInjectionUtility.ClearCache(); + CountingInjectionAttribute.Reset(); + var subject = new Subject(); + + var first = ValueInjectionUtility.TryGetValue(() => subject.Value); + + ValueInjectionUtility.ClearCache(); + var afterClear = ValueInjectionUtility.TryGetValue(() => subject.Value); + + first.Should().Be("1"); + afterClear.Should().Be("2", "clearing the cache re-runs the injection"); + CountingInjectionAttribute.Invocations.Should().Be(2); + } + + private sealed class Subject + { + [CountingInjection] + public string Value; + } + + private sealed class CountingInjectionAttribute : ValueInjectionAttributeBase + { + public static int Invocations { get; private set; } + + public static void Reset() => Invocations = 0; + + public override object GetValue(MemberInfo member, object instance) => (++Invocations).ToString(); + } +} diff --git a/tests/Fallout.Tooling.Specs/ToolPathResolverResetSpecs.cs b/tests/Fallout.Tooling.Specs/ToolPathResolverResetSpecs.cs new file mode 100644 index 000000000..57813aae0 --- /dev/null +++ b/tests/Fallout.Tooling.Specs/ToolPathResolverResetSpecs.cs @@ -0,0 +1,68 @@ +using System; +using FluentAssertions; +using Fallout.Common.IO; +using Fallout.Common.Tooling; +using Xunit; + +namespace Fallout.Common.Specs; + +/// +/// Covers the per-run Reset() hooks added in FT-1 / #306: 's +/// finally calls these so a subsequent build in the same process starts from default +/// package-location config instead of inheriting the previous run's residue. +/// +/// Shares the resolvers' process-global static fields with , +/// so both classes live in a non-parallelized collection — otherwise a concurrent test could +/// observe a field mid-reset. +/// +[Collection(ToolPathResolverStateCollection.Name)] +public class ToolPathResolverResetSpecs : IDisposable +{ + private readonly string _embeddedPackagesDirectory = NuGetToolPathResolver.EmbeddedPackagesDirectory; + private readonly string _nuGetPackagesConfigFile = NuGetToolPathResolver.NuGetPackagesConfigFile; + private readonly string _nuGetAssetsConfigFile = NuGetToolPathResolver.NuGetAssetsConfigFile; + private readonly string _paketPackagesConfigFile = NuGetToolPathResolver.PaketPackagesConfigFile; + private readonly AbsolutePath _npmPackageJsonFile = NpmToolPathResolver.NpmPackageJsonFile; + + [Fact] + public void NuGetToolPathResolver_Reset_clears_every_package_location_field() + { + NuGetToolPathResolver.EmbeddedPackagesDirectory = "/packages"; + NuGetToolPathResolver.NuGetPackagesConfigFile = "/packages.config"; + NuGetToolPathResolver.NuGetAssetsConfigFile = "/project.assets.json"; + NuGetToolPathResolver.PaketPackagesConfigFile = "/paket.dependencies"; + + NuGetToolPathResolver.Reset(); + + NuGetToolPathResolver.EmbeddedPackagesDirectory.Should().BeNull(); + NuGetToolPathResolver.NuGetPackagesConfigFile.Should().BeNull(); + NuGetToolPathResolver.NuGetAssetsConfigFile.Should().BeNull(); + NuGetToolPathResolver.PaketPackagesConfigFile.Should().BeNull(); + } + + [Fact] + public void NpmToolPathResolver_Reset_clears_the_package_json_location() + { + NpmToolPathResolver.NpmPackageJsonFile = "/tmp/package.json"; + + NpmToolPathResolver.Reset(); + + NpmToolPathResolver.NpmPackageJsonFile.Should().BeNull(); + } + + // Restore whatever the ambient environment had so these mutations don't leak into sibling tests. + public void Dispose() + { + NuGetToolPathResolver.EmbeddedPackagesDirectory = _embeddedPackagesDirectory; + NuGetToolPathResolver.NuGetPackagesConfigFile = _nuGetPackagesConfigFile; + NuGetToolPathResolver.NuGetAssetsConfigFile = _nuGetAssetsConfigFile; + NuGetToolPathResolver.PaketPackagesConfigFile = _paketPackagesConfigFile; + NpmToolPathResolver.NpmPackageJsonFile = _npmPackageJsonFile; + } +} + +[CollectionDefinition(Name, DisableParallelization = true)] +public class ToolPathResolverStateCollection +{ + public const string Name = "ToolPathResolverState"; +} diff --git a/tests/Fallout.Tooling.Specs/ToolTasksToolPathSpecs.cs b/tests/Fallout.Tooling.Specs/ToolTasksToolPathSpecs.cs index dca4c5b0b..6b12fb072 100644 --- a/tests/Fallout.Tooling.Specs/ToolTasksToolPathSpecs.cs +++ b/tests/Fallout.Tooling.Specs/ToolTasksToolPathSpecs.cs @@ -7,6 +7,7 @@ namespace Fallout.Common.Specs; +[Collection(ToolPathResolverStateCollection.Name)] public class ToolTasksToolPathSpecs { public ToolTasksToolPathSpecs()