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
4 changes: 4 additions & 0 deletions .github/workflows/startup-health-aot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,7 @@ jobs:
$state = Join-Path $env:RUNNER_TEMP 'startup-health-state'
& (Join-Path $output 'StartupHealthProbe.exe') $state roundtrip
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
$ready = Join-Path $env:RUNNER_TEMP 'startup-health-ready'
[System.IO.File]::WriteAllText($ready, 'ready')
& (Join-Path $output 'StartupHealthProbe.exe') native-handoff $state $ready
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
50 changes: 50 additions & 0 deletions docs/startup-health-store.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,3 +77,53 @@ 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.

## Durable handoff (opt-in)

`StartupHealthHandoff` connects the store and process adapter for a cooperating
host. Before calling `Prepare`, the host must generate and durably journal a
unique attempt ID associated with its own update. It can then create the
attempt, start a child, and observe its explicit readiness:

```csharp
var handoff = new StartupHealthHandoff(stateDirectory);
// Persist attemptId and its update association in the host's journal first.
handoff.Prepare(attemptId, DateTimeOffset.UtcNow.AddMinutes(2));
using var child = handoff.Start(attemptId, startInfo); // UseShellExecute = false
var status = await handoff.WaitAsync(attemptId, child, cancellationToken);
```

After a host restart, use the journaled ID with `GetStatus`. If preparation
completed but no launch was claimed, the host may call `Start`. `Start` creates
an exclusive persistent launch claim before starting the process. Competing
handoff launchers cannot both claim it, and a claimed launch must never be
retried, even when the host crashes before actually starting the child. Such
a crash is ambiguous: pending is not proof of either launch or health. Recovery
can observe confirmation or timeout, but cannot infer process exit or safely
reattach. A missing or corrupt attempt is an error, not a fresh attempt.
In particular, interrupted preparation can leave an incomplete attempt; never
reuse its ID. Launch and storage errors are surfaced, not silently retried.

The claim guarantees at-most-once launch only if every participant uses
`StartupHealthHandoff.Start` for that ID and nobody deletes the state. The
lower-level `StartupHealthProcess.Start` does not enforce it. This protocol
assumes a trusted local filesystem with reliable exclusive creation, local
locking and atomic renames; it covers process crashes, not power-loss
durability. The host still owns its journal, update association, cleanup,
child lifetime and any recovery policy. It must not pass the health variables
to unrelated descendants.

This layer is not enabled by configuration and is not connected to the existing
updater or Bowl. It does not record an exact backup, own rollback, publish a
server result, or make the updater's file-application `Success` a health
confirmation. In the existing core path, `ClientStrategy` creates the backup
and sends its path in the process contract; the executing `AbstractStrategy`
attempts restoration on an apply failure only when no earlier version in that
batch succeeded, and can fall back to the latest backup. Separately, the legacy
`BowlBootstrap` can restore on a captured crash in Upgrade mode when
`AutoRestore` is enabled. Thus there is no verified single rollback owner
across all these paths. This handoff adds no restore path; connecting it to a
deployment must first establish one owner, exact snapshot identity, fencing,
and crash-safe idempotent restoration and reporting. Bowl.Host v1's
`filesOnly`/`processAlive` checks are not business readiness and have not been
integrated or validated with this handoff.
57 changes: 57 additions & 0 deletions src/GeneralUpdate.Core/StartupHealth/StartupHealthHandoff.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

namespace GeneralUpdate.Core.StartupHealth;

