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
28 changes: 28 additions & 0 deletions docs/startup-health-store.md
Original file line number Diff line number Diff line change
@@ -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.
Comment on lines +10 to +11

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.
11 changes: 11 additions & 0 deletions src/GeneralUpdate.Core/StartupHealth/StartupHealthStatus.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
namespace GeneralUpdate.Core.StartupHealth;

/// <summary>Outcome of an explicitly monitored startup attempt.</summary>
public enum StartupHealthStatus
{
Pending = 0,
Healthy = 1,
Failed = 2,
ProcessExited = 3,
TimedOut = 4
}
170 changes: 170 additions & 0 deletions src/GeneralUpdate.Core/StartupHealth/StartupHealthStore.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;

namespace GeneralUpdate.Core.StartupHealth;

/// <summary>
/// Stores explicit startup confirmations and failures for cooperating processes.
/// This store does not launch, monitor, report to a server, or roll back an application.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
public sealed class StartupHealthStore
{
private const int FormatVersion = 1;
private readonly string _root;

/// <summary>Creates a store rooted at a host-controlled, persistent local directory.</summary>
public StartupHealthStore(string directory)
{
if (string.IsNullOrWhiteSpace(directory))
throw new ArgumentException("A persistent directory is required.", nameof(directory));
_root = Path.GetFullPath(directory);
}

/// <summary>Creates an attempt with a future UTC deadline and returns its unique ID.</summary>
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;
}

/// <summary>
/// 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.
/// </summary>
public StartupHealthStatus GetStatus(Guid attemptId) => Transition(attemptId, null, out _);

/// <summary>
/// Records an explicit business-health confirmation before the deadline. Returns false if
/// the attempt already has a terminal outcome, including a timeout.
/// </summary>
public bool ConfirmHealthy(Guid attemptId)
{
Transition(attemptId, StartupHealthStatus.Healthy, out var changed);
return changed;
}

/// <summary>
/// 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.
/// </summary>
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<BinaryWriter> 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);
}
}
}
1 change: 1 addition & 0 deletions src/GeneralUpdate.slnx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
<Project Path="../tests/BowlTest/BowlTest.csproj" />
<Project Path="../tests/ClientTest/ClientTest.csproj" />
<Project Path="../tests/CoreTest/CoreTest.csproj" />
<Project Path="../tests/StartupHealthProbe/StartupHealthProbe.csproj" />
<Project Path="../tests/DifferentialTest/DifferentialTest.csproj" />
<Project Path="../tests/DrivelutionTest/DrivelutionTest.csproj" />
<Project Path="../tests/ExtensionTest/ExtensionTest.csproj" />
Expand Down
1 change: 1 addition & 0 deletions tests/CoreTest/CoreTest.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

<ItemGroup>
<ProjectReference Include="..\..\src\GeneralUpdate.Core\GeneralUpdate.Core.csproj" />
<ProjectReference Include="..\StartupHealthProbe\StartupHealthProbe.csproj" />
</ItemGroup>

</Project>
145 changes: 145 additions & 0 deletions tests/CoreTest/StartupHealth/StartupHealthStoreTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
using System.Diagnostics;
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<ArgumentOutOfRangeException>(() => store.Begin(DateTimeOffset.UtcNow.AddSeconds(-1)));
Assert.Throws<ArgumentException>(() => store.GetStatus(Guid.Empty));
Assert.Throws<DirectoryNotFoundException>(() => store.GetStatus(Guid.NewGuid()));
var id = store.Begin(DateTimeOffset.UtcNow.AddMinutes(1));
Assert.Throws<ArgumentOutOfRangeException>(() => store.ReportFailure(id, StartupHealthStatus.Healthy));
File.WriteAllBytes(Path.Combine(_root, id.ToString("N"), "result"), new byte[] { 1 });
Assert.Throws<InvalidDataException>(() => 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 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());
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();
}

public void Dispose()
{
if (Directory.Exists(_root)) Directory.Delete(_root, true);
}
}
Loading
Loading