fix(audit-log): retention loop absorbs shutdown cancellation instead of faulting host StopAsync (plan R2-04 T12)

This commit is contained in:
Joseph Doherty
2026-07-13 10:28:03 -04:00
parent 8f46b6cec2
commit c573d8cac6
2 changed files with 60 additions and 18 deletions
@@ -61,32 +61,42 @@ public sealed class SiteAuditRetentionService : IHostedService, IDisposable
private async Task RunLoopAsync(CancellationToken ct)
{
// InitialDelay before the first purge — short so a daily-recycled node
// still purges soon after start rather than waiting a full interval it may
// never reach.
try
{
await Task.Delay(_options.InitialDelay, ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
return;
}
await SafePurgeAsync(ct).ConfigureAwait(false);
while (!ct.IsCancellationRequested)
{
// InitialDelay before the first purge — short so a daily-recycled node
// still purges soon after start rather than waiting a full interval it may
// never reach.
try
{
await Task.Delay(_options.ResolvedPurgeInterval, ct).ConfigureAwait(false);
await Task.Delay(_options.InitialDelay, ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
break;
return;
}
await SafePurgeAsync(ct).ConfigureAwait(false);
while (!ct.IsCancellationRequested)
{
try
{
await Task.Delay(_options.ResolvedPurgeInterval, ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
break;
}
await SafePurgeAsync(ct).ConfigureAwait(false);
}
}
catch (OperationCanceledException)
{
// Shutdown landed mid-purge: SafePurgeAsync rethrows OCE by design so the purge
// aborts promptly, but the loop task must complete CLEANLY — StopAsync hands
// _loop straight to the host, and a canceled task there is shutdown-log noise
// (arch-review 04 round 2, R7). Cancellation here IS the clean exit.
}
}
@@ -63,6 +63,29 @@ public class SiteAuditRetentionServiceTests
Assert.True(queue.PurgeCalls.Count >= 2);
}
[Fact]
public async Task StopAsync_MidPurge_CompletesCleanly_WithoutSurfacingCancellation()
{
// PurgeExpiredAsync blocks until cancelled, so shutdown lands mid-purge: SafePurgeAsync
// rethrows the OCE by design (abort the purge promptly), but the loop task must still
// complete CLEANLY — StopAsync hands _loop straight to the host, and a canceled task
// there is shutdown-log noise (arch-review 04 round 2, R7).
var queue = new RecordingSiteAuditQueue { BlockUntilCancelled = true };
var options = Options.Create(new SiteAuditRetentionOptions
{
RetentionDays = 7,
PurgeInterval = TimeSpan.FromHours(24),
InitialDelay = TimeSpan.Zero,
});
using var svc = new SiteAuditRetentionService(queue, options, NullLogger<SiteAuditRetentionService>.Instance);
await svc.StartAsync(CancellationToken.None);
await WaitUntilAsync(() => queue.PurgeCalls.Count >= 1, TimeSpan.FromSeconds(5));
// Must NOT throw TaskCanceledException back into the host's shutdown path.
await svc.StopAsync(CancellationToken.None);
}
private static async Task WaitUntilAsync(Func<bool> condition, TimeSpan timeout)
{
var sw = Stopwatch.StartNew();
@@ -86,7 +109,11 @@ public class SiteAuditRetentionServiceTests
public IReadOnlyCollection<DateTime> PurgeCalls => _purgeCalls;
public bool ThrowOnFirstCall { get; init; }
public Task<int> PurgeExpiredAsync(DateTime olderThanUtc, CancellationToken ct = default)
/// <summary>When set, PurgeExpiredAsync records the call then blocks until the token
/// cancels — simulating a shutdown that lands while a purge is in flight.</summary>
public bool BlockUntilCancelled { get; init; }
public async Task<int> PurgeExpiredAsync(DateTime olderThanUtc, CancellationToken ct = default)
{
var n = Interlocked.Increment(ref _calls);
_purgeCalls.Enqueue(olderThanUtc);
@@ -95,7 +122,12 @@ public class SiteAuditRetentionServiceTests
throw new InvalidOperationException("Simulated transient purge failure.");
}
return Task.FromResult(0);
if (BlockUntilCancelled)
{
await Task.Delay(Timeout.Infinite, ct).ConfigureAwait(false);
}
return 0;
}
public Task<IReadOnlyList<AuditEvent>> ReadPendingAsync(int limit, CancellationToken ct = default)