/// <summary>
/// Opt-in durable attempt creation and at-most-once process launch for cooperating hosts.
/// This does not participate in the updater pipeline or restore files.
/// </summary>
public sealed class StartupHealthHandoff
{
private readonly string _directory;
private readonly StartupHealthStore _store;
private readonly StartupHealthProcess _process;

/// <summary>Uses the same trusted persistent directory as the health store.</summary>
public StartupHealthHandoff(string directory)
{
_store = new StartupHealthStore(directory);
_directory = Path.GetFullPath(directory);
_process = new StartupHealthProcess(_directory);
}

/// <summary>
/// Creates the attempt. Persist the unique ID in the owning host's journal before calling;
/// never reuse an ID even if this method fails or is interrupted.
/// </summary>
public void Prepare(Guid attemptId, DateTimeOffset deadline) => _store.Begin(attemptId, deadline);

/// <summary>
/// Claims the single launch before starting the process. A crash after the claim leaves
/// launch uncertain; do not retry it. All launchers must use this method for the guarantee.
/// </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.");

var claimPath = Path.Combine(_directory, attemptId.ToString("N"), "launch");
using (var claim = new FileStream(claimPath, FileMode.CreateNew, FileAccess.Write, FileShare.None))
claim.Flush(true);
return _process.Start(attemptId, startInfo);
}

/// <summary>Reads the persisted outcome after a host restart; it does not infer process exit.</summary>
public StartupHealthStatus GetStatus(Guid attemptId) => _store.GetStatus(attemptId);

/// <summary>Observes the child returned by this host's <see cref="Start"/> call.</summary>
public Task<StartupHealthStatus> WaitAsync(Guid attemptId, Process process, CancellationToken cancellationToken = default)
=> _process.WaitAsync(attemptId, process, cancellationToken);
}
16 changes: 14 additions & 2 deletions src/GeneralUpdate.Core/StartupHealth/StartupHealthStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,18 +31,30 @@ public StartupHealthStore(string directory)
/// <summary>Creates an attempt with a future UTC deadline and returns its unique ID.</summary>
public Guid Begin(DateTimeOffset deadline)
{
var id = Guid.NewGuid();
Begin(id, deadline);
return id;
}

/// <summary>
/// Creates an attempt under a caller-selected ID. The caller must durably retain the ID
/// before creation; an ID must never be reused, even if creation is interrupted.
/// </summary>
public void Begin(Guid id, DateTimeOffset deadline)
{
if (id == Guid.Empty) throw new ArgumentException("An attempt ID is required.", nameof(id));
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);
using (var claim = new FileStream(Path.Combine(directory, "creation"), FileMode.CreateNew, FileAccess.Write, FileShare.None))
claim.Flush(true);
WriteAtomically(Path.Combine(directory, "attempt"), writer =>
{
writer.Write(FormatVersion);
writer.Write(deadline.UtcDateTime.Ticks);
});
return id;
}

/// <summary>
Expand Down
177 changes: 177 additions & 0 deletions tests/CoreTest/StartupHealth/StartupHealthHandoffTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
using System.Diagnostics;
using GeneralUpdate.Core.StartupHealth;

namespace CoreTest.StartupHealth;

