Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions .github/workflows/startup-health-aot.yml
Original file line number Diff line number Diff line change
@@ -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 }
53 changes: 52 additions & 1 deletion docs/startup-health-store.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
96 changes: 96 additions & 0 deletions src/GeneralUpdate.Core/StartupHealth/StartupHealthProcess.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

namespace GeneralUpdate.Core.StartupHealth;

/// <summary>
/// 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.
/// </summary>
public sealed class StartupHealthProcess
{
/// <summary>Environment variable containing the trusted health store directory.</summary>
public const string DirectoryVariable = "GENERALUPDATE_STARTUP_HEALTH_DIRECTORY";

/// <summary>Environment variable containing the startup attempt ID.</summary>
public const string AttemptVariable = "GENERALUPDATE_STARTUP_HEALTH_ATTEMPT";

private readonly StartupHealthStore _store;
private readonly string _directory;

/// <summary>Creates a process adapter for the same trusted directory used by the store.</summary>
public StartupHealthProcess(string directory)
{
_store = new StartupHealthStore(directory);
_directory = System.IO.Path.GetFullPath(directory);
}

/// <summary>
/// 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.
/// </summary>
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;
}
}

/// <summary>
/// Waits for explicit confirmation, failure, timeout, or exit of the process returned by
/// <see cref="Start"/>. Cancellation stops observation only; it does not stop the child.
/// </summary>
public async Task<StartupHealthStatus> 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);
}
}

/// <summary>
/// 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.
/// </summary>
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);
}
}
187 changes: 187 additions & 0 deletions tests/CoreTest/StartupHealth/StartupHealthProcessTests.cs
Original file line number Diff line number Diff line change
@@ -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<Win32Exception>(() => 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<InvalidOperationException>(() => 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<OperationCanceledException>(() => 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);
}
}
Loading
Loading