diff --git a/src/ServiceControl.Audit.Persistence.EFCore.SqlServer/SqlServerAuditPartitionManager.cs b/src/ServiceControl.Audit.Persistence.EFCore.SqlServer/SqlServerAuditPartitionManager.cs index 584dffccdc..5ebdbe85a8 100644 --- a/src/ServiceControl.Audit.Persistence.EFCore.SqlServer/SqlServerAuditPartitionManager.cs +++ b/src/ServiceControl.Audit.Persistence.EFCore.SqlServer/SqlServerAuditPartitionManager.cs @@ -2,6 +2,7 @@ namespace ServiceControl.Audit.Persistence.EFCore.SqlServer; using Microsoft.EntityFrameworkCore; using ServiceControl.Audit.Persistence.EFCore.DbContexts; +using ServiceControl.Audit.Persistence.EFCore.Entities; using ServiceControl.Audit.Persistence.EFCore.Infrastructure; using ServiceControl.Audit.Persistence.EFCore.Infrastructure.Metrics; @@ -13,14 +14,29 @@ public Task EnsurePartitions(AuditDbContext dbContext, DateTime fromHour, DateTi public async Task> ListExpired(AuditDbContext dbContext, AuditRetentionEntity entity, DateTime keepFrom, CancellationToken cancellationToken = default) { - var hours = entity switch + // One seek on the clustered key for each expired hour. + var expired = new List(); + DateTime? last = null; + + while (true) { - AuditRetentionEntity.AuditMessages => dbContext.AuditMessages.Where(message => message.CreatedOn < keepFrom).Select(message => message.CreatedOn), - AuditRetentionEntity.SagaSnapshots => dbContext.SagaSnapshots.Where(snapshot => snapshot.CreatedOn < keepFrom).Select(snapshot => snapshot.CreatedOn), - _ => throw new ArgumentOutOfRangeException(nameof(entity)) - }; + var after = last; + var hours = entity switch + { + AuditRetentionEntity.AuditMessages => dbContext.AuditMessages.Where(message => message.CreatedOn < keepFrom && (after == null || message.CreatedOn > after)).OrderBy(message => message.CreatedOn).Select(message => (DateTime?)message.CreatedOn), + AuditRetentionEntity.SagaSnapshots => dbContext.SagaSnapshots.Where(snapshot => snapshot.CreatedOn < keepFrom && (after == null || snapshot.CreatedOn > after)).OrderBy(snapshot => snapshot.CreatedOn).Select(snapshot => (DateTime?)snapshot.CreatedOn), + _ => throw new ArgumentOutOfRangeException(nameof(entity)) + }; - return await hours.Distinct().OrderBy(hour => hour).ToListAsync(cancellationToken); + var next = await hours.FirstOrDefaultAsync(cancellationToken); + if (next is null) + { + return expired; + } + + expired.Add(next.Value); + last = next; + } } public Task DeleteBodies(IAuditBodyStoragePersistence bodyStorage, DateTime hour, CancellationToken cancellationToken = default) => @@ -28,20 +44,35 @@ public Task DeleteBodies(IAuditBodyStoragePersistence bodyStorage, DateTime hour public async Task DropExpired(AuditDbContext dbContext, AuditRetentionEntity entity, DateTime hour, int batchSize, CancellationToken cancellationToken = default) { - var deleted = entity switch + var entityType = entity switch { - AuditRetentionEntity.AuditMessages => await dbContext.AuditMessages - .Where(message => message.CreatedOn == hour) - .OrderBy(message => message.Id) - .Take(batchSize) - .ExecuteDeleteAsync(cancellationToken), - AuditRetentionEntity.SagaSnapshots => await dbContext.SagaSnapshots - .Where(snapshot => snapshot.CreatedOn == hour) - .OrderBy(snapshot => snapshot.Id) - .Take(batchSize) - .ExecuteDeleteAsync(cancellationToken), + AuditRetentionEntity.AuditMessages => dbContext.Model.FindEntityType(typeof(AuditMessageEntity))!, + AuditRetentionEntity.SagaSnapshots => dbContext.Model.FindEntityType(typeof(SagaSnapshotEntity))!, _ => throw new ArgumentOutOfRangeException(nameof(entity)) }; + var table = $"[{entityType.GetSchema()}].[{entityType.GetTableName()}]"; + + // Raw SQL because ExecuteDeleteAsync cannot add the hints. +#pragma warning disable EF1002 // The table name comes from the EF Core model. + var deleted = await dbContext.Database.ExecuteSqlRawAsync( + $""" + DELETE FROM [a] + FROM {table} AS [a] + WHERE EXISTS ( + SELECT 1 + FROM ( + SELECT TOP (@p0) [a0].[CreatedOn], [a0].[Id] + FROM {table} AS [a0] WITH (FORCESEEK) + WHERE [a0].[CreatedOn] = @p1 + ORDER BY [a0].[Id] + ) AS [a1] + WHERE [a1].[CreatedOn] = [a].[CreatedOn] AND [a1].[Id] = [a].[Id] + ) + OPTION (KEEPFIXED PLAN) + """, + [batchSize, hour], + cancellationToken); +#pragma warning restore EF1002 return new DropResult(deleted, Completed: deleted < batchSize); } diff --git a/src/ServiceControl.Audit.Persistence.EFCore/Implementation/AuditRetention.cs b/src/ServiceControl.Audit.Persistence.EFCore/Implementation/AuditRetention.cs index 466dbca45d..fddf4fa8d7 100644 --- a/src/ServiceControl.Audit.Persistence.EFCore/Implementation/AuditRetention.cs +++ b/src/ServiceControl.Audit.Persistence.EFCore/Implementation/AuditRetention.cs @@ -24,6 +24,7 @@ sealed class AuditRetention( static readonly TimeSpan Interval = TimeSpan.FromHours(1); static readonly TimeSpan InitialDelay = TimeSpan.FromMinutes(1); static readonly TimeSpan BatchPause = TimeSpan.FromSeconds(1); + static readonly TimeSpan RetryBaseDelay = TimeSpan.FromSeconds(10); // Before ingestion starts, which cannot insert into an hour that has no partition. public override async Task StartAsync(CancellationToken cancellationToken = default) @@ -48,17 +49,16 @@ protected override async Task ExecuteAsync(CancellationToken cancellationToken = do { - try + var attempt = 0; + while (!await TrySweep(cancellationToken)) { - await Sweep(pace: true, cancellationToken); - } -#pragma warning disable PS0019 // Filtered on the token alone because SqlClient reports a cancelled command as a SqlException. - catch (Exception ex) when (!cancellationToken.IsCancellationRequested) - { - logger.LogError(ex, "Error during audit retention sweep"); + var delay = RetryDelay(++attempt, Random.Shared.NextDouble()); + logger.LogWarning("The audit retention sweep failed. Attempt {Attempt} starts in {Delay}", attempt + 1, delay); + await Task.Delay(delay, timeProvider, cancellationToken); } } while (await timer.WaitForNextTickAsync(cancellationToken)); } +#pragma warning disable PS0019 // Filtered on the token alone because SqlClient reports a cancelled command as a SqlException. catch (Exception) when (cancellationToken.IsCancellationRequested) { logger.LogInformation("Stopping audit retention sweep"); @@ -66,9 +66,32 @@ protected override async Task ExecuteAsync(CancellationToken cancellationToken = #pragma warning restore PS0019 } + async Task TrySweep(CancellationToken cancellationToken) + { + try + { + return await Sweep(pace: true, cancellationToken); + } +#pragma warning disable PS0019 // Filtered on the token alone because SqlClient reports a cancelled command as a SqlException. + catch (Exception ex) when (!cancellationToken.IsCancellationRequested) + { + logger.LogError(ex, "Error during audit retention sweep"); + return false; + } +#pragma warning restore PS0019 + } + + // Exponential back-off with jitter, capped at the sweep interval. jitter is in [0, 1). + internal static TimeSpan RetryDelay(int attempt, double jitter) + { + var exponential = TimeSpan.FromTicks(Math.Min(Interval.Ticks, RetryBaseDelay.Ticks << Math.Min(attempt - 1, 16))); + return (exponential / 2) + (exponential / 2 * jitter); + } + internal Task SweepNow(CancellationToken cancellationToken = default) => Sweep(pace: false, cancellationToken); - async Task Sweep(bool pace, CancellationToken cancellationToken) + // Returns false when a pass failed. + async Task Sweep(bool pace, CancellationToken cancellationToken) { var passesStarted = false; try @@ -79,7 +102,7 @@ async Task Sweep(bool pace, CancellationToken cancellationToken) if (handle is null) { logger.LogWarning("Skipping the audit retention sweep because another instance holds the retention lock. Only one audit instance should own a database."); - return; + return true; } var now = timeProvider.GetUtcNow().UtcDateTime; @@ -99,11 +122,11 @@ async Task Sweep(bool pace, CancellationToken cancellationToken) if (passFailures.Count > 0) { retentionState.SweepFailed(string.Join("; ", passFailures)); + return false; } - else - { - retentionState.SweepSucceeded(); - } + + retentionState.SweepSucceeded(); + return true; } #pragma warning disable PS0019 // Filtered on the token alone because SqlClient reports a cancelled command as a SqlException. catch (Exception ex) when (!cancellationToken.IsCancellationRequested) diff --git a/src/ServiceControl.Audit.Persistence.Tests/EFCore/AuditRetentionRetryDelayTests.cs b/src/ServiceControl.Audit.Persistence.Tests/EFCore/AuditRetentionRetryDelayTests.cs new file mode 100644 index 0000000000..f3f119c80a --- /dev/null +++ b/src/ServiceControl.Audit.Persistence.Tests/EFCore/AuditRetentionRetryDelayTests.cs @@ -0,0 +1,30 @@ +namespace ServiceControl.Audit.Persistence.Tests +{ + using System; + using NUnit.Framework; + using ServiceControl.Audit.Persistence.EFCore.Implementation; + + [TestFixture] + class AuditRetentionRetryDelayTests + { + [TestCase(1, 5, 10)] + [TestCase(2, 10, 20)] + [TestCase(3, 20, 40)] + [TestCase(6, 160, 320)] + public void Doubles_with_each_attempt_and_stays_within_the_jitter_range(int attempt, int minSeconds, int maxSeconds) + { + using (Assert.EnterMultipleScope()) + { + Assert.That(AuditRetention.RetryDelay(attempt, 0), Is.EqualTo(TimeSpan.FromSeconds(minSeconds))); + Assert.That(AuditRetention.RetryDelay(attempt, 0.5), Is.EqualTo(TimeSpan.FromSeconds((minSeconds + maxSeconds) / 2.0))); + Assert.That(AuditRetention.RetryDelay(attempt, 0.999999), Is.LessThan(TimeSpan.FromSeconds(maxSeconds))); + } + } + + [TestCase(10)] + [TestCase(100)] + [TestCase(int.MaxValue)] + public void Never_exceeds_the_sweep_interval(int attempt) => + Assert.That(AuditRetention.RetryDelay(attempt, 0.999999), Is.LessThan(TimeSpan.FromHours(1)).And.GreaterThanOrEqualTo(TimeSpan.FromMinutes(30))); + } +}