From 662c2976f5a3ae5385c1d5d99ce9ce33543bc944 Mon Sep 17 00:00:00 2001 From: Ramon Smits Date: Fri, 27 Nov 2026 09:01:17 +0100 Subject: [PATCH 1/3] List expired audit hours with one seek for each hour The DISTINCT query over the expired rows reads all of them. On a large table it exceeds the command timeout, and the retention pass fails before it deletes a row. The new query seeks the next expired hour on the clustered key. --- .../SqlServerAuditPartitionManager.cs | 27 ++++++++++++++----- 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/src/ServiceControl.Audit.Persistence.EFCore.SqlServer/SqlServerAuditPartitionManager.cs b/src/ServiceControl.Audit.Persistence.EFCore.SqlServer/SqlServerAuditPartitionManager.cs index 584dffccdc..97c1dfeeff 100644 --- a/src/ServiceControl.Audit.Persistence.EFCore.SqlServer/SqlServerAuditPartitionManager.cs +++ b/src/ServiceControl.Audit.Persistence.EFCore.SqlServer/SqlServerAuditPartitionManager.cs @@ -13,14 +13,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)) + }; + + var next = await hours.FirstOrDefaultAsync(cancellationToken); + if (next is null) + { + return expired; + } - return await hours.Distinct().OrderBy(hour => hour).ToListAsync(cancellationToken); + expired.Add(next.Value); + last = next; + } } public Task DeleteBodies(IAuditBodyStoragePersistence bodyStorage, DateTime hour, CancellationToken cancellationToken = default) => From 9899a09e1eeb6481a7252bc52d53153236313e72 Mon Sep 17 00:00:00 2001 From: Ramon Smits Date: Fri, 27 Nov 2026 09:01:17 +0100 Subject: [PATCH 2/3] Force a seek and a fixed plan for the audit retention delete The delete that EF Core generates failed on a large table in two ways: - The compile waited for a synchronous update of the statistics of the table. - The plan read IX_AuditMessages_Id in Id order with a filter on the hour. The last batch of an hour has fewer rows than the batch size, so the scan read the complete index. Both exceeded the command timeout, and the retention loop then waited for its next hourly tick. The statement is now raw SQL with WITH (FORCESEEK) and OPTION (KEEPFIXED PLAN), because EF Core cannot add these hints to ExecuteDeleteAsync. --- .../SqlServerAuditPartitionManager.cs | 38 +++++++++++++------ 1 file changed, 27 insertions(+), 11 deletions(-) diff --git a/src/ServiceControl.Audit.Persistence.EFCore.SqlServer/SqlServerAuditPartitionManager.cs b/src/ServiceControl.Audit.Persistence.EFCore.SqlServer/SqlServerAuditPartitionManager.cs index 97c1dfeeff..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; @@ -43,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); } From 8fa07f387c4b48d3cc738f205481e1aff473f447 Mon Sep 17 00:00:00 2001 From: Ramon Smits Date: Fri, 27 Nov 2026 09:20:02 +0100 Subject: [PATCH 3/3] Retry a failed audit retention sweep with exponential back-off A failed sweep waited for the next hourly tick, so one command timeout stopped the purge for up to one hour. The loop now starts the sweep again after 10 seconds, and doubles the delay for each next failure up to the sweep interval. Jitter spreads each delay over the upper half of its range. --- .../Implementation/AuditRetention.cs | 49 ++++++++++++++----- .../EFCore/AuditRetentionRetryDelayTests.cs | 30 ++++++++++++ 2 files changed, 66 insertions(+), 13 deletions(-) create mode 100644 src/ServiceControl.Audit.Persistence.Tests/EFCore/AuditRetentionRetryDelayTests.cs 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))); + } +}