From 130e5f658bd53e4e495e5792f4cd11adb589134c Mon Sep 17 00:00:00 2001 From: Ramon Smits Date: Mon, 30 Nov 2026 09:45:13 +0100 Subject: [PATCH] Base the audit retention custom check on the oldest expired rows The check counted consecutive failed sweeps in memory. A sweep that succeeds but takes longer than the sweep interval, a sweep that does not end and a restart did not fail the check, and the sweep retries reached the count of three in less than a minute. The check reads the oldest expired rows from the database and fails when rows stay more than three hours after their retention period ended. --- docs/telemetry.md | 3 +- .../SqlServerAuditPartitionManager.cs | 8 ++ .../AuditRetentionCustomCheck.cs | 76 +++++----- .../Infrastructure/IAuditPartitionManager.cs | 3 + .../EFCore/EFPersistenceTestFixture.cs | 9 ++ .../EFCore/EFRetentionCustomCheckTests.cs | 131 +++++++++++++----- .../EFCore/EFRetentionMetricsTests.cs | 9 -- .../EFCore/EFRetentionTests.cs | 2 +- 8 files changed, 159 insertions(+), 82 deletions(-) diff --git a/docs/telemetry.md b/docs/telemetry.md index 68762a7c9e..3e512b36e2 100644 --- a/docs/telemetry.md +++ b/docs/telemetry.md @@ -133,7 +133,8 @@ What the shapes mean: - On the error instance, `rows_deleted_total` flat at zero across a long window is only healthy if the instance is also not ingesting. Deletion stopping while ingestion continues means the retention window is not being enforced. - A cycle duration climbing towards the hourly interval means the sweep is no longer keeping up with the arrival rate, and each run starts further behind than the last. - A body store that refuses a delete fails the `failed_messages` pass rather than orphaning the body, so an expired credential or a changed permission shows as a climbing gauge instead of storage that quietly keeps growing. Those rows stay until a sweep can delete the body and the row together. -- On the audit instance, a pass that leaves expired rows because its table is too busy to drop them is recorded as `failed`. The "Audit retention" custom check counts that sweep as failed too. A sweep skipped because another audit instance holds the retention lock records nothing. +- On the audit instance, a pass that leaves expired rows because its table is too busy to drop them is recorded as `failed`. A sweep skipped because another audit instance holds the retention lock records nothing. +- On the audit instance, the "Audit retention" custom check does not count sweeps. Each hour it reads the oldest rows from the database and fails when rows stay more than three hours after their retention period ended. It therefore also reports a sweep that succeeds but removes rows slower than they expire, a sweep that does not end, and an instance that restarts before a sweep completes. None of these raise `consecutive_failures_total`, which also starts at zero after a restart. The failure message carries the reason of the last failed sweep when there is one. - Each pass is isolated, so one kind of row failing to be reclaimed does not stop the others. Every pass that runs reports a result, and the gauge is per pass, so alert across all entities rather than on any one of them. ## Monitoring diff --git a/src/ServiceControl.Audit.Persistence.EFCore.SqlServer/SqlServerAuditPartitionManager.cs b/src/ServiceControl.Audit.Persistence.EFCore.SqlServer/SqlServerAuditPartitionManager.cs index 2495fb0ad1..49dcd0f6fa 100644 --- a/src/ServiceControl.Audit.Persistence.EFCore.SqlServer/SqlServerAuditPartitionManager.cs +++ b/src/ServiceControl.Audit.Persistence.EFCore.SqlServer/SqlServerAuditPartitionManager.cs @@ -40,6 +40,14 @@ public async Task> ListExpired(AuditDbContext dbContext, } } + public Task OldestExpired(AuditDbContext dbContext, AuditRetentionEntity entity, DateTime keepFrom, CancellationToken cancellationToken = default) => + entity switch + { + AuditRetentionEntity.AuditMessages => dbContext.AuditMessages.Where(message => message.CreatedOn < keepFrom).OrderBy(message => message.CreatedOn).Select(message => (DateTime?)message.CreatedOn).FirstOrDefaultAsync(cancellationToken), + AuditRetentionEntity.SagaSnapshots => dbContext.SagaSnapshots.Where(snapshot => snapshot.CreatedOn < keepFrom).OrderBy(snapshot => snapshot.CreatedOn).Select(snapshot => (DateTime?)snapshot.CreatedOn).FirstOrDefaultAsync(cancellationToken), + _ => throw new ArgumentOutOfRangeException(nameof(entity)) + }; + public Task DeleteBodies(IAuditBodyStoragePersistence bodyStorage, DateTime hour, CancellationToken cancellationToken = default) => bodyStorage.DeleteBodiesForHour(hour, cancellationToken); diff --git a/src/ServiceControl.Audit.Persistence.EFCore/Implementation/AuditRetentionCustomCheck.cs b/src/ServiceControl.Audit.Persistence.EFCore/Implementation/AuditRetentionCustomCheck.cs index 5304e327b5..dd7f5c1d9f 100644 --- a/src/ServiceControl.Audit.Persistence.EFCore/Implementation/AuditRetentionCustomCheck.cs +++ b/src/ServiceControl.Audit.Persistence.EFCore/Implementation/AuditRetentionCustomCheck.cs @@ -1,52 +1,62 @@ namespace ServiceControl.Audit.Persistence.EFCore.Implementation; +using Microsoft.Extensions.DependencyInjection; using NServiceBus.CustomChecks; +using ServiceControl.Audit.Persistence.EFCore.Abstractions; +using ServiceControl.Audit.Persistence.EFCore.DbContexts; +using ServiceControl.Audit.Persistence.EFCore.Infrastructure; +using ServiceControl.Audit.Persistence.EFCore.Infrastructure.Metrics; -class AuditRetentionCustomCheck(AuditRetentionCustomCheck.State state) +class AuditRetentionCustomCheck( + IServiceScopeFactory scopeFactory, + IAuditPartitionManager partitions, + EFPersisterSettings settings, + TimeProvider timeProvider, + AuditRetentionCustomCheck.State state) : CustomCheck("Audit retention", "ServiceControl.Audit Health", TimeSpan.FromHours(1)) { - public override Task PerformCheck(CancellationToken cancellationToken = default) - { - var (consecutiveFailedSweeps, lastFailure) = state.Current; - - return Task.FromResult(consecutiveFailedSweeps < 3 - ? CheckResult.Pass - : CheckResult.Failed($"The last {consecutiveFailedSweeps} audit retention sweeps failed. Last failure: {lastFailure}. See https://docs.particular.net/servicecontrol/troubleshooting for guidance on resolving the issue.")); - } + public static readonly TimeSpan Tolerance = TimeSpan.FromHours(3); - internal class State + public override async Task PerformCheck(CancellationToken cancellationToken = default) { - readonly object gate = new(); - int consecutiveFailedSweeps; - string? lastFailure; + await using var scope = scopeFactory.CreateAsyncScope(); + var dbContext = scope.ServiceProvider.GetRequiredService(); - public (int ConsecutiveFailedSweeps, string? LastFailure) Current - { - get - { - lock (gate) - { - return (consecutiveFailedSweeps, lastFailure); - } - } - } + var overdueBefore = AuditHours.Truncate(timeProvider.GetUtcNow().UtcDateTime - settings.AuditRetentionPeriod - Tolerance); - public void SweepSucceeded() + List overdue = []; + foreach (var entity in Entities) { - lock (gate) + if (await partitions.OldestExpired(dbContext, entity, overdueBefore, cancellationToken) is { } oldest) { - consecutiveFailedSweeps = 0; - lastFailure = null; + overdue.Add($"{entity} from {oldest:u}"); } } - public void SweepFailed(string reason) + if (overdue.Count == 0) { - lock (gate) - { - consecutiveFailedSweeps++; - lastFailure = reason; - } + return CheckResult.Pass; } + + var cause = state.LastFailure is { } lastFailure + ? $"Last sweep failure: {lastFailure}." + : "No sweep failed since this instance started, so the sweep removes rows slower than they expire or did not complete yet."; + + return CheckResult.Failed( + $"Audit retention is behind. Rows stay more than {Tolerance.TotalHours:0} hours after the retention period of {settings.AuditRetentionPeriod} ended for them: {string.Join(", ", overdue)}. " + + $"The database grows while this continues. {cause} See https://docs.particular.net/servicecontrol/troubleshooting for guidance on resolving the issue."); + } + + static readonly AuditRetentionEntity[] Entities = Enum.GetValues(); + + internal class State + { + volatile string? lastFailure; + + public string? LastFailure => lastFailure; + + public void SweepSucceeded() => lastFailure = null; + + public void SweepFailed(string reason) => lastFailure = reason; } } diff --git a/src/ServiceControl.Audit.Persistence.EFCore/Infrastructure/IAuditPartitionManager.cs b/src/ServiceControl.Audit.Persistence.EFCore/Infrastructure/IAuditPartitionManager.cs index 43ef010b2b..c09de96444 100644 --- a/src/ServiceControl.Audit.Persistence.EFCore/Infrastructure/IAuditPartitionManager.cs +++ b/src/ServiceControl.Audit.Persistence.EFCore/Infrastructure/IAuditPartitionManager.cs @@ -9,6 +9,9 @@ interface IAuditPartitionManager Task> ListExpired(AuditDbContext dbContext, AuditRetentionEntity entity, DateTime keepFrom, CancellationToken cancellationToken = default); + async Task OldestExpired(AuditDbContext dbContext, AuditRetentionEntity entity, DateTime keepFrom, CancellationToken cancellationToken = default) => + await ListExpired(dbContext, entity, keepFrom, cancellationToken) is [var oldest, ..] ? oldest : null; + /// /// Deletes every body stored for the rows that removes for . /// diff --git a/src/ServiceControl.Audit.Persistence.Tests/EFCore/EFPersistenceTestFixture.cs b/src/ServiceControl.Audit.Persistence.Tests/EFCore/EFPersistenceTestFixture.cs index 2e8bd897d5..992f14c2c2 100644 --- a/src/ServiceControl.Audit.Persistence.Tests/EFCore/EFPersistenceTestFixture.cs +++ b/src/ServiceControl.Audit.Persistence.Tests/EFCore/EFPersistenceTestFixture.cs @@ -9,6 +9,7 @@ namespace ServiceControl.Audit.Persistence.Tests using Monitoring; using NServiceBus; using ServiceControl.Audit.Persistence.EFCore.DbContexts; + using ServiceControl.SagaAudit; abstract class EFPersistenceTestFixture : PersistenceTestFixture { @@ -32,6 +33,14 @@ protected async Task Ingest(ProcessedMessage message, byte[] body) await configuration.CompleteDBOperation(); } + protected async Task IngestSagaSnapshot() + { + await using var unitOfWork = await StartAuditUnitOfWork(1); + await unitOfWork.RecordSagaSnapshot(new SagaSnapshot { SagaId = Guid.NewGuid(), Status = SagaStateChangeStatus.New }); + await unitOfWork.Complete(); + await configuration.CompleteDBOperation(); + } + protected async Task WithDbContext(Func> query) { await using var scope = ServiceProvider.CreateAsyncScope(); diff --git a/src/ServiceControl.Audit.Persistence.Tests/EFCore/EFRetentionCustomCheckTests.cs b/src/ServiceControl.Audit.Persistence.Tests/EFCore/EFRetentionCustomCheckTests.cs index 425ab1e545..534e4e381e 100644 --- a/src/ServiceControl.Audit.Persistence.Tests/EFCore/EFRetentionCustomCheckTests.cs +++ b/src/ServiceControl.Audit.Persistence.Tests/EFCore/EFRetentionCustomCheckTests.cs @@ -13,76 +13,123 @@ namespace ServiceControl.Audit.Persistence.Tests class EFRetentionCustomCheckTests : EFPersistenceTestFixture { + static readonly TimeSpan RetentionPeriod = TimeSpan.FromDays(1); + AuditRetentionCustomCheck Check => ServiceProvider.GetServices().OfType().Single(); + public override Task Setup() + { + SetSettings = settings => settings.AuditRetentionPeriod = RetentionPeriod; + return base.Setup(); + } + [Test] - public async Task Check_fails_once_three_consecutive_sweeps_have_failed() + public async Task Check_passes_when_no_row_expired() { - var retention = CreateRetentionWithUnreachableDatabase(); + await Ingest(MakeMessage()); + await IngestSagaSnapshot(); + + Assert.That((await Check.PerformCheck()).HasFailed, Is.False); + } + + [Test] + public async Task Check_passes_while_expired_rows_are_within_the_tolerance() + { + await Ingest(MakeMessage()); + await IngestSagaSnapshot(); + + configuration.TimeProvider.Advance(RetentionPeriod + AuditRetentionCustomCheck.Tolerance - TimeSpan.FromHours(1)); + + Assert.That((await Check.PerformCheck()).HasFailed, Is.False); + } + + [Test] + public async Task Check_fails_when_expired_rows_stay_and_no_sweep_ran() + { + await Ingest(MakeMessage()); + await IngestSagaSnapshot(); + + configuration.TimeProvider.Advance(TimeSpan.FromDays(3)); + var result = await Check.PerformCheck(); + + using (Assert.EnterMultipleScope()) + { + Assert.That(result.HasFailed, Is.True); + Assert.That(result.FailureReason, Does.Contain(nameof(AuditRetentionEntity.AuditMessages)).And.Contain(nameof(AuditRetentionEntity.SagaSnapshots))); + Assert.That(result.FailureReason, Does.Contain("No sweep failed")); + } + } + + [Test] + public async Task Check_passes_when_sweeps_fail_and_no_row_is_overdue() + { + await Ingest(MakeMessage()); + + FailThreeSweeps(); + + Assert.That((await Check.PerformCheck()).HasFailed, Is.False); + } + + [Test] + public async Task Check_gives_the_reason_of_a_sweep_that_failed_before_its_passes() + { + await Ingest(MakeMessage()); + configuration.TimeProvider.Advance(TimeSpan.FromDays(3)); - Assert.ThrowsAsync(() => retention.SweepNow()); - Assert.ThrowsAsync(() => retention.SweepNow()); - var afterTwo = await Check.PerformCheck(); - Assert.ThrowsAsync(() => retention.SweepNow()); - var afterThree = await Check.PerformCheck(); + Assert.ThrowsAsync(() => CreateRetentionWithUnreachableDatabase().SweepNow()); + var result = await Check.PerformCheck(); using (Assert.EnterMultipleScope()) { - Assert.That(afterTwo.HasFailed, Is.False); - Assert.That(afterThree.HasFailed, Is.True); - Assert.That(afterThree.FailureReason, Does.Contain(UnreachableRetentionLock.Reason)); + Assert.That(result.HasFailed, Is.True); + Assert.That(result.FailureReason, Does.Contain(UnreachableRetentionLock.Reason)); } } [Test] - public async Task Check_fails_once_three_consecutive_sweeps_have_left_expired_rows_behind() + public async Task Check_gives_the_reason_of_a_sweep_that_left_expired_rows_behind() { - var retention = ActivatorUtilities.CreateInstance(ServiceProvider, new BusyAuditPartitions()); + await Ingest(MakeMessage()); + configuration.TimeProvider.Advance(TimeSpan.FromDays(3)); - await retention.SweepNow(); - await retention.SweepNow(); - var afterTwo = await Check.PerformCheck(); - await retention.SweepNow(); - var afterThree = await Check.PerformCheck(); + await ActivatorUtilities.CreateInstance(ServiceProvider, new BusyAuditPartitions()).SweepNow(); + var result = await Check.PerformCheck(); using (Assert.EnterMultipleScope()) { - Assert.That(afterTwo.HasFailed, Is.False); - Assert.That(afterThree.HasFailed, Is.True); - Assert.That(afterThree.FailureReason, Does.Contain("too busy")); + Assert.That(result.HasFailed, Is.True); + Assert.That(result.FailureReason, Does.Contain("too busy")); } } - [TestCase(AuditRetentionEntity.AuditMessages)] - [TestCase(AuditRetentionEntity.SagaSnapshots)] - public async Task Check_fails_once_three_consecutive_sweeps_have_had_a_failing_pass(AuditRetentionEntity failing) + [TestCase(AuditRetentionEntity.AuditMessages, AuditRetentionEntity.SagaSnapshots)] + [TestCase(AuditRetentionEntity.SagaSnapshots, AuditRetentionEntity.AuditMessages)] + public async Task Check_names_only_the_rows_that_a_failing_pass_left(AuditRetentionEntity failing, AuditRetentionEntity other) { + await Ingest(MakeMessage()); + await IngestSagaSnapshot(); + configuration.TimeProvider.Advance(TimeSpan.FromDays(3)); var partitions = new FailingAuditPartitions(failing, ServiceProvider.GetRequiredService()); - var retention = ActivatorUtilities.CreateInstance(ServiceProvider, partitions); - await retention.SweepNow(); - await retention.SweepNow(); - var afterTwo = await Check.PerformCheck(); - await retention.SweepNow(); - var afterThree = await Check.PerformCheck(); + await ActivatorUtilities.CreateInstance(ServiceProvider, partitions).SweepNow(); + var result = await Check.PerformCheck(); using (Assert.EnterMultipleScope()) { - Assert.That(afterTwo.HasFailed, Is.False); - Assert.That(afterThree.HasFailed, Is.True); - Assert.That(afterThree.FailureReason, Does.Contain(FailingAuditPartitions.Reason)); + Assert.That(result.HasFailed, Is.True); + Assert.That(result.FailureReason, Does.Contain($"{failing} from").And.Not.Contain($"{other} from")); + Assert.That(result.FailureReason, Does.Contain(FailingAuditPartitions.Reason)); } } [Test] public async Task Check_names_the_command_timeout_setting_when_a_pass_exceeds_the_command_timeout() { + await Ingest(MakeMessage()); + configuration.TimeProvider.Advance(TimeSpan.FromDays(3)); var partitions = new FailingAuditPartitions(AuditRetentionEntity.AuditMessages, ServiceProvider.GetRequiredService(), failsWithCommandTimeout: true); - var retention = ActivatorUtilities.CreateInstance(ServiceProvider, partitions); - await retention.SweepNow(); - await retention.SweepNow(); - await retention.SweepNow(); + await ActivatorUtilities.CreateInstance(ServiceProvider, partitions).SweepNow(); var result = await Check.PerformCheck(); using (Assert.EnterMultipleScope()) @@ -95,17 +142,25 @@ public async Task Check_names_the_command_timeout_setting_when_a_pass_exceeds_th [Test] public async Task A_successful_sweep_clears_the_failure() { + await Ingest(MakeMessage()); + configuration.TimeProvider.Advance(TimeSpan.FromDays(3)); FailThreeSweeps(); + var beforeSweep = await Check.PerformCheck(); await configuration.CreateRetention().SweepNow(); - Assert.That((await Check.PerformCheck()).HasFailed, Is.False); + using (Assert.EnterMultipleScope()) + { + Assert.That(beforeSweep.HasFailed, Is.True); + Assert.That((await Check.PerformCheck()).HasFailed, Is.False); + } } [Test] public async Task A_sweep_skipped_for_the_lock_leaves_the_failure_in_place() { - FailThreeSweeps(); + await Ingest(MakeMessage()); + configuration.TimeProvider.Advance(TimeSpan.FromDays(3)); await using (await ServiceProvider.GetRequiredService().TryAcquire()) { diff --git a/src/ServiceControl.Audit.Persistence.Tests/EFCore/EFRetentionMetricsTests.cs b/src/ServiceControl.Audit.Persistence.Tests/EFCore/EFRetentionMetricsTests.cs index 5df547c0c8..8dd4638db1 100644 --- a/src/ServiceControl.Audit.Persistence.Tests/EFCore/EFRetentionMetricsTests.cs +++ b/src/ServiceControl.Audit.Persistence.Tests/EFCore/EFRetentionMetricsTests.cs @@ -14,7 +14,6 @@ namespace ServiceControl.Audit.Persistence.Tests using ServiceControl.Audit.Persistence.EFCore.Implementation; using ServiceControl.Audit.Persistence.EFCore.Infrastructure; using ServiceControl.Audit.Persistence.EFCore.Infrastructure.Metrics; - using ServiceControl.SagaAudit; class EFRetentionMetricsTests : EFPersistenceTestFixture { @@ -202,14 +201,6 @@ public async Task A_sweep_skipped_for_the_lock_reports_nothing() } } - async Task IngestSagaSnapshot() - { - await using var unitOfWork = await StartAuditUnitOfWork(1); - await unitOfWork.RecordSagaSnapshot(new SagaSnapshot { SagaId = Guid.NewGuid(), Status = SagaStateChangeStatus.New }); - await unitOfWork.Complete(); - await configuration.CompleteDBOperation(); - } - RecordedAuditRetentionMetrics Listen() => new(ServiceProvider.GetRequiredService()); sealed class UnreachableRetentionLock : IRetentionLock diff --git a/src/ServiceControl.Audit.Persistence.Tests/EFCore/EFRetentionTests.cs b/src/ServiceControl.Audit.Persistence.Tests/EFCore/EFRetentionTests.cs index cf6b5c8ed8..04463e4468 100644 --- a/src/ServiceControl.Audit.Persistence.Tests/EFCore/EFRetentionTests.cs +++ b/src/ServiceControl.Audit.Persistence.Tests/EFCore/EFRetentionTests.cs @@ -91,7 +91,7 @@ public async Task Keeps_the_rows_when_deleting_their_bodies_fails() { Assert.That(remaining.Results, Has.Count.EqualTo(1)); Assert.That(body.HasContent, Is.True, "the body is still in storage"); - Assert.That(ServiceProvider.GetRequiredService().Current.ConsecutiveFailedSweeps, Is.EqualTo(1), "the failed pass is recorded against the check"); + Assert.That(ServiceProvider.GetRequiredService().LastFailure, Does.Contain("storage is down"), "the failed pass is recorded against the check"); } }