public class StartupHealthHandoffTests : IDisposable
{
private readonly string _root = Path.Combine(Path.GetTempPath(), "startup-handoff-" + Guid.NewGuid().ToString("N"));

[Fact]
public async Task Handoff_launches_child_and_requires_explicit_readiness()
{
var id = Guid.NewGuid();
var handoff = new StartupHealthHandoff(_root);
handoff.Prepare(id, DateTimeOffset.UtcNow.AddSeconds(30));
var ready = Path.Combine(_root, "ready");
File.WriteAllText(ready, "ready");
using var child = handoff.Start(id, Probe("business-ready", ready));
Assert.Equal(StartupHealthStatus.Healthy, await handoff.WaitAsync(id, child));
Assert.True(child.WaitForExit(15000));
Assert.Equal(0, child.ExitCode);
Assert.Equal(StartupHealthStatus.Healthy, new StartupHealthHandoff(_root).GetStatus(id));
}

[Fact]
public void Restart_after_prepare_can_start_but_cannot_recreate_attempt()
{
var id = Guid.NewGuid();
var marker = Path.Combine(_root, "prepared");
using var host = Process.Start(Probe("handoff-prepare", _root, id.ToString("D"), marker))!;
try
{
Assert.True(SpinWait.SpinUntil(() => File.Exists(marker) || host.HasExited, TimeSpan.FromSeconds(15)));
Assert.True(File.Exists(marker));
Stop(host);
var handoff = new StartupHealthHandoff(_root);
Assert.Equal(StartupHealthStatus.Pending, handoff.GetStatus(id));
Assert.Throws<IOException>(() => handoff.Prepare(id, DateTimeOffset.UtcNow.AddSeconds(30)));
using var child = handoff.Start(id, Probe("wait"));
try { Assert.False(child.HasExited); }
finally { Stop(child); }
}
finally { Stop(host); }
}

[Fact]
public void Killed_launcher_cannot_be_relaunched_and_does_not_imply_exit()
{
var id = Guid.NewGuid();
var handoff = new StartupHealthHandoff(_root);
handoff.Prepare(id, DateTimeOffset.UtcNow.AddSeconds(30));
var pidFile = Path.Combine(_root, "pid");
using var host = Process.Start(Host(id, pidFile))!;
Process? child = null;
try
{
Assert.True(SpinWait.SpinUntil(() => File.Exists(pidFile) || host.HasExited, TimeSpan.FromSeconds(15)));
Assert.True(File.Exists(pidFile));
child = Process.GetProcessById(int.Parse(File.ReadAllText(pidFile)));
Stop(host);
var recovered = new StartupHealthHandoff(_root);
Assert.Equal(StartupHealthStatus.Pending, recovered.GetStatus(id));
Assert.False(child.HasExited);
Assert.Throws<IOException>(() => recovered.Start(id, Probe("wait")));
Assert.Equal(StartupHealthStatus.Pending, recovered.GetStatus(id));
}
finally
{
if (child != null) { Stop(child); child.Dispose(); }
Stop(host);
}
}

[Fact]
public void Interrupted_launch_claim_is_not_retried()
{
var id = Guid.NewGuid();
var handoff = new StartupHealthHandoff(_root);
handoff.Prepare(id, DateTimeOffset.UtcNow.AddSeconds(30));
File.WriteAllBytes(Path.Combine(_root, id.ToString("N"), "launch"), Array.Empty<byte>());
Assert.Throws<IOException>(() => new StartupHealthHandoff(_root).Start(id, Probe("wait")));
Assert.Equal(StartupHealthStatus.Pending, handoff.GetStatus(id));
}

[Fact]
public void Interrupted_creation_is_not_reinitialized()
{
var id = Guid.NewGuid();
var attemptDir = Path.Combine(_root, id.ToString("N"));
Directory.CreateDirectory(attemptDir);
File.WriteAllBytes(Path.Combine(attemptDir, "creation"), Array.Empty<byte>());
var handoff = new StartupHealthHandoff(_root);
Assert.Throws<IOException>(() => handoff.Prepare(id, DateTimeOffset.UtcNow.AddSeconds(30)));
Assert.Throws<FileNotFoundException>(() => handoff.GetStatus(id));
}

[Fact]
public void Restart_records_timeout_without_assuming_the_child_is_healthy()
{
var id = Guid.NewGuid();
var handoff = new StartupHealthHandoff(_root);
handoff.Prepare(id, DateTimeOffset.UtcNow.AddMilliseconds(200));
Thread.Sleep(350);
Assert.Equal(StartupHealthStatus.TimedOut, new StartupHealthHandoff(_root).GetStatus(id));
Assert.Throws<InvalidOperationException>(() => handoff.Start(id, Probe("wait")));
}

[Fact]
public void Failed_launch_is_persisted_and_cannot_be_retried()
{
var id = Guid.NewGuid();
var handoff = new StartupHealthHandoff(_root);
handoff.Prepare(id, DateTimeOffset.UtcNow.AddSeconds(30));
Assert.Throws<System.ComponentModel.Win32Exception>(() => handoff.Start(id,
new ProcessStartInfo(Path.Combine(_root, "missing")) { UseShellExecute = false }));
Assert.Equal(StartupHealthStatus.Failed, new StartupHealthHandoff(_root).GetStatus(id));
Assert.Throws<InvalidOperationException>(() => handoff.Start(id, Probe("wait")));
}

[Fact]
public void Competing_launcher_processes_cannot_both_start()
{
var id = Guid.NewGuid();
var handoff = new StartupHealthHandoff(_root);
handoff.Prepare(id, DateTimeOffset.UtcNow.AddSeconds(30));
var firstPid = Path.Combine(_root, "pid1");
var secondPid = Path.Combine(_root, "pid2");
using var first = Process.Start(Host(id, firstPid))!;
using var second = Process.Start(Host(id, secondPid))!;
Process? child = null;
try
{
Assert.True(SpinWait.SpinUntil(
() => (File.Exists(firstPid) && second.HasExited) || (File.Exists(secondPid) && first.HasExited),
TimeSpan.FromSeconds(15)));
Assert.NotEqual(File.Exists(firstPid), File.Exists(secondPid));
var loser = File.Exists(firstPid) ? second : first;
Assert.NotEqual(0, loser.ExitCode);
child = Process.GetProcessById(int.Parse(File.ReadAllText(File.Exists(firstPid) ? firstPid : secondPid)));
Assert.Equal(StartupHealthStatus.Pending, handoff.GetStatus(id));
}
finally
{
if (child != null) { Stop(child); child.Dispose(); }
Stop(first);
Stop(second);
}
}

private ProcessStartInfo Host(Guid id, string pidFile) => Probe("handoff-host", _root, id.ToString("D"), pidFile,
Path.Combine(AppContext.BaseDirectory, "StartupHealthProbe.dll"),
Path.Combine(AppContext.BaseDirectory, "CoreTest.runtimeconfig.json"),
Path.Combine(AppContext.BaseDirectory, "CoreTest.deps.json"));

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(Path.Combine(AppContext.BaseDirectory, "CoreTest.runtimeconfig.json"));
start.ArgumentList.Add("--depsfile");
start.ArgumentList.Add(Path.Combine(AppContext.BaseDirectory, "CoreTest.deps.json"));
start.ArgumentList.Add(Path.Combine(AppContext.BaseDirectory, "StartupHealthProbe.dll"));
foreach (var arg in args) start.ArgumentList.Add(arg);
return start;
}

