perf(audit): indexed, chunked retention sweep that runs off the startup path (SEC-014, #256)
This commit is contained in:
@@ -45,7 +45,6 @@ public sealed class AuditDrainService(
|
||||
try
|
||||
{
|
||||
await sink.EnsureInitializedAsync(cancellationToken).ConfigureAwait(false);
|
||||
await SweepRetentionAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
@@ -250,6 +249,10 @@ public sealed class AuditDrainService(
|
||||
{
|
||||
try
|
||||
{
|
||||
// The first sweep runs here rather than in StartAsync: on a large audit table it can
|
||||
// take a while (and builds the retention index once), and host startup must not wait on it.
|
||||
await SweepRetentionAsync(stoppingToken).ConfigureAwait(false);
|
||||
|
||||
using PeriodicTimer timer = new(RetentionSweepInterval, timeProvider);
|
||||
|
||||
while (await timer.WaitForNextTickAsync(stoppingToken).ConfigureAwait(false))
|
||||
|
||||
@@ -66,6 +66,19 @@ public sealed class SqliteCanonicalAuditStore(
|
||||
$category, $target, $source_node, $correlation_id, $details_json);
|
||||
""";
|
||||
|
||||
// Index on the same expression the sweep compares, so the DELETE seeks instead of scanning the
|
||||
// whole table. It is the instant (datetime()), not the raw text, that is indexed: the sweep
|
||||
// compares instants so rows in a non-UTC or mixed format are still judged correctly.
|
||||
private const string CreateRetentionIndexSql =
|
||||
"CREATE INDEX IF NOT EXISTS ix_audit_event_occurred_instant ON audit_event (datetime(occurred_at_utc));";
|
||||
|
||||
// Rows removed per statement. Each chunk is its own implicit transaction, so the single SQLite
|
||||
// write lock (shared with the API-key store's last_used writes) is released between chunks.
|
||||
private const int SweepChunkSize = 5000;
|
||||
|
||||
/// <summary>0 until the retention index has been created at least once by this instance.</summary>
|
||||
private int _retentionIndexEnsured;
|
||||
|
||||
/// <summary>0 until the <c>audit_event</c> table has been created at least once by this instance.</summary>
|
||||
private int _tableEnsured;
|
||||
|
||||
@@ -162,17 +175,32 @@ public sealed class SqliteCanonicalAuditStore(
|
||||
|
||||
await EnsureTableAsync(connection, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
await using SqliteCommand command = connection.CreateCommand();
|
||||
command.CommandText =
|
||||
"""
|
||||
DELETE FROM audit_event
|
||||
WHERE datetime(occurred_at_utc) < datetime($cutoff);
|
||||
""";
|
||||
command.Parameters.AddWithValue(
|
||||
"$cutoff",
|
||||
cutoffUtc.ToUniversalTime().ToString("O", CultureInfo.InvariantCulture));
|
||||
await EnsureRetentionIndexAsync(connection, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
|
||||
string cutoff = cutoffUtc.ToUniversalTime().ToString("O", CultureInfo.InvariantCulture);
|
||||
int total = 0;
|
||||
int deleted;
|
||||
|
||||
do
|
||||
{
|
||||
await using SqliteCommand command = connection.CreateCommand();
|
||||
command.CommandText =
|
||||
"""
|
||||
DELETE FROM audit_event
|
||||
WHERE rowid IN (
|
||||
SELECT rowid FROM audit_event
|
||||
WHERE datetime(occurred_at_utc) < datetime($cutoff)
|
||||
LIMIT $chunk);
|
||||
""";
|
||||
command.Parameters.AddWithValue("$cutoff", cutoff);
|
||||
command.Parameters.AddWithValue("$chunk", SweepChunkSize);
|
||||
|
||||
deleted = await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
|
||||
total += deleted;
|
||||
}
|
||||
while (deleted >= SweepChunkSize);
|
||||
|
||||
return total;
|
||||
}
|
||||
|
||||
/// <summary>Returns the most recent canonical audit events, newest first.</summary>
|
||||
@@ -226,6 +254,22 @@ public sealed class SqliteCanonicalAuditStore(
|
||||
return events;
|
||||
}
|
||||
|
||||
// Created lazily by the sweep rather than with the table: building it over a large existing
|
||||
// table is a one-time cost, and it belongs on the background retention loop, not on startup.
|
||||
private async Task EnsureRetentionIndexAsync(SqliteConnection connection, CancellationToken cancellationToken)
|
||||
{
|
||||
if (Volatile.Read(ref _retentionIndexEnsured) == 1)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await using SqliteCommand command = connection.CreateCommand();
|
||||
command.CommandText = CreateRetentionIndexSql;
|
||||
await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
Volatile.Write(ref _retentionIndexEnsured, 1);
|
||||
}
|
||||
|
||||
// Latched bootstrap: after the first success this is a single volatile read, so the DDL
|
||||
// round-trip is paid once per process rather than once per audit write.
|
||||
private async Task EnsureTableAsync(SqliteConnection connection, CancellationToken cancellationToken)
|
||||
|
||||
@@ -6,6 +6,7 @@ using ZB.MOM.WW.Auth.ApiKeys.Sqlite;
|
||||
using ZB.MOM.WW.MxGateway.Server.Configuration;
|
||||
using ZB.MOM.WW.MxGateway.Server.Security.Audit;
|
||||
using ZB.MOM.WW.MxGateway.Tests.Security.Authentication;
|
||||
using ZB.MOM.WW.MxGateway.Tests.TestSupport;
|
||||
|
||||
namespace ZB.MOM.WW.MxGateway.Tests.Security.Audit;
|
||||
|
||||
@@ -160,7 +161,8 @@ public sealed class ChannelAuditWriterTests : IDisposable
|
||||
|
||||
/// <summary>
|
||||
/// The retention sweep deletes rows older than <c>AuditRetentionDays</c>, measured from the
|
||||
/// injected clock, and runs once at startup after the one-time table bootstrap.
|
||||
/// injected clock. The table bootstrap completes in <c>StartAsync</c>; the first sweep runs from
|
||||
/// the background loop so a large audit table cannot delay host startup (SEC-014).
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
@@ -174,12 +176,67 @@ public sealed class ChannelAuditWriterTests : IDisposable
|
||||
clock);
|
||||
|
||||
await drain.StartAsync(CancellationToken.None);
|
||||
await Eventually.WaitUntilAsync(() => sink.DeleteCutoffs.Count >= 1, TimeSpan.FromSeconds(10));
|
||||
await drain.StopAsync(CancellationToken.None);
|
||||
|
||||
Assert.Equal(1, sink.EnsureInitializedCalls);
|
||||
Assert.Equal(new DateTimeOffset(2026, 7, 16, 12, 0, 0, TimeSpan.Zero), Assert.Single(sink.DeleteCutoffs));
|
||||
}
|
||||
|
||||
/// <summary>SEC-014: a sweep that blocks (a big table) must not hold up <c>StartAsync</c>.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task StartAsync_WhenTheSweepBlocks_StillCompletes()
|
||||
{
|
||||
CountingAuditSink sink = new() { BlockDelete = new TaskCompletionSource() };
|
||||
(_, AuditDrainService drain) = CreateWriterAndDrain(sink);
|
||||
|
||||
await drain.StartAsync(CancellationToken.None).WaitAsync(TimeSpan.FromSeconds(10));
|
||||
|
||||
sink.BlockDelete.SetResult();
|
||||
await drain.StopAsync(CancellationToken.None);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SEC-014: the sweep seeks an index on the instant it compares rather than scanning the table,
|
||||
/// and removes a backlog larger than one chunk.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task SqliteStore_DeleteOlderThan_UsesTheRetentionIndexAndSweepsMoreThanOneChunk()
|
||||
{
|
||||
(SqliteCanonicalAuditStore store, AuthSqliteConnectionFactory factory) = CreateStore();
|
||||
DateTimeOffset old = new(2026, 1, 1, 0, 0, 0, TimeSpan.Zero);
|
||||
List<AuditEvent> backlog = [];
|
||||
for (int index = 0; index < 5200; index++)
|
||||
{
|
||||
backlog.Add(MakeEvent("old", old));
|
||||
}
|
||||
|
||||
await store.InsertBatchAsync(backlog, CancellationToken.None);
|
||||
await store.InsertAsync(MakeEvent("fresh", new DateTimeOffset(2026, 6, 1, 0, 0, 0, TimeSpan.Zero)), CancellationToken.None);
|
||||
|
||||
int deleted = await store.DeleteOlderThanAsync(new DateTimeOffset(2026, 3, 1, 0, 0, 0, TimeSpan.Zero), CancellationToken.None);
|
||||
|
||||
Assert.Equal(5200, deleted);
|
||||
Assert.Equal(["fresh"], await ListActionsAsync(factory));
|
||||
|
||||
await using SqliteConnection connection = await factory.OpenConnectionAsync(CancellationToken.None);
|
||||
await using SqliteCommand plan = connection.CreateCommand();
|
||||
plan.CommandText =
|
||||
"EXPLAIN QUERY PLAN SELECT rowid FROM audit_event WHERE datetime(occurred_at_utc) < datetime('2026-03-01T00:00:00.0000000+00:00') LIMIT 5000;";
|
||||
List<string> details = [];
|
||||
await using (SqliteDataReader reader = await plan.ExecuteReaderAsync(CancellationToken.None))
|
||||
{
|
||||
while (await reader.ReadAsync(CancellationToken.None))
|
||||
{
|
||||
details.Add(reader.GetString(3));
|
||||
}
|
||||
}
|
||||
|
||||
Assert.Contains(details, detail => detail.Contains("ix_audit_event_occurred_instant", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The sweep compares instants, not stored text, and never deletes a row it cannot date.
|
||||
/// </summary>
|
||||
@@ -357,6 +414,9 @@ public sealed class ChannelAuditWriterTests : IDisposable
|
||||
/// <summary>Gets the number of accepted <see cref="InsertBatchAsync"/> calls.</summary>
|
||||
public int InsertBatchCalls => BatchSizes.Count;
|
||||
|
||||
/// <summary>Gets or sets a gate the sweep waits on, to model a long-running delete.</summary>
|
||||
public TaskCompletionSource? BlockDelete { get; set; }
|
||||
|
||||
/// <summary>Gets the number of <see cref="EnsureInitializedAsync"/> calls.</summary>
|
||||
public int EnsureInitializedCalls { get; private set; }
|
||||
|
||||
@@ -395,14 +455,19 @@ public sealed class ChannelAuditWriterTests : IDisposable
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<int> DeleteOlderThanAsync(DateTimeOffset cutoffUtc, CancellationToken cancellationToken)
|
||||
public async Task<int> DeleteOlderThanAsync(DateTimeOffset cutoffUtc, CancellationToken cancellationToken)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
DeleteCutoffs.Add(cutoffUtc);
|
||||
}
|
||||
|
||||
return Task.FromResult(0);
|
||||
if (BlockDelete is { } gate)
|
||||
{
|
||||
await gate.Task.WaitAsync(cancellationToken);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user