From 682c6c4c28bf4e43508a593df0e1a434cf5ca291 Mon Sep 17 00:00:00 2001 From: Juster Zhu Date: Sun, 22 Nov 2026 23:06:46 +0800 Subject: [PATCH 1/2] Add opt-in startup health state store Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/startup-health-store.md | 28 +++ .../StartupHealth/StartupHealthStatus.cs | 11 ++ .../StartupHealth/StartupHealthStore.cs | 170 ++++++++++++++++++ tests/CoreTest/CoreTest.csproj | 1 + .../StartupHealth/StartupHealthStoreTests.cs | 145 +++++++++++++++ tests/StartupHealthProbe/Program.cs | 29 +++ .../StartupHealthProbe.csproj | 11 ++ 7 files changed, 395 insertions(+) create mode 100644 docs/startup-health-store.md create mode 100644 src/GeneralUpdate.Core/StartupHealth/StartupHealthStatus.cs create mode 100644 src/GeneralUpdate.Core/StartupHealth/StartupHealthStore.cs create mode 100644 tests/CoreTest/StartupHealth/StartupHealthStoreTests.cs create mode 100644 tests/StartupHealthProbe/Program.cs create mode 100644 tests/StartupHealthProbe/StartupHealthProbe.csproj diff --git a/docs/startup-health-store.md b/docs/startup-health-store.md new file mode 100644 index 00000000..8df87ee4 --- /dev/null +++ b/docs/startup-health-store.md @@ -0,0 +1,28 @@ +# Startup health state foundation + +`StartupHealthStore` is opt-in and independent of the update pipeline. A trusted +host creates an attempt with a future UTC deadline, shares its directory and ID +with the updated application, and the application calls `ConfirmHealthy` only +after its own business readiness checks pass. The host can record `Failed` or +`ProcessExited` when it observes a failure. `GetStatus` records `TimedOut` on +the first access at or after the deadline if no terminal outcome was recorded. +A restarted host can reopen the same attempt. Terminal outcomes cannot be +overwritten; a `false` return means no new outcome was recorded, so read the +status to distinguish a retry from a conflicting outcome. + +The store uses a local, host-controlled persistent directory, atomic file +publication and an OS-released per-attempt lock. Use the same path for all +participants, outside the installation and backup trees, and restrict write +access to trusted processes. An attempt ID is not an authentication credential. +Do not delete an attempt or its lock while any participant might still use it. +The host owns eventual cleanup. UTC clock changes can affect deadlines. This +mechanism is intended for process crashes, not a guarantee against power loss +or filesystems without reliable local locking and atomic renames. + +This is **not an end-to-end rollback implementation**. It does not launch or +monitor processes, send reports, select or restore backups, change manifest +versions, or claim rollback ownership. In particular, a running process is not +proof of health. Existing update and reporting behavior remains unchanged. +Integrating it requires an agreed cross-process contract, a single rollback +owner shared with Bowl, exact backup identity, durable and idempotent recovery +of interrupted rollback, and lifecycle/reporting changes across the hosts. diff --git a/src/GeneralUpdate.Core/StartupHealth/StartupHealthStatus.cs b/src/GeneralUpdate.Core/StartupHealth/StartupHealthStatus.cs new file mode 100644 index 00000000..72fae3db --- /dev/null +++ b/src/GeneralUpdate.Core/StartupHealth/StartupHealthStatus.cs @@ -0,0 +1,11 @@ +namespace GeneralUpdate.Core.StartupHealth; + +/// Outcome of an explicitly monitored startup attempt. +public enum StartupHealthStatus +{ + Pending = 0, + Healthy = 1, + Failed = 2, + ProcessExited = 3, + TimedOut = 4 +} diff --git a/src/GeneralUpdate.Core/StartupHealth/StartupHealthStore.cs b/src/GeneralUpdate.Core/StartupHealth/StartupHealthStore.cs new file mode 100644 index 00000000..fd11cbd4 --- /dev/null +++ b/src/GeneralUpdate.Core/StartupHealth/StartupHealthStore.cs @@ -0,0 +1,170 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Threading; + +namespace GeneralUpdate.Core.StartupHealth; + +/// +/// Stores explicit startup confirmations and failures for cooperating processes. +/// This store does not launch, monitor, report to a server, or roll back an application. +/// +/// +/// Use a local directory outside the installation and backup trees, writable only by trusted +/// participants. All participants must use the same directory and attempt ID. Retain the +/// directory until no participant can access it; do not delete lock files while in use. +/// Timeouts use the local UTC clock and are recorded when a participant next accesses the attempt. +/// +public sealed class StartupHealthStore +{ + private const int FormatVersion = 1; + private readonly string _root; + + /// Creates a store rooted at a host-controlled, persistent local directory. + public StartupHealthStore(string directory) + { + if (string.IsNullOrWhiteSpace(directory)) + throw new ArgumentException("A persistent directory is required.", nameof(directory)); + _root = Path.GetFullPath(directory); + } + + /// Creates an attempt with a future UTC deadline and returns its unique ID. + public Guid Begin(DateTimeOffset deadline) + { + if (deadline <= DateTimeOffset.UtcNow) + throw new ArgumentOutOfRangeException(nameof(deadline), "The deadline must be in the future."); + + var id = Guid.NewGuid(); + var directory = AttemptDirectory(id); + Directory.CreateDirectory(directory); + WriteAtomically(Path.Combine(directory, "attempt"), writer => + { + writer.Write(FormatVersion); + writer.Write(deadline.UtcDateTime.Ticks); + }); + return id; + } + + /// + /// Reads the outcome, recording a timeout if the deadline has elapsed while still pending. + /// Missing or corrupt attempts and storage failures are reported as exceptions. + /// + public StartupHealthStatus GetStatus(Guid attemptId) => Transition(attemptId, null, out _); + + /// + /// Records an explicit business-health confirmation before the deadline. Returns false if + /// the attempt already has a terminal outcome, including a timeout. + /// + public bool ConfirmHealthy(Guid attemptId) + { + Transition(attemptId, StartupHealthStatus.Healthy, out var changed); + return changed; + } + + /// + /// Records a failed health check or an observed process exit. Returns false if the attempt + /// already has a terminal outcome. Observing an exit is the host's responsibility. + /// + public bool ReportFailure(Guid attemptId, StartupHealthStatus failure) + { + if (failure != StartupHealthStatus.Failed && failure != StartupHealthStatus.ProcessExited) + throw new ArgumentOutOfRangeException(nameof(failure)); + Transition(attemptId, failure, out var changed); + return changed; + } + + private StartupHealthStatus Transition(Guid id, StartupHealthStatus? requested, out bool changed) + { + if (id == Guid.Empty) throw new ArgumentException("An attempt ID is required.", nameof(id)); + var directory = AttemptDirectory(id); + if (!Directory.Exists(directory)) throw new DirectoryNotFoundException($"Startup attempt {id} was not found."); + + using (AcquireLock(Path.Combine(directory, "lock"))) + { + var deadline = ReadDeadline(Path.Combine(directory, "attempt")); + var resultPath = Path.Combine(directory, "result"); + changed = false; + if (File.Exists(resultPath)) return ReadResult(resultPath); + + var result = DateTimeOffset.UtcNow >= deadline ? StartupHealthStatus.TimedOut : requested; + if (!result.HasValue) return StartupHealthStatus.Pending; + + WriteAtomically(resultPath, writer => + { + writer.Write(FormatVersion); + writer.Write((int)result.Value); + }); + changed = result == requested; + return result.Value; + } + } + + private string AttemptDirectory(Guid id) => Path.Combine(_root, id.ToString("N")); + + private static FileStream AcquireLock(string path) + { + var elapsed = Stopwatch.StartNew(); + while (true) + { + try + { + return new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); + } + catch (IOException) when (elapsed.Elapsed < TimeSpan.FromSeconds(5)) + { + Thread.Sleep(10); + } + } + } + + private static DateTimeOffset ReadDeadline(string path) + { + using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) + using (var reader = new BinaryReader(stream)) + { + if (stream.Length != 12 || reader.ReadInt32() != FormatVersion) + throw new InvalidDataException("Invalid startup attempt metadata."); + var ticks = reader.ReadInt64(); + if (ticks < DateTime.MinValue.Ticks || ticks > DateTime.MaxValue.Ticks) + throw new InvalidDataException("Invalid startup attempt deadline."); + return new DateTimeOffset(ticks, TimeSpan.Zero); + } + } + + private static StartupHealthStatus ReadResult(string path) + { + using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) + using (var reader = new BinaryReader(stream)) + { + if (stream.Length != 8 || reader.ReadInt32() != FormatVersion) + throw new InvalidDataException("Invalid startup attempt result."); + var status = (StartupHealthStatus)reader.ReadInt32(); + if (status != StartupHealthStatus.Healthy && status != StartupHealthStatus.Failed && + status != StartupHealthStatus.ProcessExited && status != StartupHealthStatus.TimedOut) + throw new InvalidDataException("Invalid startup attempt outcome."); + return status; + } + } + + private static void WriteAtomically(string path, Action write) + { + var temporary = path + "." + Guid.NewGuid().ToString("N") + ".tmp"; + try + { + using (var stream = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + { + using (var writer = new BinaryWriter(stream, System.Text.Encoding.UTF8, true)) + { + write(writer); + writer.Flush(); + } + stream.Flush(true); + } + File.Move(temporary, path); + } + finally + { + if (File.Exists(temporary)) File.Delete(temporary); + } + } +} diff --git a/tests/CoreTest/CoreTest.csproj b/tests/CoreTest/CoreTest.csproj index 99d514db..d8249d18 100644 --- a/tests/CoreTest/CoreTest.csproj +++ b/tests/CoreTest/CoreTest.csproj @@ -21,6 +21,7 @@ + \ No newline at end of file diff --git a/tests/CoreTest/StartupHealth/StartupHealthStoreTests.cs b/tests/CoreTest/StartupHealth/StartupHealthStoreTests.cs new file mode 100644 index 00000000..7cf638d4 --- /dev/null +++ b/tests/CoreTest/StartupHealth/StartupHealthStoreTests.cs @@ -0,0 +1,145 @@ +using System.Diagnostics; +using System.Runtime.CompilerServices; +using GeneralUpdate.Core.StartupHealth; + +namespace CoreTest.StartupHealth; + +public class StartupHealthStoreTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "startup-health-" + Guid.NewGuid().ToString("N")); + + [Fact] + public void Explicit_confirmation_is_persistent_and_terminal() + { + var store = new StartupHealthStore(_root); + var id = store.Begin(DateTimeOffset.UtcNow.AddMinutes(1)); + Assert.Equal(StartupHealthStatus.Pending, store.GetStatus(id)); + Assert.True(store.ConfirmHealthy(id)); + Assert.False(store.ConfirmHealthy(id)); + Assert.False(store.ReportFailure(id, StartupHealthStatus.Failed)); + Assert.Equal(StartupHealthStatus.Healthy, new StartupHealthStore(_root).GetStatus(id)); + } + + [Theory] + [InlineData(StartupHealthStatus.Failed)] + [InlineData(StartupHealthStatus.ProcessExited)] + public void Failure_is_persistent_and_cannot_be_overwritten(StartupHealthStatus failure) + { + var store = new StartupHealthStore(_root); + var id = store.Begin(DateTimeOffset.UtcNow.AddMinutes(1)); + Assert.True(store.ReportFailure(id, failure)); + Assert.False(store.ConfirmHealthy(id)); + Assert.False(store.ReportFailure(id, failure)); + Assert.Equal(failure, new StartupHealthStore(_root).GetStatus(id)); + } + + [Fact] + public void Deadline_is_enforced_even_without_a_running_monitor() + { + var store = new StartupHealthStore(_root); + var id = store.Begin(DateTimeOffset.UtcNow.AddMilliseconds(200)); + Thread.Sleep(350); + Assert.False(new StartupHealthStore(_root).ConfirmHealthy(id)); + Assert.Equal(StartupHealthStatus.TimedOut, store.GetStatus(id)); + Assert.False(store.ReportFailure(id, StartupHealthStatus.ProcessExited)); + } + + [Fact] + public void Invalid_or_corrupt_state_never_becomes_success() + { + var store = new StartupHealthStore(_root); + Assert.Throws(() => store.Begin(DateTimeOffset.UtcNow.AddSeconds(-1))); + Assert.Throws(() => store.GetStatus(Guid.Empty)); + Assert.Throws(() => store.GetStatus(Guid.NewGuid())); + var id = store.Begin(DateTimeOffset.UtcNow.AddMinutes(1)); + Assert.Throws(() => store.ReportFailure(id, StartupHealthStatus.Healthy)); + File.WriteAllBytes(Path.Combine(_root, id.ToString("N"), "result"), new byte[] { 1 }); + Assert.Throws(() => store.ConfirmHealthy(id)); + } + + [Fact] + public void Interrupted_temporary_write_does_not_count_as_an_outcome() + { + var store = new StartupHealthStore(_root); + var id = store.Begin(DateTimeOffset.UtcNow.AddMinutes(1)); + File.WriteAllBytes(Path.Combine(_root, id.ToString("N"), "result.interrupted.tmp"), new byte[] { 1 }); + Assert.Equal(StartupHealthStatus.Pending, store.GetStatus(id)); + Assert.True(store.ReportFailure(id, StartupHealthStatus.Failed)); + Assert.Equal(StartupHealthStatus.Failed, store.GetStatus(id)); + } + + [Fact] + public void Competing_processes_commit_only_one_terminal_result() + { + var store = new StartupHealthStore(_root); + var id = store.Begin(DateTimeOffset.UtcNow.AddMinutes(1)); + using var healthy = StartProbe(id, "healthy"); + using var failed = StartProbe(id, "failed"); + var healthyOutput = Finish(healthy); + var failedOutput = Finish(failed); + Assert.NotEqual(healthyOutput, failedOutput); + Assert.Contains("changed", new[] { healthyOutput, failedOutput }); + Assert.Contains("unchanged", new[] { healthyOutput, failedOutput }); + Assert.Equal(healthyOutput == "changed" ? StartupHealthStatus.Healthy : StartupHealthStatus.Failed, + store.GetStatus(id)); + } + + [Fact] + public void Crashed_lock_holder_does_not_prevent_recovery() + { + var store = new StartupHealthStore(_root); + var id = store.Begin(DateTimeOffset.UtcNow.AddMinutes(1)); + var ready = Path.Combine(_root, "ready"); + using var process = StartProbe(id, "hold-lock", ready); + try + { + Assert.True(SpinWait.SpinUntil(() => File.Exists(ready) || process.HasExited, TimeSpan.FromSeconds(15))); + if (!File.Exists(ready)) + throw new InvalidOperationException("Probe exited before acquiring the lock: " + process.StandardError.ReadToEnd()); + var report = Task.Run(() => store.ReportFailure(id, StartupHealthStatus.ProcessExited)); + Assert.False(report.Wait(150)); + process.Kill(); + Assert.True(process.WaitForExit(15000)); + Assert.True(report.Wait(15000)); + Assert.True(report.Result); + Assert.Equal(StartupHealthStatus.ProcessExited, new StartupHealthStore(_root).GetStatus(id)); + } + finally + { + if (!process.HasExited) + { + process.Kill(); + process.WaitForExit(); + } + } + } + + private Process StartProbe(Guid id, string operation, string? extra = null) + { + var configuration = new DirectoryInfo(AppContext.BaseDirectory).Parent!.Name; + var helper = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(SourcePath())!, "..", "..", + "StartupHealthProbe", "bin", configuration, "net10.0", "StartupHealthProbe.dll")); + var start = new ProcessStartInfo("dotnet") { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true }; + start.ArgumentList.Add(helper); + start.ArgumentList.Add(_root); + start.ArgumentList.Add(id.ToString()); + start.ArgumentList.Add(operation); + if (extra != null) start.ArgumentList.Add(extra); + return Process.Start(start) ?? throw new InvalidOperationException("Failed to start health probe."); + } + + private static string Finish(Process process) + { + Assert.True(process.WaitForExit(15000)); + var error = process.StandardError.ReadToEnd(); + Assert.True(process.ExitCode == 0, error); + return process.StandardOutput.ReadToEnd().Trim(); + } + + private static string SourcePath([CallerFilePath] string path = "") => path; + + public void Dispose() + { + if (Directory.Exists(_root)) Directory.Delete(_root, true); + } +} diff --git a/tests/StartupHealthProbe/Program.cs b/tests/StartupHealthProbe/Program.cs new file mode 100644 index 00000000..3b895d99 --- /dev/null +++ b/tests/StartupHealthProbe/Program.cs @@ -0,0 +1,29 @@ +using GeneralUpdate.Core.StartupHealth; + +var root = args[0]; +if (args.Length == 2 && args[1] == "roundtrip") +{ + var store = new StartupHealthStore(root); + var attempt = store.Begin(DateTimeOffset.UtcNow.AddMinutes(1)); + if (!store.ConfirmHealthy(attempt) || new StartupHealthStore(root).GetStatus(attempt) != StartupHealthStatus.Healthy) + throw new InvalidOperationException("Startup health roundtrip failed."); + Console.WriteLine("healthy"); + return; +} + +var id = Guid.Parse(args[1]); +if (args[2] == "hold-lock") +{ + using var held = new FileStream(Path.Combine(root, id.ToString("N"), "lock"), + FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); + File.WriteAllText(args[3], "ready"); + Thread.Sleep(Timeout.Infinite); +} +else +{ + var store = new StartupHealthStore(root); + var changed = args[2] == "healthy" + ? store.ConfirmHealthy(id) + : store.ReportFailure(id, StartupHealthStatus.Failed); + Console.WriteLine(changed ? "changed" : "unchanged"); +} diff --git a/tests/StartupHealthProbe/StartupHealthProbe.csproj b/tests/StartupHealthProbe/StartupHealthProbe.csproj new file mode 100644 index 00000000..601478a7 --- /dev/null +++ b/tests/StartupHealthProbe/StartupHealthProbe.csproj @@ -0,0 +1,11 @@ + + + Exe + net10.0 + enable + enable + + + + + From dd84619df8e04cc013f7c2ab843472fc08c1fcdf Mon Sep 17 00:00:00 2001 From: Juster Zhu Date: Sun, 22 Nov 2026 23:38:40 +0800 Subject: [PATCH 2/2] Fix startup health probe discovery in CI Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- src/GeneralUpdate.slnx | 1 + tests/CoreTest/CoreTest.csproj | 2 +- .../StartupHealth/StartupHealthStoreTests.cs | 12 ++++++------ 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/GeneralUpdate.slnx b/src/GeneralUpdate.slnx index ad302e33..350d878e 100644 --- a/src/GeneralUpdate.slnx +++ b/src/GeneralUpdate.slnx @@ -10,6 +10,7 @@ + diff --git a/tests/CoreTest/CoreTest.csproj b/tests/CoreTest/CoreTest.csproj index d8249d18..98368a96 100644 --- a/tests/CoreTest/CoreTest.csproj +++ b/tests/CoreTest/CoreTest.csproj @@ -21,7 +21,7 @@ - + \ No newline at end of file diff --git a/tests/CoreTest/StartupHealth/StartupHealthStoreTests.cs b/tests/CoreTest/StartupHealth/StartupHealthStoreTests.cs index 7cf638d4..e6747787 100644 --- a/tests/CoreTest/StartupHealth/StartupHealthStoreTests.cs +++ b/tests/CoreTest/StartupHealth/StartupHealthStoreTests.cs @@ -1,5 +1,4 @@ using System.Diagnostics; -using System.Runtime.CompilerServices; using GeneralUpdate.Core.StartupHealth; namespace CoreTest.StartupHealth; @@ -116,10 +115,13 @@ public void Crashed_lock_holder_does_not_prevent_recovery() private Process StartProbe(Guid id, string operation, string? extra = null) { - var configuration = new DirectoryInfo(AppContext.BaseDirectory).Parent!.Name; - var helper = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(SourcePath())!, "..", "..", - "StartupHealthProbe", "bin", configuration, "net10.0", "StartupHealthProbe.dll")); + var helper = Path.Combine(AppContext.BaseDirectory, "StartupHealthProbe.dll"); var start = new ProcessStartInfo("dotnet") { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true }; + start.ArgumentList.Add("exec"); + start.ArgumentList.Add("--runtimeconfig"); + start.ArgumentList.Add(Path.Combine(AppContext.BaseDirectory, "CoreTest.runtimeconfig.json")); + start.ArgumentList.Add("--depsfile"); + start.ArgumentList.Add(Path.Combine(AppContext.BaseDirectory, "CoreTest.deps.json")); start.ArgumentList.Add(helper); start.ArgumentList.Add(_root); start.ArgumentList.Add(id.ToString()); @@ -136,8 +138,6 @@ private static string Finish(Process process) return process.StandardOutput.ReadToEnd().Trim(); } - private static string SourcePath([CallerFilePath] string path = "") => path; - public void Dispose() { if (Directory.Exists(_root)) Directory.Delete(_root, true);