Skip to content
Draft
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
34 changes: 34 additions & 0 deletions .github/workflows/diagnostic-outbox.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,40 @@ jobs:
run: dotnet test tests/CoreTest/CoreTest.csproj -c Release --filter FullyQualifiedName~Diagnostics
- name: Build integration harness
run: dotnet build tests/OutboxConsumerHarness/OutboxConsumerHarness.csproj -c Release
- name: Build all compatible Core targets
run: dotnet build src/GeneralUpdate.Core/GeneralUpdate.Core.csproj -c Release
- name: Publish standalone Native AOT host
run: dotnet publish src/GeneralUpdate.Diagnostics.Host/GeneralUpdate.Diagnostics.Host.csproj -c Release -r ${{ matrix.rid }} -o diagnostic-host-aot
- name: Run default-off host (Windows)
if: runner.os == 'Windows'
run: ./diagnostic-host-aot/GeneralUpdate.Diagnostics.Host.exe
- name: Run default-off host (Linux)
if: runner.os == 'Linux'
run: ./diagnostic-host-aot/GeneralUpdate.Diagnostics.Host
- name: Run enabled native host lifecycle (Linux)
if: runner.os == 'Linux'
shell: bash
run: |
root=$(mktemp -d)
export GENERALUPDATE_DIAGNOSTICS_ENABLED=true
export GENERALUPDATE_DIAGNOSTICS_TENANT=ci-tenant
export GENERALUPDATE_DIAGNOSTICS_APP_KEY=ci-app
export GENERALUPDATE_DIAGNOSTICS_SCAN_SECONDS=0.1
./diagnostic-host-aot/GeneralUpdate.Diagnostics.Host "$root" https://localhost:1/Fault/UploadArtifact > "$root/host.log" 2> "$root/error.log" &
pid=$!
trap 'kill -TERM "$pid" 2>/dev/null || true' EXIT
for i in {1..100}; do
if grep -q ScanCompleted "$root/host.log"; then break; fi
sleep 0.1
done
grep -q ScanCompleted "$root/host.log"
kill -TERM "$pid"
wait "$pid"
grep -q Stopped "$root/host.log"
test ! -s "$root/error.log"
rm "$root/host.log" "$root/error.log"
rmdir "$root"
trap - EXIT
- name: Publish Native AOT smoke
run: dotnet publish tests/OutboxAotSmoke/OutboxAotSmoke.csproj -c Release -r ${{ matrix.rid }} -o outbox-aot
- name: Run Native AOT smoke (Windows)
Expand Down
104 changes: 103 additions & 1 deletion docs/diagnostic-artifact-transport.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
`ArtifactUploadClient` is an opt-in transport for an already prepared Bowl schema 2
crash ZIP. `DiagnosticOutboxConsumer` separately implements the cooperative Bowl
`outboxProtocol: 1` case lifecycle. Neither component is integrated into
`LaunchAsync`; the host explicitly schedules and retries cases.
`LaunchAsync`. The default-off standalone `GeneralUpdate.Diagnostics.Host`
now schedules startup replay and periodic retries independently of upgrades.

The host must provide a stable ZIP snapshot, `manifest.json` at its root, and
matching metadata. Retain the **same ZIP bytes** for retries, including after a
Expand Down Expand Up @@ -76,6 +77,107 @@ during deletion cannot trigger a regenerated upload. The host must also enumerat
the same stripe lock. Tombstones count against Bowl's admission limits until
removed; a cleanup failure can therefore cause exit-code-only degradation.

## Standalone host (default off)

Publish the executable separately from the application and upgrade worker. It
must not be a download/pipeline hook or a child whose completion is awaited by
`LaunchAsync`. Existing update APIs, reports, hooks and IPC are unchanged. A
supervisor starts the diagnostic process after consent/configuration deployment
and restarts it when it exits unexpectedly; Windows service integration is the
supervisor's responsibility (this is a foreground executable, not a Windows
Service). Use .NET 10 for managed deployment, or publish its Native AOT binary:

