From 59af7951458727e128b440cab8a82eef0500dec2 Mon Sep 17 00:00:00 2001 From: Juster Zhu Date: Sun, 22 Nov 2026 23:54:53 +0800 Subject: [PATCH] Add opt-in startup readiness process adapter Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/workflows/startup-health-aot.yml | 26 +++ docs/startup-health-store.md | 53 ++++- .../StartupHealth/StartupHealthProcess.cs | 96 +++++++++ .../StartupHealthProcessTests.cs | 187 ++++++++++++++++++ tests/StartupHealthProbe/Program.cs | 58 +++++- 5 files changed, 417 insertions(+), 3 deletions(-) create mode 100644 .github/workflows/startup-health-aot.yml create mode 100644 src/GeneralUpdate.Core/StartupHealth/StartupHealthProcess.cs create mode 100644 tests/CoreTest/StartupHealth/StartupHealthProcessTests.cs diff --git a/.github/workflows/startup-health-aot.yml b/.github/workflows/startup-health-aot.yml new file mode 100644 index 00000000..27b39ad8 --- /dev/null +++ b/.github/workflows/startup-health-aot.yml @@ -0,0 +1,26 @@ +name: Startup health Native AOT + +on: + pull_request: + paths: + - 'src/GeneralUpdate.Core/StartupHealth/**' + - 'tests/StartupHealthProbe/**' + - '.github/workflows/startup-health-aot.yml' + +jobs: + native-aot: + runs-on: windows-latest + steps: + - uses: actions/checkout@v6 + - uses: actions/setup-dotnet@v5 + with: + dotnet-version: '10.0.x' + - name: Publish and exercise readiness confirmation + shell: pwsh + run: | + $output = Join-Path $env:RUNNER_TEMP 'startup-health-aot' + dotnet publish tests\StartupHealthProbe\StartupHealthProbe.csproj -c Release -r win-x64 --self-contained true -p:PublishAot=true -p:TargetFrameworks=net10.0 -p:TargetFramework=net10.0 -o $output + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + $state = Join-Path $env:RUNNER_TEMP 'startup-health-state' + & (Join-Path $output 'StartupHealthProbe.exe') $state roundtrip + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } diff --git a/docs/startup-health-store.md b/docs/startup-health-store.md index 8df87ee4..7bd4623d 100644 --- a/docs/startup-health-store.md +++ b/docs/startup-health-store.md @@ -20,9 +20,60 @@ 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 +monitor processes by itself, 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. + +## Explicit process integration + +`StartupHealthProcess` is a separate opt-in adapter, not an update-pipeline +switch. A host that owns a new application process may create a store attempt, +persist its ID in its own durable journal, and then start and observe the child: + +```csharp +var store = new StartupHealthStore(stateDirectory); +var id = store.Begin(DateTimeOffset.UtcNow.AddMinutes(2)); +// Persist id before starting the process. +var supervisor = new StartupHealthProcess(stateDirectory); +var start = new ProcessStartInfo(applicationPath) { UseShellExecute = false }; +using var child = supervisor.Start(id, start); +var status = await supervisor.WaitAsync(id, child, cancellationToken); +``` + +In the updated application, call +`StartupHealthProcess.ConfirmCurrentProcess()` **only after application-owned +business readiness checks have passed**. It returns false when not enabled or +when the attempt is already terminal; an incomplete environment is an error. +Starting a process and surviving a time window never confirm readiness. A +failed process creation records `Failed`; an observed exit before confirmation +records `ProcessExited`; the deadline records `TimedOut`. These outcomes are +distinct from file application success. Cancellation only stops observation; +it does not kill the child or change the attempt. The caller owns the process +and must decide how to stop it safely. + +After a host crash, reopen the persisted ID using `GetStatus`. A confirmation +survives restart, and a pending attempt eventually times out even if no host was +running. A restarted host cannot infer process exit or safely reattach from an +attempt ID alone; `WaitAsync` is only for the process returned by `Start` in the +same host. This adapter does not provide an exclusive launch lease, a durable +process identity, or crash-safe launch deduplication. Never launch the same +attempt twice. Storage errors and inability to inspect a process are errors, +not evidence of failed health. + +The child receives the store path and ID via its environment; neither is an +authentication credential. Only trusted processes with access to the protected +state directory may participate. Callers must also ensure unrelated child +processes do not inherit and use these variables. + +This adapter is **not wired into** the existing GeneralUpdate updater, +Bowl.Host v1, or server reports. Bowl.Host v1's `filesOnly` and `processAlive` +verification do not consume this readiness signal. The current updater can +report `Success` before application launch; it must not be interpreted by a +server as business health. Do not combine this adapter with automatic rollback +or claim an end-to-end health guarantee until the host protocol, reporting +semantics, a single rollback owner, exact snapshot identity, process fencing, +and idempotent restart recovery are coordinated. Existing behavior remains +unchanged when this adapter is not explicitly used. diff --git a/src/GeneralUpdate.Core/StartupHealth/StartupHealthProcess.cs b/src/GeneralUpdate.Core/StartupHealth/StartupHealthProcess.cs new file mode 100644 index 00000000..432aba19 --- /dev/null +++ b/src/GeneralUpdate.Core/StartupHealth/StartupHealthProcess.cs @@ -0,0 +1,96 @@ +using System; +using System.Diagnostics; +using System.Threading; +using System.Threading.Tasks; + +namespace GeneralUpdate.Core.StartupHealth; + +/// +/// Opt-in process launch and observation for a previously created startup attempt. +/// This API does not participate in the update pipeline, report success, or restore files. +/// +public sealed class StartupHealthProcess +{ + /// Environment variable containing the trusted health store directory. + public const string DirectoryVariable = "GENERALUPDATE_STARTUP_HEALTH_DIRECTORY"; + + /// Environment variable containing the startup attempt ID. + public const string AttemptVariable = "GENERALUPDATE_STARTUP_HEALTH_ATTEMPT"; + + private readonly StartupHealthStore _store; + private readonly string _directory; + + /// Creates a process adapter for the same trusted directory used by the store. + public StartupHealthProcess(string directory) + { + _store = new StartupHealthStore(directory); + _directory = System.IO.Path.GetFullPath(directory); + } + + /// + /// Starts a child with the attempt identity in its environment. The caller must persist the + /// attempt ID before calling this method and must not launch the same attempt twice. + /// + public Process Start(Guid attemptId, ProcessStartInfo startInfo) + { + if (startInfo == null) throw new ArgumentNullException(nameof(startInfo)); + if (startInfo.UseShellExecute) + throw new ArgumentException("Shell execution cannot pass the health environment.", nameof(startInfo)); + if (_store.GetStatus(attemptId) != StartupHealthStatus.Pending) + throw new InvalidOperationException("The startup attempt is already terminal."); + + startInfo.Environment[DirectoryVariable] = _directory; + startInfo.Environment[AttemptVariable] = attemptId.ToString("D"); + try + { + return Process.Start(startInfo) ?? throw new InvalidOperationException("Failed to start the application."); + } + catch (Exception launchError) + { + try + { + _store.ReportFailure(attemptId, StartupHealthStatus.Failed); + } + catch (Exception stateError) + { + throw new AggregateException("Process launch and recording its failure both failed.", launchError, stateError); + } + throw; + } + } + + /// + /// Waits for explicit confirmation, failure, timeout, or exit of the process returned by + /// . Cancellation stops observation only; it does not stop the child. + /// + public async Task WaitAsync(Guid attemptId, Process process, CancellationToken cancellationToken = default) + { + if (process == null) throw new ArgumentNullException(nameof(process)); + while (true) + { + cancellationToken.ThrowIfCancellationRequested(); + var status = _store.GetStatus(attemptId); + if (status != StartupHealthStatus.Pending) return status; + if (process.HasExited) + { + _store.ReportFailure(attemptId, StartupHealthStatus.ProcessExited); + return _store.GetStatus(attemptId); + } + await Task.Delay(100, cancellationToken).ConfigureAwait(false); + } + } + + /// + /// Called by the child only after its business readiness checks pass. Returns false when + /// monitoring is not enabled or the attempt already has a terminal outcome. + /// + public static bool ConfirmCurrentProcess() + { + var directory = Environment.GetEnvironmentVariable(DirectoryVariable); + var attempt = Environment.GetEnvironmentVariable(AttemptVariable); + if (directory == null && attempt == null) return false; + if (string.IsNullOrWhiteSpace(directory) || !Guid.TryParseExact(attempt, "D", out var id) || id == Guid.Empty) + throw new InvalidOperationException("Incomplete or invalid startup health environment."); + return new StartupHealthStore(directory).ConfirmHealthy(id); + } +} diff --git a/tests/CoreTest/StartupHealth/StartupHealthProcessTests.cs b/tests/CoreTest/StartupHealth/StartupHealthProcessTests.cs new file mode 100644 index 00000000..af4f6782 --- /dev/null +++ b/tests/CoreTest/StartupHealth/StartupHealthProcessTests.cs @@ -0,0 +1,187 @@ +using System.Diagnostics; +using System.ComponentModel; +using GeneralUpdate.Core.StartupHealth; + +namespace CoreTest.StartupHealth; + +public class StartupHealthProcessTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "startup-process-" + Guid.NewGuid().ToString("N")); + + [Fact] + public async Task Child_explicitly_confirms_business_readiness() + { + var store = new StartupHealthStore(_root); + var id = store.Begin(DateTimeOffset.UtcNow.AddSeconds(30)); + var host = new StartupHealthProcess(_root); + var readinessFile = Path.Combine(_root, "business-ready"); + File.WriteAllText(readinessFile, "ready"); + using var child = host.Start(id, Probe("business-ready", readinessFile)); + Assert.Equal(StartupHealthStatus.Healthy, await host.WaitAsync(id, child)); + Assert.True(child.WaitForExit(15000)); + Assert.Equal(0, child.ExitCode); + Assert.Equal(StartupHealthStatus.Healthy, new StartupHealthStore(_root).GetStatus(id)); + } + + [Fact] + public async Task Failed_business_check_does_not_confirm() + { + var store = new StartupHealthStore(_root); + var id = store.Begin(DateTimeOffset.UtcNow.AddSeconds(30)); + var host = new StartupHealthProcess(_root); + var start = Probe("business-ready", Path.Combine(_root, "missing-ready-file")); + start.RedirectStandardError = true; + using var child = host.Start(id, start); + Assert.Equal(StartupHealthStatus.ProcessExited, await host.WaitAsync(id, child)); + Assert.Contains("business readiness check failed", child.StandardError.ReadToEnd()); + } + + [Fact] + public async Task Exit_without_confirmation_is_not_healthy() + { + var store = new StartupHealthStore(_root); + var id = store.Begin(DateTimeOffset.UtcNow.AddSeconds(30)); + var host = new StartupHealthProcess(_root); + using var child = host.Start(id, Probe("exit")); + Assert.Equal(StartupHealthStatus.ProcessExited, await host.WaitAsync(id, child)); + } + + [Fact] + public async Task Running_without_confirmation_times_out() + { + var store = new StartupHealthStore(_root); + var id = store.Begin(DateTimeOffset.UtcNow.AddSeconds(2)); + var host = new StartupHealthProcess(_root); + using var child = host.Start(id, Probe("wait")); + try + { + Assert.Equal(StartupHealthStatus.TimedOut, await host.WaitAsync(id, child)); + Assert.False(child.HasExited); + Assert.False(store.ConfirmHealthy(id)); + } + finally { Stop(child); } + } + + [Fact] + public void Process_creation_failure_is_persisted() + { + var store = new StartupHealthStore(_root); + var id = store.Begin(DateTimeOffset.UtcNow.AddSeconds(30)); + var host = new StartupHealthProcess(_root); + Assert.Throws(() => host.Start(id, + new ProcessStartInfo(Path.Combine(_root, "missing-executable")) { UseShellExecute = false })); + Assert.Equal(StartupHealthStatus.Failed, new StartupHealthStore(_root).GetStatus(id)); + } + + [Fact] + public void Terminal_attempt_cannot_be_started_again() + { + var store = new StartupHealthStore(_root); + var id = store.Begin(DateTimeOffset.UtcNow.AddSeconds(30)); + Assert.True(store.ReportFailure(id, StartupHealthStatus.Failed)); + var host = new StartupHealthProcess(_root); + Assert.Throws(() => host.Start(id, Probe("wait"))); + Assert.Equal(StartupHealthStatus.Failed, store.GetStatus(id)); + } + + [Fact] + public void No_environment_means_monitoring_is_disabled() + { + var start = Probe("disabled"); + start.Environment.Remove(StartupHealthProcess.DirectoryVariable); + start.Environment.Remove(StartupHealthProcess.AttemptVariable); + using var child = Process.Start(start)!; + Assert.True(child.WaitForExit(15000)); + Assert.Equal(0, child.ExitCode); + Assert.False(Directory.Exists(_root)); + } + + [Fact] + public async Task Cancellation_does_not_change_the_attempt_or_kill_the_child() + { + var store = new StartupHealthStore(_root); + var id = store.Begin(DateTimeOffset.UtcNow.AddSeconds(30)); + var host = new StartupHealthProcess(_root); + using var child = host.Start(id, Probe("wait")); + try + { + using var cts = new CancellationTokenSource(200); + await Assert.ThrowsAnyAsync(() => host.WaitAsync(id, child, cts.Token)); + Assert.Equal(StartupHealthStatus.Pending, store.GetStatus(id)); + Assert.False(child.HasExited); + } + finally { Stop(child); } + } + + [Fact] + public void Killed_host_can_reopen_attempt_without_inventing_an_exit() + { + var store = new StartupHealthStore(_root); + var id = store.Begin(DateTimeOffset.UtcNow.AddSeconds(15)); + var pidFile = Path.Combine(_root, "child-pid"); + var start = Probe("host", _root, id.ToString("D"), pidFile, ProbePath(), + RuntimeConfigPath(), DepsPath()); + using var host = Process.Start(start)!; + Process? child = null; + try + { + Assert.True(SpinWait.SpinUntil(() => File.Exists(pidFile) || host.HasExited, TimeSpan.FromSeconds(10))); + Assert.True(File.Exists(pidFile), "Host exited before publishing the child PID."); + child = Process.GetProcessById(int.Parse(File.ReadAllText(pidFile))); + Stop(host); + Assert.Equal("Pending", ReadStatusInNewProcess(id)); + Assert.False(child.HasExited); + Assert.True(SpinWait.SpinUntil( + () => new StartupHealthStore(_root).GetStatus(id) == StartupHealthStatus.TimedOut, + TimeSpan.FromSeconds(20))); + Assert.Equal("TimedOut", ReadStatusInNewProcess(id)); + } + finally + { + if (child != null) { Stop(child); child.Dispose(); } + Stop(host); + } + } + + private static ProcessStartInfo Probe(params string[] args) + { + var start = new ProcessStartInfo("dotnet") { UseShellExecute = false }; + start.ArgumentList.Add("exec"); + start.ArgumentList.Add("--runtimeconfig"); + start.ArgumentList.Add(RuntimeConfigPath()); + start.ArgumentList.Add("--depsfile"); + start.ArgumentList.Add(DepsPath()); + start.ArgumentList.Add(ProbePath()); + foreach (var arg in args) start.ArgumentList.Add(arg); + return start; + } + + private string ReadStatusInNewProcess(Guid id) + { + var start = Probe(_root, id.ToString("D"), "status"); + start.RedirectStandardOutput = true; + using var process = Process.Start(start)!; + var output = process.StandardOutput.ReadToEnd(); + Assert.True(process.WaitForExit(15000)); + Assert.Equal(0, process.ExitCode); + return output.Trim(); + } + + private static string ProbePath() => Path.Combine(AppContext.BaseDirectory, "StartupHealthProbe.dll"); + private static string RuntimeConfigPath() => Path.Combine(AppContext.BaseDirectory, "CoreTest.runtimeconfig.json"); + private static string DepsPath() => Path.Combine(AppContext.BaseDirectory, "CoreTest.deps.json"); + + private static void Stop(Process process) + { + if (!process.HasExited) + { + process.Kill(); + process.WaitForExit(); + } + } + + public void Dispose() + { + if (Directory.Exists(_root)) Directory.Delete(_root, true); + } +} diff --git a/tests/StartupHealthProbe/Program.cs b/tests/StartupHealthProbe/Program.cs index 3b895d99..39169e1c 100644 --- a/tests/StartupHealthProbe/Program.cs +++ b/tests/StartupHealthProbe/Program.cs @@ -1,18 +1,72 @@ using GeneralUpdate.Core.StartupHealth; +using System.Diagnostics; + +if (args.Length == 1 && args[0] == "disabled") +{ + if (StartupHealthProcess.ConfirmCurrentProcess()) + throw new InvalidOperationException("Monitoring was unexpectedly enabled."); + return; +} + +if (args.Length == 7 && args[0] == "host") +{ + var host = new StartupHealthProcess(args[1]); + var attempt = Guid.Parse(args[2]); + var start = new ProcessStartInfo("dotnet") { UseShellExecute = false }; + start.ArgumentList.Add("exec"); + start.ArgumentList.Add("--runtimeconfig"); + start.ArgumentList.Add(args[5]); + start.ArgumentList.Add("--depsfile"); + start.ArgumentList.Add(args[6]); + start.ArgumentList.Add(args[4]); + start.ArgumentList.Add("wait"); + using var child = host.Start(attempt, start); + File.WriteAllText(args[3], child.Id.ToString()); + await host.WaitAsync(attempt, child); + return; +} + +if (args.Length == 2 && args[0] == "business-ready") +{ + if (!File.Exists(args[1]) || File.ReadAllText(args[1]) != "ready") + { + Console.Error.WriteLine("The business readiness check failed."); + Environment.ExitCode = 1; + return; + } + if (!StartupHealthProcess.ConfirmCurrentProcess()) + throw new InvalidOperationException("Readiness confirmation was not recorded."); + return; +} + +if (args.Length == 1 && args[0] == "exit") + return; + +if (args.Length == 1 && args[0] == "wait") +{ + Thread.Sleep(Timeout.Infinite); + return; +} 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) + Environment.SetEnvironmentVariable(StartupHealthProcess.DirectoryVariable, root); + Environment.SetEnvironmentVariable(StartupHealthProcess.AttemptVariable, attempt.ToString("D")); + if (!StartupHealthProcess.ConfirmCurrentProcess() || 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") +if (args[2] == "status") +{ + Console.WriteLine(new StartupHealthStore(root).GetStatus(id)); +} +else if (args[2] == "hold-lock") { using var held = new FileStream(Path.Combine(root, id.ToString("N"), "lock"), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);