From 00e76c7401bc451d6c8b3e9b43229d36dc0ea43a Mon Sep 17 00:00:00 2001 From: Chrison Simtian Date: Tue, 30 Jun 2026 22:19:26 +1200 Subject: [PATCH 1/4] Move the in-memory log sink onto BuildContext (FT-6) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Logging.InMemorySink is now owned per-run by BuildContext.LogSink; the static InMemorySink.Instance becomes a facade over BuildContext.Current, with a lazy ambient fallback for logging outside a run. ConfigureInMemory wires the sink at the top of the run and WriteErrorsAndWarnings reads it at the end — both inside the scope — so a build's warnings and errors are discarded with its context instead of resurfacing in the next in-process invocation. The FT-1 InMemorySink.Clear() on dispose is dropped: there is no shared sink left to clear. Clear() itself stays for explicit resets. The sink constructor becomes internal so a context (and a spec) can create its own. Non-breaking — the public Logging surface is unchanged. --- docs/engine-de-statification.md | 2 +- src/Fallout.Build/Execution/BuildContext.cs | 30 ++++++++++++++++++--- src/Fallout.Build/Logging.cs | 21 ++++++++++++--- 3 files changed, 45 insertions(+), 8 deletions(-) diff --git a/docs/engine-de-statification.md b/docs/engine-de-statification.md index 151eff700..dba52b6bd 100644 --- a/docs/engine-de-statification.md +++ b/docs/engine-de-statification.md @@ -80,7 +80,7 @@ flowchart TD ### Problems (all in the engine) - **God class** — `FalloutBuild` is ~456 LOC across 5 partials with 4 responsibilities: inheritable base class (`FalloutBuild.cs`), process-global state + static ctor (`FalloutBuild.Statics.cs:16-30`), output formatting (`FalloutBuild.Output.cs`), extension host (`FalloutBuild.Events.cs`). The partials hide the size, not the coupling. -- **Static state leaks across runs** — `BuildManager.cs:20,41,69` (handlers accumulate), `Logging.cs:20,214` (`LevelSwitch` + `InMemorySink.Instance` carry log events over), `ValueInjectionUtility.cs:13` (`s_valueCache` persists), `NuGetToolPathResolver.cs:14-17` (set per-run at `BuildManager.cs:53-56`, never reset). +- **Static state leaks across runs** — `BuildManager.cs:20,41,69` (handlers accumulate), `Logging.cs:20` (`LevelSwitch` carries over) and `Logging.cs:214` (`InMemorySink.Instance` carried log events over; now per-run on `BuildContext.LogSink`, FT-6), `ValueInjectionUtility.cs:13` (`s_valueCache` persists), `NuGetToolPathResolver.cs:14-17` (set per-run at `BuildManager.cs:53-56`, never reset). - **Test/prod path divergence** — production reads the static `ParameterService.Instance` (`ParameterService.Statics.cs:11-13`), but `ParameterServiceTest.cs:14-22` constructs a *fresh* `ParameterService(funcs)`. Tests exercise a different object than production. - **No DIP seams** — `BuildManager.cs:39-41` pokes `Console` directly; `BuildExecutor.cs:81` writes the filesystem directly; output goes through static `Host.Error()`. diff --git a/src/Fallout.Build/Execution/BuildContext.cs b/src/Fallout.Build/Execution/BuildContext.cs index 339111f38..675acc965 100644 --- a/src/Fallout.Build/Execution/BuildContext.cs +++ b/src/Fallout.Build/Execution/BuildContext.cs @@ -15,10 +15,13 @@ namespace Fallout.Build.Execution; /// /// /// is stored in an , so concurrent runs each see their own context. -/// The context owns the cancellation handlers, the event subscriptions and the . +/// The context owns the cancellation handlers, the event subscriptions, the +/// and the in-memory log sink. +/// Serilog's Log.Logger is still process-wide, so two runs at the same time can send events +/// to each other's sink. The sink itself is not shared. /// /// -/// On dispose, the context also resets some process-wide state: the in-memory log sink, the value-injection cache +/// On dispose, the context also resets some process-wide state: the value-injection cache /// and the NuGet and npm tool path resolvers. That state is shared, so concurrent runs in one process can still /// affect each other through it. /// @@ -48,9 +51,17 @@ internal sealed class BuildContext : IDisposable /// public ParameterService Parameters { get; } = ParameterService.CreateDefault(); + /// + /// The in-memory log sink for this run. FT-6 / #311: + /// Logging.ConfigureInMemory wires Serilog to this instance at the top of the run and + /// WriteErrorsAndWarnings reads it back at the end, both inside the scope — so a run's + /// warnings and errors are discarded with it rather than resurfacing in the next build. + /// + public Logging.InMemorySink LogSink { get; } = new(); + private BuildContext() { - onCancelKeyPress = (_, _) => cancellationHandlers.ForEach(x => x()); + onCancelKeyPress = (_, _) => RunCancellationHandlers(); onToolOptionsCreated = (options, _) => VerbosityMapping.Apply((ToolOptions)options); Console.CancelKeyPress += onCancelKeyPress; ToolOptions.Created += onToolOptionsCreated; @@ -59,6 +70,17 @@ private BuildContext() /// Creates the ambient context for a build run and installs it as . public static BuildContext Activate() => currentInstance.Value = new BuildContext(); + /// + /// Runs the cancellation handlers with this context as . Console.CancelKeyPress + /// fires on a thread that does not carry the run's , and the handlers + /// (for example the build summary) read run state such as through it. + /// + internal void RunCancellationHandlers() + { + currentInstance.Value = this; + cancellationHandlers.ForEach(x => x()); + } + public void RegisterCancellationHandler(Action handler) => cancellationHandlers.AddFirst(handler); public void UnregisterCancellationHandler(Action handler) => cancellationHandlers.Remove(handler); @@ -66,6 +88,7 @@ private BuildContext() public void Dispose() { // These subscriptions belong to this instance, so removing them never affects another context. + // The per-run services (Parameters, LogSink) are dropped with the context, so they need no reset. Console.CancelKeyPress -= onCancelKeyPress; ToolOptions.Created -= onToolOptionsCreated; @@ -76,7 +99,6 @@ public void Dispose() return; } - Logging.InMemorySink.Instance.Clear(); ValueInjectionUtility.ClearCache(); NuGetToolPathResolver.Reset(); NpmToolPathResolver.Reset(); diff --git a/src/Fallout.Build/Logging.cs b/src/Fallout.Build/Logging.cs index 714265f2b..309d65928 100644 --- a/src/Fallout.Build/Logging.cs +++ b/src/Fallout.Build/Logging.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using Fallout.Build.Execution; using Fallout.Common.CI; using Fallout.Common.Execution.Theming; using Fallout.Common.IO; @@ -242,11 +243,21 @@ public static IDisposable SetTarget(string name) public class InMemorySink : ILogEventSink, IDisposable { - public static InMemorySink Instance { get; } = new(); + // FT-6 (#311): the active sink is the per-run one on BuildContext, so one build's warnings and + // errors cannot resurface in the next build in the same process. The fallback covers logging + // outside a run — process-wide, but with no run for its events to bleed into. + private static readonly Lazy ambientInstance = new(() => new InMemorySink()); + + /// + /// The sink of the running build, or a shared fallback sink outside a run. The result changes + /// between runs, so do not cache it across a run boundary. A sink fetched before + /// BuildManager.Execute starts is the fallback, not the run's sink. + /// + public static InMemorySink Instance => BuildContext.Current?.LogSink ?? ambientInstance.Value; private readonly List logEvents; - private InMemorySink() + internal InMemorySink() { logEvents = new List(); } @@ -259,7 +270,11 @@ public void Emit(LogEvent logEvent) logEvents.Add(logEvent); } - /// Drops accumulated events so a subsequent build in the same process starts clean. FT-1 / #306. + /// + /// Drops accumulated events. Since FT-6 / #311 a run's sink is discarded with its + /// , so this is no longer needed to keep runs from bleeding into each + /// other — it stays for explicit resets (and for ). + /// public void Clear() { logEvents.Clear(); From 81ccfa6f02b1c76535a5d925ce2b6d7fc6df7b92 Mon Sep 17 00:00:00 2001 From: Chrison Simtian Date: Sun, 26 Jul 2026 22:40:48 +1200 Subject: [PATCH 2/4] Scope the log-sink specs to the per-run sink MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit BuildContextSpecs mirrors the FT-4 parameter-service cases for the sink: the facade resolves the running context's sink, falls back to a stable ambient sink outside a run, and each run gets its own. Two existing cases assumed a process-wide sink and had to move with the mechanism: - Dispose_runs_the_per_run_teardown used the shared sink as its witness and fails once dispose stops clearing it — it becomes Log_events_do_not_carry_into_the_next_run, asserting the guarantee directly (the next run's sink never saw the previous run's events); - Disposing_a_superseded_context_leaves_the_shared_state_intact drops its sink witness and keeps the resolver-config one, since the sink is no longer shared state. InMemorySinkSpecs now exercises its own instance rather than the singleton, so it no longer needs the process-global collection or a normalising reset between cases. --- .../Fallout.Build.Specs/BuildContextSpecs.cs | 65 ++++- .../Fallout.Build.Specs/InMemorySinkSpecs.cs | 50 ++-- .../LogSinkScopeQaSpecs.cs | 273 ++++++++++++++++++ 3 files changed, 347 insertions(+), 41 deletions(-) create mode 100644 tests/Fallout.Build.Specs/LogSinkScopeQaSpecs.cs diff --git a/tests/Fallout.Build.Specs/BuildContextSpecs.cs b/tests/Fallout.Build.Specs/BuildContextSpecs.cs index e29209ae5..df6b73f5c 100644 --- a/tests/Fallout.Build.Specs/BuildContextSpecs.cs +++ b/tests/Fallout.Build.Specs/BuildContextSpecs.cs @@ -13,10 +13,11 @@ namespace Fallout.Common.Specs.Execution; /// /// Covers (FT-2 / #307) — the per-run ambient scope that owns the -/// process-global state a build touches. is AsyncLocal, so -/// each case resolves its own context, but the singletons the teardown resets (in-memory sink, -/// value-injection cache, resolver config) remain process-wide — assertions that touch them key on a -/// sentinel rather than on the singleton being empty. +/// process-global state a build touches, plus the services that have since moved onto it (the +/// parameter service, FT-4 / #309; the in-memory log sink, FT-6 / #311). +/// is AsyncLocal, so each case resolves its own context, but +/// the singletons the teardown still resets (value-injection cache, resolver config) remain +/// process-wide — assertions that touch those key on a sentinel rather than on the singleton being empty. /// [Collection(ProcessGlobalStateCollection.Name)] public class BuildContextSpecs @@ -104,6 +105,39 @@ public void Parameter_service_state_does_not_leak_into_the_next_run() ParameterService.Instance.ArgumentsFromCommitMessageService.Should().BeNull(); } + [Fact] + public void Log_sink_facade_resolves_the_current_contexts_sink() + { + using var context = BuildContext.Activate(); + + // FT-6 (#311): same seam as the parameter service — the static sink is a pointer at the run. + Logging.InMemorySink.Instance.Should().BeSameAs(context.LogSink); + } + + [Fact] + public void Log_sink_facade_falls_back_to_an_ambient_sink_outside_a_run() + { + BuildContext.Current.Should().BeNull(); + + // Logging outside a run (a CLI command, a spec) has to land somewhere rather than throw. + Logging.InMemorySink.Instance.Should().NotBeNull(); + Logging.InMemorySink.Instance.Should().BeSameAs(Logging.InMemorySink.Instance); + } + + [Fact] + public void Each_run_gets_its_own_log_sink() + { + Logging.InMemorySink first; + Logging.InMemorySink second; + + using (var context = BuildContext.Activate()) + first = context.LogSink; + using (var context = BuildContext.Activate()) + second = context.LogSink; + + second.Should().NotBeSameAs(first); + } + [Fact] public void Disposing_a_superseded_context_leaves_the_newer_one_current() { @@ -119,20 +153,17 @@ public void Disposing_a_superseded_context_leaves_the_newer_one_current() [Fact] public void Disposing_a_superseded_context_leaves_the_shared_state_intact() { - var sink = Logging.InMemorySink.Instance; var sentinel = $"build-context-superseded-{Guid.NewGuid()}"; var first = BuildContext.Activate(); using var second = BuildContext.Activate(); NuGetToolPathResolver.EmbeddedPackagesDirectory = sentinel; - sink.Emit(CreateLogEvent(sentinel)); - // `second` is the live run and this state belongs to it. The teardown resets are process-wide, + // `second` is the live run and this config belongs to it. The teardown resets are process-wide, // so a superseded scope disposing out of order must skip them entirely — clearing Current is // not the only thing the identity guard protects. first.Dispose(); - sink.LogEvents.Should().Contain(x => x.MessageTemplate.Text == sentinel); NuGetToolPathResolver.EmbeddedPackagesDirectory.Should().Be(sentinel); } @@ -186,20 +217,22 @@ public void Cancellation_handler_facade_is_a_no_op_without_an_active_context() } [Fact] - public void Dispose_runs_the_per_run_teardown() + public void Log_events_do_not_carry_into_the_next_run() { - var sink = Logging.InMemorySink.Instance; - var sentinel = $"build-context-teardown-{Guid.NewGuid()}"; + var sentinel = $"build-context-log-{Guid.NewGuid()}"; using (BuildContext.Activate()) { - sink.Emit(CreateLogEvent(sentinel)); + Logging.InMemorySink.Instance.Emit(CreateLogEvent(sentinel)); } - // Leaving the scope disposes the context, whose teardown clears the shared in-memory sink so a - // subsequent run in the same process starts clean. Assert on the sentinel specifically so a - // build emitting on another flow can't make this flaky. - sink.LogEvents.Should().NotContain(x => x.MessageTemplate.Text == sentinel); + // FT-6 (#311): the sink belonged to the run that just ended and went out of scope with it, so + // the next run starts on an empty one. Nothing clears a shared sink — there is no shared sink. + // Assert on the sentinel specifically so a build emitting on another flow can't make it flaky. + using (BuildContext.Activate()) + { + Logging.InMemorySink.Instance.LogEvents.Should().NotContain(x => x.MessageTemplate.Text == sentinel); + } } private static LogEvent CreateLogEvent(string message) => diff --git a/tests/Fallout.Build.Specs/InMemorySinkSpecs.cs b/tests/Fallout.Build.Specs/InMemorySinkSpecs.cs index e254a2eaa..bf0ac3e72 100644 --- a/tests/Fallout.Build.Specs/InMemorySinkSpecs.cs +++ b/tests/Fallout.Build.Specs/InMemorySinkSpecs.cs @@ -1,4 +1,5 @@ using System; +using Fallout.Build.Execution; using Fallout.Common.Execution; using FluentAssertions; using Serilog.Events; @@ -8,54 +9,53 @@ 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. +/// Covers 's own reset behaviour (FT-1 / #306). Since FT-6 / #311 a +/// sink is per-run state owned by a rather than a process-wide singleton, so +/// each case exercises its own instance and nothing here needs serialising against other specs. How the +/// per-run sink is resolved and scoped is covered by BuildContextSpecs. /// -[Collection(ProcessGlobalStateCollection.Name)] 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(); - } + private readonly Logging.InMemorySink sink = new(); [Fact] public void Clear_drops_accumulated_events() { - Sink.Emit(CreateLogEvent("first")); - Sink.Emit(CreateLogEvent("second")); - Sink.LogEvents.Should().HaveCount(2); + sink.Emit(CreateLogEvent("first")); + sink.Emit(CreateLogEvent("second")); + sink.LogEvents.Should().HaveCount(2); - Sink.Clear(); + sink.Clear(); - Sink.LogEvents.Should().BeEmpty(); + sink.LogEvents.Should().BeEmpty(); } [Fact] public void Dispose_drops_accumulated_events() { - Sink.Emit(CreateLogEvent("only")); - Sink.LogEvents.Should().ContainSingle(); + sink.Emit(CreateLogEvent("only")); + sink.LogEvents.Should().ContainSingle(); - Sink.Dispose(); + sink.Dispose(); - Sink.LogEvents.Should().BeEmpty(); + sink.LogEvents.Should().BeEmpty(); } [Fact] public void Clear_on_an_empty_sink_is_a_no_op() { - Sink.LogEvents.Should().BeEmpty(); + sink.LogEvents.Should().BeEmpty(); - Sink.Clear(); + sink.Clear(); - Sink.LogEvents.Should().BeEmpty(); + sink.LogEvents.Should().BeEmpty(); + } + + [Fact] + public void A_new_sink_starts_empty() + { + // A run's sink is constructed with its context, so a build never inherits earlier events. + new Logging.InMemorySink().LogEvents.Should().BeEmpty(); } private static LogEvent CreateLogEvent(string message) => diff --git a/tests/Fallout.Build.Specs/LogSinkScopeQaSpecs.cs b/tests/Fallout.Build.Specs/LogSinkScopeQaSpecs.cs new file mode 100644 index 000000000..99da70a74 --- /dev/null +++ b/tests/Fallout.Build.Specs/LogSinkScopeQaSpecs.cs @@ -0,0 +1,273 @@ +using System; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using FluentAssertions; +using Fallout.Build.Execution; +using Fallout.Common.Execution; +using Serilog.Events; +using Serilog.Parsing; +using Xunit; + +namespace Fallout.Common.Specs; + +[Collection(ProcessGlobalStateCollection.Name)] +public class LogSinkScopeQaSpecs +{ + private static LogEvent Event(string text, LogEventLevel level = LogEventLevel.Warning) + => new(DateTimeOffset.UtcNow, level, null, new MessageTemplateParser().Parse(text), []); + + private static string[] Texts(Logging.InMemorySink sink) + => sink.LogEvents.Select(x => x.RenderMessage()).ToArray(); + + [Fact] + public void Each_run_gets_its_own_sink() + { + // Arrange + using var runA = BuildContext.Activate(); + var sinkA = Logging.InMemorySink.Instance; + + // Act + using var runB = BuildContext.Activate(); + var sinkB = Logging.InMemorySink.Instance; + + // Assert + sinkB.Should().NotBeSameAs(sinkA); + } + + [Fact] + public void Facade_returns_the_same_sink_throughout_one_run() + { + // Arrange + using var run = BuildContext.Activate(); + + // Act + var first = Logging.InMemorySink.Instance; + var second = Logging.InMemorySink.Instance; + + // Assert + second.Should().BeSameAs(first); + } + + [Fact] + public void Events_from_run_A_are_not_visible_in_run_B() + { + // Arrange + using (BuildContext.Activate()) + { + Logging.InMemorySink.Instance.Emit(Event("from A")); + Texts(Logging.InMemorySink.Instance).Should().Contain("from A"); + } + + // Act + using var runB = BuildContext.Activate(); + + // Assert + Texts(Logging.InMemorySink.Instance).Should().BeEmpty(); + } + + [Fact] + public void Events_from_run_B_do_not_appear_in_run_A_sink() + { + // Arrange + using var runA = BuildContext.Activate(); + var sinkA = Logging.InMemorySink.Instance; + + // Act + using var runB = BuildContext.Activate(); + Logging.InMemorySink.Instance.Emit(Event("from B")); + + // Assert + Texts(sinkA).Should().BeEmpty(); + } + + [Fact] + public void Fallback_outside_a_run_is_stable() + { + // Arrange + BuildContext.Current.Should().BeNull(); + + // Act + var first = Logging.InMemorySink.Instance; + var second = Logging.InMemorySink.Instance; + + // Assert + first.Should().NotBeNull(); + second.Should().BeSameAs(first); + } + + [Fact] + public void Fallback_is_not_the_sink_of_a_run() + { + // Arrange + var fallback = Logging.InMemorySink.Instance; + + // Act + using var run = BuildContext.Activate(); + + // Assert + Logging.InMemorySink.Instance.Should().NotBeSameAs(fallback); + } + + [Fact] + public void Run_events_do_not_leak_into_the_fallback() + { + // Arrange + var fallback = Logging.InMemorySink.Instance; + fallback.Clear(); + + // Act + using (BuildContext.Activate()) + Logging.InMemorySink.Instance.Emit(Event("in run")); + + // Assert + Texts(fallback).Should().BeEmpty(); + } + + [Fact] + public async Task Concurrent_runs_do_not_see_each_others_events() + { + // Arrange + using var gate = new System.Threading.Barrier(2); + + async Task<(string[] Texts, Logging.InMemorySink Sink)> Run(string tag) + { + await Task.Yield(); + using var ctx = BuildContext.Activate(); + var sink = Logging.InMemorySink.Instance; + gate.SignalAndWait(); + for (var i = 0; i < 200; i++) + { + sink.Emit(Event($"{tag}-{i}")); + if (i % 20 == 0) await Task.Yield(); + } + + gate.SignalAndWait(); + return (Texts(Logging.InMemorySink.Instance), sink); + } + + // Act + var results = await Task.WhenAll(Task.Run(() => Run("A")), Task.Run(() => Run("B"))); + + // Assert + results[0].Sink.Should().NotBeSameAs(results[1].Sink); + results[0].Texts.Should().HaveCount(200).And.OnlyContain(x => x.StartsWith("A-")); + results[1].Texts.Should().HaveCount(200).And.OnlyContain(x => x.StartsWith("B-")); + } + + [Fact] + public async Task Facade_in_a_child_task_resolves_the_parent_runs_sink() + { + // Arrange + using var run = BuildContext.Activate(); + var expected = Logging.InMemorySink.Instance; + + // Act + var seen = await Task.Run(() => Logging.InMemorySink.Instance); + + // Assert + seen.Should().BeSameAs(expected); + } + + [Fact] + public void End_of_run_report_contains_only_that_runs_warnings_and_errors() + { + // Arrange + using (BuildContext.Activate()) + Logging.InMemorySink.Instance.Emit(Event("old warning")); + + // Act + using var run = BuildContext.Activate(); + Logging.InMemorySink.Instance.Emit(Event("new warning")); + Logging.InMemorySink.Instance.Emit(Event("new error", LogEventLevel.Error)); + + // Assert + Texts(Logging.InMemorySink.Instance).Should().Equal("new warning", "new error"); + } + + [Fact] + public void Clear_empties_the_current_runs_sink() + { + // Arrange + using var run = BuildContext.Activate(); + var sink = Logging.InMemorySink.Instance; + sink.Emit(Event("x")); + + // Act + sink.Clear(); + + // Assert + sink.LogEvents.Should().BeEmpty(); + } + + [Fact] + public void Clear_in_one_run_leaves_another_runs_sink_intact() + { + // Arrange + using var runA = BuildContext.Activate(); + var sinkA = Logging.InMemorySink.Instance; + sinkA.Emit(Event("keep")); + using var runB = BuildContext.Activate(); + + // Act + Logging.InMemorySink.Instance.Clear(); + + // Assert + Texts(sinkA).Should().Equal("keep"); + } + + [Fact] + public void Disposing_a_run_does_not_clear_the_fallback() + { + // Arrange + var fallback = Logging.InMemorySink.Instance; + fallback.Clear(); + fallback.Emit(Event("fallback event")); + + // Act + using (BuildContext.Activate()) { } + + // Assert + Texts(fallback).Should().Equal("fallback event"); + fallback.Clear(); + } + + [Fact] + public void Cancellation_handlers_see_the_run_sink_on_a_thread_without_the_run_context() + { + // Arrange + using var context = BuildContext.Activate(); + context.LogSink.Emit(Event("from the run")); + Logging.InMemorySink seen = null; + context.RegisterCancellationHandler(() => seen = Logging.InMemorySink.Instance); + + // Act (Console.CancelKeyPress fires on a thread that does not carry the run's AsyncLocal) + using (ExecutionContext.SuppressFlow()) + { + var thread = new Thread(context.RunCancellationHandlers); + thread.Start(); + thread.Join(); + } + + // Assert + seen.Should().BeSameAs(context.LogSink); + Texts(seen).Should().Equal("from the run"); + } + + [Fact] + public void Configured_sink_collects_run_warnings_for_the_summary() + { + // Arrange + using var context = BuildContext.Activate(); + var logger = new Serilog.LoggerConfiguration() + .WriteTo.Sink(Logging.InMemorySink.Instance, LogEventLevel.Warning) + .CreateLogger(); + + // Act + logger.Information("ignored"); + logger.Warning("kept"); + + // Assert + Texts(context.LogSink).Should().Equal("kept"); + } +} From e099f40eb0e61e26091a189c05d3aaea560caf51 Mon Sep 17 00:00:00 2001 From: Chrison Simtian Date: Sun, 26 Jul 2026 22:52:24 +1200 Subject: [PATCH 3/4] Release the run's file sinks when the errors-and-warnings logger takes over MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Host.WriteErrorsAndWarnings replaces Log.Logger with a console-only logger to re-render the run's warnings. The logger it replaced owns that run's file sinks, and assigning Log.Logger does not dispose it — so it leaked and kept `build.log` open for the life of the process. The next in-process run then threw in Logging.DeleteOldLogFiles trying to truncate that file, and did so silently: the throw lands before Configure has reassigned Log.Logger, so Execute's own Host.Error call went to an already-disposed logger. The run just returned the error exit code with no output. Any second run whose predecessor logged a warning hit this. Dispose the replaced logger. Nothing is lost — from that point the run logs through the console-only logger regardless, so the file sinks were already out of the picture. --- src/Fallout.Build/Host.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/Fallout.Build/Host.cs b/src/Fallout.Build/Host.cs index 1ab513d1f..ab3897200 100644 --- a/src/Fallout.Build/Host.cs +++ b/src/Fallout.Build/Host.cs @@ -102,6 +102,10 @@ protected internal virtual void WriteErrorsAndWarnings() // TODO: move to Logging using (WriteBlock("Errors & Warnings")) { + // The logger we replace owns the run's file sinks. Setting Log.Logger does not dispose it. + // Without this, `build.log` stays open and the next run in the same process cannot reset it. + var replaced = Log.Logger as IDisposable; + Log.Logger = new LoggerConfiguration() .WriteTo.Console( outputTemplate: Logging.ErrorsAndWarningsOutputTemplate, @@ -109,6 +113,8 @@ protected internal virtual void WriteErrorsAndWarnings() applyThemeToRedirectedOutput: true) .CreateLogger(); + replaced?.Dispose(); + var nonEmptyLogEvents = Logging.InMemorySink.Instance.LogEvents.Where(x => !x.MessageTemplate.Text.IsNullOrEmpty()); nonEmptyLogEvents.ForEach(Log.Write); } From 565ef40a3d8515936ded9b9fa567dc19130693a3 Mon Sep 17 00:00:00 2001 From: Chrison Simtian Date: Sun, 26 Jul 2026 22:52:24 +1200 Subject: [PATCH 4/4] Add the reentrant Execute harness (FT-9) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Runs a fixture build end-to-end, twice in one process, and asserts what the de-static work promised: both runs succeed, the second gets its own context/parameter service/log sink, it opens on an empty sink, and the static facades inside a run point at that run. This is what the original FT-9 commit set out to do. Its unit-level assertions have since landed with the steps they belong to (FT-2 in #451, FT-4 in #452, FT-6 in #453), so what is left here is the end-to-end case they could not cover — and it immediately found the leaked file-sink logger fixed in the previous commit. Verified as a real guard: reverting that fix fails 4 of these 5 specs. Two process-wide inputs are pinned to make a build runnable under a test host — the argument parser (swapped and restored) and the statically-resolved root directory (asserted to carry the .fallout marker, since UpdateNotification prompts for input without it). Both are de-statification candidates in their own right. --- .../BuildManagerReentrancySpecs.cs | 166 ++++++++++++++++++ .../GitRepositoryWorktreeSpecs.cs | 3 + 2 files changed, 169 insertions(+) create mode 100644 tests/Fallout.Build.Specs/BuildManagerReentrancySpecs.cs diff --git a/tests/Fallout.Build.Specs/BuildManagerReentrancySpecs.cs b/tests/Fallout.Build.Specs/BuildManagerReentrancySpecs.cs new file mode 100644 index 000000000..9ee7b264d --- /dev/null +++ b/tests/Fallout.Build.Specs/BuildManagerReentrancySpecs.cs @@ -0,0 +1,166 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using FluentAssertions; +using Fallout.Build.Execution; +using Fallout.Common.Execution; +using Fallout.Common.IO; +using Fallout.Common.Utilities; +using Serilog; +using Xunit; + +namespace Fallout.Common.Specs.Execution; + +/// +/// Runs a real build through twice in one process (FT-9, +/// #314). This checks that each run +/// gets its own state and that nothing carries over. +/// +/// +/// Two process-wide inputs must be fixed for a build to run under a test host. Both are candidates to +/// make per-run later: +/// +/// : Execute reads the invoked +/// targets from the process arguments, which here belong to the test runner. The specs replace it and +/// restore it afterwards. +/// : it is set once in a static constructor, +/// so it always points at this repo's root. That root has the .fallout marker the first spec +/// checks. +/// +/// +[Collection(ProcessGlobalStateCollection.Name)] +public class BuildManagerReentrancySpecs : IDisposable +{ + private static readonly Expression>[] defaultTargets = { x => x.Ping }; + + private readonly ArgumentParser originalArguments = EnvironmentInfo.ArgumentParser; + private readonly ILogger originalLogger = Log.Logger; + + public BuildManagerReentrancySpecs() + { + // A local build without a `.fallout` marker waits for a key press (UpdateNotificationAttribute). + // Check the marker for every spec, so a moved spec fails here and does not hang. + Constants.GetFalloutDirectory(FalloutBuild.RootDirectory).DirectoryExists().Should().BeTrue( + "the harness runs a local build, which prompts for input when the root has no .fallout marker"); + + EnvironmentInfo.ArgumentParser = new ArgumentParser(new[] { nameof(ReentrancyBuild.Ping) }); + ReentrancyBuild.Runs.Clear(); + } + + public void Dispose() + { + EnvironmentInfo.ArgumentParser = originalArguments; + Log.Logger = originalLogger; + ReentrancyBuild.Runs.Clear(); + } + + [Fact] + public void A_build_runs_end_to_end_under_the_harness() + { + var exitCode = Run(); + + exitCode.Should().Be(0); + ReentrancyBuild.Runs.Should().ContainSingle(); + BuildContext.Current.Should().BeNull("the scope is disposed when Execute returns"); + } + + [Fact] + public void A_second_run_in_the_same_process_also_succeeds() + { + // The first run logs a warning. Host.WriteErrorsAndWarnings then replaces Log.Logger. + // Before the fix, the replaced logger kept `build.log` open. The second run then failed to + // reset that file and returned the error exit code without any message. + Run().Should().Be(0); + + Run().Should().Be(0, "a second in-process run must not inherit the first run's open log file"); + } + + [Fact] + public void A_second_run_gets_its_own_context_and_services() + { + RunSucceeding(); + RunSucceeding(); + + var (first, second) = FirstTwoRuns(); + + second.Context.Should().NotBeSameAs(first.Context, "FT-2 (#307)"); + second.Parameters.Should().NotBeSameAs(first.Parameters, "FT-4 (#309)"); + second.LogSink.Should().NotBeSameAs(first.LogSink, "FT-6 (#311)"); + } + + [Fact] + public void A_second_run_does_not_see_the_first_runs_log_events() + { + RunSucceeding(); + RunSucceeding(); + + var (first, second) = FirstTwoRuns(); + + // Each run starts with an empty sink and ends with only its own warning. Carry-over from the + // first run would show up in the second run's entry snapshot. + first.EventsOnEntry.Should().BeEmpty(); + second.EventsOnEntry.Should().BeEmpty(); + second.EventsAfterOwnWarning.Should().ContainSingle().Which.Should().Be(second.Sentinel); + } + + [Fact] + public void The_static_facades_inside_a_run_point_at_that_run() + { + RunSucceeding(); + + var run = ReentrancyBuild.Runs.Single(); + + run.Parameters.Should().BeSameAs(run.Context.Parameters); + run.LogSink.Should().BeSameAs(run.Context.LogSink); + } + + private static int Run() => BuildManager.Execute(defaultTargets); + + private static void RunSucceeding() => Run().Should().Be(0, "the run must reach its target"); + + private static (RunObservation First, RunObservation Second) FirstTwoRuns() + { + ReentrancyBuild.Runs.Should().HaveCount(2, "both runs must reach their target"); + return (ReentrancyBuild.Runs[0], ReentrancyBuild.Runs[1]); + } + + /// What one run of the fixture build observed about its own per-run state. + private sealed record RunObservation( + BuildContext Context, + ParameterService Parameters, + Logging.InMemorySink LogSink, + string Sentinel, + IReadOnlyCollection EventsOnEntry, + IReadOnlyCollection EventsAfterOwnWarning); + + /// + /// The build the specs run. Its one target records the per-run state it sees and logs one warning, + /// so a later run can be checked for carry-over. + /// + private class ReentrancyBuild : FalloutBuild + { + public static readonly List Runs = new(); + + public Target Ping => _ => _ + .Executes(() => + { + var sink = Logging.InMemorySink.Instance; + var eventsOnEntry = Texts(sink); + var sentinel = $"reentrancy-run-{Runs.Count}"; + + Log.Warning(sentinel); + + Runs.Add(new RunObservation( + Context: BuildContext.Current, + Parameters: ParameterService.Instance, + LogSink: sink, + Sentinel: sentinel, + EventsOnEntry: eventsOnEntry, + EventsAfterOwnWarning: Texts(sink))); + }); + + private static IReadOnlyCollection Texts(Logging.InMemorySink sink) => + sink.LogEvents.Select(x => x.MessageTemplate.Text).ToList(); + } +} diff --git a/tests/Fallout.Build.Specs/GitRepositoryWorktreeSpecs.cs b/tests/Fallout.Build.Specs/GitRepositoryWorktreeSpecs.cs index 8244f4479..a376f3acb 100644 --- a/tests/Fallout.Build.Specs/GitRepositoryWorktreeSpecs.cs +++ b/tests/Fallout.Build.Specs/GitRepositoryWorktreeSpecs.cs @@ -9,6 +9,9 @@ namespace Fallout.Common.Specs; +// Runs `git` through the process runner, which logs to the process-wide Log. Without the shared +// collection those lines land in a concurrent build run's in-memory sink. +[Collection(ProcessGlobalStateCollection.Name)] public class GitRepositoryWorktreeSpecs { [Fact]