```powershell
dotnet publish src\GeneralUpdate.Diagnostics.Host -c Release -r win-x64 -o diagnostic-host
# Environment values must come from trusted deployment configuration, never a case manifest.
$env:GENERALUPDATE_DIAGNOSTICS_ENABLED = 'true'
$env:GENERALUPDATE_DIAGNOSTICS_TENANT = 'configured-tenant'
$env:GENERALUPDATE_DIAGNOSTICS_APP_KEY = 'configured-app'
$env:GENERALUPDATE_DIAGNOSTICS_SCAN_SECONDS = '60'
$env:GENERALUPDATE_DIAGNOSTICS_UPLOAD_SECONDS = '30'
.\diagnostic-host\GeneralUpdate.Diagnostics.Host.exe `
'C:\application\fail' 'https://gateway.example/Fault/UploadArtifact'
```

Unset or `false` enablement exits successfully with `Disabled` without checking
arguments, touching the outbox, or making HTTP requests. Any other enablement
value is a configuration error. Enabled mode requires an explicit root, HTTPS
endpoint, nonempty tenant and app key. Scan interval is 0.1 seconds through one
day; upload timeout is positive and at most two minutes. Numeric environment
values use invariant decimal seconds. Options are copied at construction, not
read from evidence. The executable rejects redirects, disables proxies, and uses
normal system TLS trust; it has no certificate-validation bypass. Install the
deployment CA in the OS trust store and secure/authenticate the gateway.

On startup it immediately enumerates version/GUID directories, skips `.locks`
and non-case names, and finishes confirmed tombstones under their stripe lock.
It scans serially, with a full configured interval after each scan, so scans
never overlap and each case has at most one attempt per scan. Recoverable disk,
manifest, HTTP and upload-timeout errors are reported per case/directory and
preserve evidence; malformed cases do not prevent other cases being processed.
A missing root is reported and retried, not created automatically. Directory
chains are checked for links/reparse points before enumeration and consumption;
streaming enumeration checks cancellation between entries. An inaccessible or
changed directory can defer the rest of that directory to the next scan. The
same private-local-filesystem/ACL and protocol-1 deployment prerequisites apply;
these checks do not defeat a hostile local writer racing path replacement.
Legacy unmarked cases remain skipped: the executable offers no legacy override.

`Started`, `ScanStarted`, `ScanCompleted`, `ConfirmedAndDeleted`,
`TombstoneDeleted`, `Deferred` and `Stopped` are timestamped on stdout; errors
include exception type and message on stderr. Paths/messages may contain
sensitive information: protect and retain these logs appropriately. `Deferred`
means busy, incomplete, unmarked or unconfirmed, not success. A failed scan will
still emit `ScanCompleted`; inspect `Error` events, not that marker alone.
Configuration/unexpected process errors exit 1; ordinary scan errors keep
retrying. Ctrl+C and Unix SIGTERM cancel the scan/upload and emit `Stopped`;
supervisors must allow the handler to finish before force-killing. Force-kill
releases OS locks, and next startup replays persisted snapshots/tombstones.
Cancellation cannot interrupt a synchronous filesystem operation or a broken
HTTP handler that ignores its token; shutdown grace must account for this.

Applications with their own long-lived process can instead explicitly construct
`DiagnosticOutboxHost(options, observer, httpClient)` and retain the task from
`StartAsync(shutdownToken)`. `StartAsync` queues work and returns immediately;
await that task only at host shutdown, not in the upgrade lifecycle. The caller
owns the HTTP client and policies and must keep it alive until completion.
Observer callbacks must be quick and thread-safe. Observer failures and
unexpected faults fail the completion task, so callers must observe it. Host
cancellation completes normally; upload timeout is an observable case error.
Do not dynamically change tenant/app/endpoint for an existing outbox.

### No inferred attempt association

Core's version-response/report `RecordId` and IPC do **not** provide a durable
mapping to a Bowl case. `BowlContext` and schema-2 manifests provide no trustworthy
attempt record. Consequently this host sends no `RecordId`/`RecordType`, never
reports an upgrade failure, and does not associate an arbitrary crash with an
upgrade or push. Tenant/app configuration identifies the upload destination,
not a particular attempt.

Only opt in for a dedicated outbox whose ordinary crashes may be uploaded
**without association**. If a deployment requires attempt association, leave
this host disabled for that outbox until a trusted, persistent binding exists
and is fixed before first send. GeneralSpace's duplicate-GUID path checks tenant
and ZIP hash, but does not add or repair record/AppKey associations later; a
successful unassociated first upload cannot be repaired by retrying it with
record fields. Do not fabricate a record from version, current/latest attempt,
process environment, or untrusted manifest data. This PR deliberately does not
implement a record-context API in the absence of a trustworthy source.

### Verification boundary

Diagnostic unit tests cover startup replay, periodic discovery/retry, missing
root recovery, per-case errors, timeout/cancellation, another process holding the
stripe, trusted configuration, no record fields, and tombstone recovery. Native
AOT smoke covers the scheduler and consumer; CI publishes the production host
on Windows and Linux. These use local fixtures/mock HTTP and are **not** evidence
of real Bowl watchdog/dump capture or a deployed GeneralSpace service.
The cross-repository follow-up reuses GeneralSpace #326's
`diagnostic-three-repo.yml`/`eng/diagnostic-three-repo.py` with exact source SHAs
and must separately report real writer/API verification versus complete
watchdog/dump coverage.

The lock is `{fail}/.locks/{first two lowercase GUID hex characters}.lock`,
opened with `FileShare.None` and never deleted. It remains held through snapshot,
upload and cleanup. The required upload timeout is at most two minutes; the HTTP
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,7 @@ private static void RejectLinkIfExists(string path)
throw new InvalidDataException("Outbox links and reparse points are not allowed.");
}

private static void CheckDirectoryChain(string path)
internal static void CheckDirectoryChain(string path)
{
var current = new DirectoryInfo(path);
while (current != null)
Expand Down
169 changes: 169 additions & 0 deletions src/GeneralUpdate.Core/Diagnostics/DiagnosticOutboxHost.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
using System;
using System.IO;
using System.Net.Http;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

namespace GeneralUpdate.Core.Diagnostics;

/// <summary>Explicit configuration for a standalone diagnostic scheduler, disabled by default.</summary>
public sealed class DiagnosticOutboxHostOptions
{
public bool Enabled { get; set; }
public string FailDirectory { get; set; } = string.Empty;
public Uri? Endpoint { get; set; }
public string TenantId { get; set; } = string.Empty;
public string AppKey { get; set; } = string.Empty;
public TimeSpan ScanInterval { get; set; } = TimeSpan.FromMinutes(1);
public TimeSpan UploadTimeout { get; set; } = TimeSpan.FromSeconds(30);
}

public enum DiagnosticOutboxHostStatus
{
Disabled, Started, ScanStarted, ConfirmedAndDeleted, TombstoneDeleted,
Deferred, Error, ScanCompleted, Stopped
}

/// <summary>Scheduler notifications never report update success or failure.</summary>
public sealed class DiagnosticOutboxHostEvent
{
internal DiagnosticOutboxHostEvent(DiagnosticOutboxHostStatus status, string? path = null, Exception? error = null)
{
Status = status;
Path = path;
Error = error;
}

public DiagnosticOutboxHostStatus Status { get; }
public string? Path { get; }
public Exception? Error { get; }
}

/// <summary>
/// Replays on startup and scans periodically without running on the caller's update thread.
/// The caller owns HTTP policies, cancellation, notifications and the returned completion task.
/// </summary>
public sealed class DiagnosticOutboxHost
{
private const string TombstonePrefix = ".generalupdate-uploaded-";
private readonly string _root;
private readonly TimeSpan _interval;
private readonly DiagnosticOutboxConsumer? _consumer;
private readonly Action<DiagnosticOutboxHostEvent> _notify;
private int _started;

public DiagnosticOutboxHost(DiagnosticOutboxHostOptions options,
Action<DiagnosticOutboxHostEvent> notify, HttpClient? httpClient = null)
{
if (options == null) throw new ArgumentNullException(nameof(options));
_notify = notify ?? throw new ArgumentNullException(nameof(notify));
_root = string.Empty;
_interval = options.ScanInterval;
if (!options.Enabled) return;
if (_interval < TimeSpan.FromMilliseconds(100) || _interval > TimeSpan.FromDays(1))
throw new ArgumentOutOfRangeException(nameof(options.ScanInterval));
if (httpClient == null) throw new ArgumentNullException(nameof(httpClient));
var upload = new ArtifactUploadClient(httpClient,
options.Endpoint ?? throw new ArgumentException("An explicit endpoint is required.", nameof(options)),
options.TenantId, options.AppKey);
_consumer = new DiagnosticOutboxConsumer(options.FailDirectory, upload, options.UploadTimeout);
_root = Path.GetFullPath(options.FailDirectory);
}

/// <summary>
/// Starts once and returns immediately. Await the task at shutdown; observer exceptions
/// and unexpected scheduler faults propagate through it. Expected case errors are notified.
/// </summary>
public Task StartAsync(CancellationToken cancellationToken = default)
{
if (Interlocked.Exchange(ref _started, 1) != 0)
throw new InvalidOperationException("The diagnostic host has already been started.");
return Task.Run(() => RunAsync(cancellationToken));
}

private async Task RunAsync(CancellationToken token)
{
if (_consumer == null)
{
Report(DiagnosticOutboxHostStatus.Disabled);
return;
}
Report(DiagnosticOutboxHostStatus.Started);
try
{
while (true)
{
token.ThrowIfCancellationRequested();
Report(DiagnosticOutboxHostStatus.ScanStarted);
try { await ScanAsync(token).ConfigureAwait(false); }
catch (Exception error) when (IsRecoverable(error, token))
{
Report(DiagnosticOutboxHostStatus.Error, _root, error);
}
Report(DiagnosticOutboxHostStatus.ScanCompleted);
await Task.Delay(_interval, token).ConfigureAwait(false);
}
}
catch (OperationCanceledException) when (token.IsCancellationRequested)
{
// Host cancellation is normal shutdown, not an update failure.
}
finally { Report(DiagnosticOutboxHostStatus.Stopped); }
}

private async Task ScanAsync(CancellationToken token)
{
DiagnosticOutboxConsumer.CheckDirectoryChain(_root);
foreach (var versionPath in Directory.EnumerateDirectories(_root))
{
token.ThrowIfCancellationRequested();
var version = Path.GetFileName(versionPath);
if (version.Equals(".locks", StringComparison.OrdinalIgnoreCase)) continue;
try
{
DiagnosticOutboxConsumer.CheckDirectoryChain(versionPath);
foreach (var casePath in Directory.EnumerateDirectories(versionPath))
{
token.ThrowIfCancellationRequested();
var name = Path.GetFileName(casePath);
var tombstone = name.StartsWith(TombstonePrefix, StringComparison.Ordinal);
var id = tombstone ? name.Substring(TombstonePrefix.Length) : name;
if (!Guid.TryParseExact(id, "D", out _)) continue;
try
{
DiagnosticOutboxConsumer.CheckDirectoryChain(casePath);
var deleted = tombstone
? _consumer!.CleanupConfirmedCase(version, id)
: await _consumer!.ProcessCaseAsync(version, id, token).ConfigureAwait(false);
Report(deleted
? (tombstone ? DiagnosticOutboxHostStatus.TombstoneDeleted : DiagnosticOutboxHostStatus.ConfirmedAndDeleted)
: DiagnosticOutboxHostStatus.Deferred, casePath);
}
catch (Exception error) when (IsRecoverable(error, token))
{
Report(DiagnosticOutboxHostStatus.Error, casePath, error);
}
}
}
catch (Exception error) when (IsRecoverable(error, token))
{
Report(DiagnosticOutboxHostStatus.Error, versionPath, error);
}
}
}

private static bool IsRecoverable(Exception error, CancellationToken token) =>
error is IOException || error is InvalidDataException || error is UnauthorizedAccessException ||
error is ArgumentException || error is JsonException || error is HttpRequestException ||
error is OperationCanceledException && !token.IsCancellationRequested;

private void Report(DiagnosticOutboxHostStatus status, string? path = null, Exception? error = null)
{
try { _notify(new DiagnosticOutboxHostEvent(status, path, error)); }
catch (Exception observerError)
{
throw new InvalidOperationException("The diagnostic host observer failed.", observerError);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsAotCompatible>true</IsAotCompatible>
<EnableTrimAnalyzer>true</EnableTrimAnalyzer>
<PublishAot>true</PublishAot>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\GeneralUpdate.Core\GeneralUpdate.Core.csproj" />
</ItemGroup>
</Project>
Loading
Loading