private static void Stop(Process process)
{
if (!process.HasExited) { process.Kill(); process.WaitForExit(); }
}

public void Dispose()
{
if (Directory.Exists(_root)) Directory.Delete(_root, true);
}
}
41 changes: 41 additions & 0 deletions tests/StartupHealthProbe/Program.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,47 @@
using GeneralUpdate.Core.StartupHealth;
using System.Diagnostics;

if (args.Length == 3 && args[0] == "native-handoff")
{
var handoff = new StartupHealthHandoff(args[1]);
var nativeId = Guid.NewGuid();
handoff.Prepare(nativeId, DateTimeOffset.UtcNow.AddMinutes(1));
var start = new ProcessStartInfo(Environment.ProcessPath!) { UseShellExecute = false };
start.ArgumentList.Add("business-ready");
start.ArgumentList.Add(args[2]);
using var child = handoff.Start(nativeId, start);
if (await handoff.WaitAsync(nativeId, child) != StartupHealthStatus.Healthy)
throw new InvalidOperationException("Native handoff failed.");
Console.WriteLine("healthy");
return;
}

if (args.Length == 4 && args[0] == "handoff-prepare")
{
new StartupHealthHandoff(args[1]).Prepare(Guid.Parse(args[2]), DateTimeOffset.UtcNow.AddSeconds(30));
File.WriteAllText(args[3], "prepared");
Thread.Sleep(Timeout.Infinite);
return;
}

if (args.Length == 7 && args[0] == "handoff-host")
{
var handoff = new StartupHealthHandoff(args[1]);
var handoffId = 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 = handoff.Start(handoffId, start);
File.WriteAllText(args[3], child.Id.ToString());
await handoff.WaitAsync(handoffId, child);
return;
}

if (args.Length == 1 && args[0] == "disabled")
{
if (StartupHealthProcess.ConfirmCurrentProcess())
Expand Down
Loading