perf(audit-log,site-event-log): channel+age purge index with varchar binding; instance+timestamp event index (AUD-5, SEL-1, WP6 task 6.5)

AUD-5: PurgeChannelOlderThanAsync binds @channel as varchar(32) and the model
gains IX_AuditLog_Channel_Occurred (Category, OccurredAtUtc). The migration +
partition-aligned SQL script land in the WP's final migration commit
(AuditLogChannelOccurredIndex).
  sqlcmd -I, SQL_Latin1_General_CP1_CI_AS, scratch DB with 1M AuditLog rows
  (6 channels, clustered (OccurredAtUtc, EventId), ScriptTrace override 30 d),
  steady-state per-channel tick (nothing left to purge):
  before (nvarchar, old indexes): 5,858 logical reads, 124 ms
  after  (varchar + new index):   6 logical reads, 0 ms
  new index but nvarchar param:   4,747 logical reads, 114 ms (binding matters)

SEL-1: site_events idx_events_instance -> idx_events_instance_timestamp
(instance_id, timestamp), dropped/rebuilt in place by SiteEventLogSchema.Apply
like #123; the storage-cap size model now charges 4 x timestamp per row.
  sqlite3, 2.7M rows / 20 instances, instance-filtered 501-row page:
  before: SEARCH idx_events_instance + USE TEMP B-TREE FOR ORDER BY; 396 ms
  after:  SEARCH idx_events_instance_timestamp (temp b-tree for id tiebreak only); 0.7 ms
This commit is contained in:
Joseph Doherty
2026-12-03 10:00:42 -05:00
parent 9f03726fc7
commit 04e3969071
10 changed files with 64 additions and 16 deletions
@@ -24,10 +24,31 @@ public class AuditPurgeBudgetTests
Assert.Equal(ConnectionState.Closed, connection.State);
}
/// <summary>
/// AUD-5 (WP6 6.5): the channel is bound as varchar(32) to match the Category column — an
/// nvarchar parameter makes SQL Server convert the column under a SQL collation and rules
/// out a seek on IX_AuditLog_Channel_Occurred.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task ChannelParameter_IsBoundAsVarchar32()
{
using var connection = new BackloggedConnection();
await using var context = new ScadaBridgeDbContext(new DbContextOptionsBuilder<ScadaBridgeDbContext>()
.UseSqlServer(connection).Options);
await new AuditLogRepository(context).PurgeChannelOlderThanAsync(
"ScriptTrace", DateTime.UtcNow, batchSize: 3, maxRows: 3);
var channel = Assert.Single(connection.ChannelParameters);
Assert.Equal(SqlDbType.VarChar, channel.Type);
Assert.Equal(32, channel.Size);
}
private sealed class BackloggedConnection : DbConnection
{
/// <summary>Gets the batch sizes requested by the purge, in order.</summary>
public List<int> RequestedBatches { get; } = new();
/// <summary>Gets the SQL type and size of each bound <c>@channel</c> parameter, in order.</summary>
public List<(SqlDbType Type, int Size)> ChannelParameters { get; } = new();
private ConnectionState _state;
/// <inheritdoc />
[AllowNull] public override string ConnectionString { get; set; } = "Server=localhost;Database=test";
@@ -81,6 +102,8 @@ public class AuditPurgeBudgetTests
throw new InvalidOperationException("Purge did not yield despite exhausting its row budget.");
var requested = (int)_parameters.Parameters["@batch"].Value;
owner.RequestedBatches.Add(requested);
var channel = _parameters.Parameters["@channel"];
owner.ChannelParameters.Add((channel.SqlDbType, channel.Size));
return requested;
}
/// <inheritdoc />
@@ -84,6 +84,7 @@ public class SchemaIndexTests : IDisposable
[Theory]
[InlineData("severity", "idx_events_severity_timestamp")]
[InlineData("event_type", "idx_events_type_timestamp")]
[InlineData("instance_id", "idx_events_instance_timestamp")] // SEL-1 (WP6 6.5)
public void EqualityFilteredPage_ReadsInTimestampOrder_WithoutSortingEveryMatch(string column, string expectedIndex)
{
foreach (var window in new[] { "", "AND timestamp >= '2026-01-01' " })
@@ -135,7 +136,7 @@ public class SchemaIndexTests : IDisposable
while (reader.Read()) indexes.Add(reader.GetString(0));
Assert.Equal(
["idx_events_instance", "idx_events_severity_timestamp", "idx_events_timestamp", "idx_events_type_timestamp"],
["idx_events_instance_timestamp", "idx_events_severity_timestamp", "idx_events_timestamp", "idx_events_type_timestamp"],
indexes);
using var count = connection.CreateCommand();
count.CommandText = "SELECT COUNT(*) FROM site_events INDEXED BY idx_events_severity_timestamp WHERE severity = 'Info'";
@@ -121,7 +121,7 @@ public class SiteEventLogSchemaTests
while (reader.Read()) indexes.Add(reader.GetString(0));
Assert.Equal(
["idx_events_instance", "idx_events_severity_timestamp", "idx_events_timestamp", "idx_events_type_timestamp"],
["idx_events_instance_timestamp", "idx_events_severity_timestamp", "idx_events_timestamp", "idx_events_type_timestamp"],
indexes);
}
@@ -75,7 +75,7 @@ public class SiteEventsSchemaCalibrationTests
Assert.True(
indexes.SequenceEqual(
[
"idx_events_instance",
"idx_events_instance_timestamp",
"idx_events_severity_timestamp",
"idx_events_timestamp",
"idx_events_type_timestamp",
@@ -89,14 +89,14 @@ public class SiteEventsSchemaCalibrationTests
/// <param name="expectedColumns">The columns the index is expected to cover, comma-separated, in key order.</param>
[Theory]
[InlineData("idx_events_timestamp", "timestamp")]
[InlineData("idx_events_instance", "instance_id")]
[InlineData("idx_events_instance_timestamp", "instance_id,timestamp")]
[InlineData("idx_events_type_timestamp", "event_type,timestamp")]
[InlineData("idx_events_severity_timestamp", "severity,timestamp")]
public void EachIndex_CoversExactlyTheColumnsTheSamplerSums(string indexName, string expectedColumns)
{
// The sampler's indexed_bytes expression sums 3 * octet_length(timestamp) +
// The sampler's indexed_bytes expression sums 4 * octet_length(timestamp) +
// octet_length(event_type) + octet_length(severity) + octet_length(instance_id):
// timestamp once for its own index and once for each of the two composites (#123).
// timestamp once for its own index and once for each of the three composites (#123, SEL-1).
// Widening or re-pointing an index changes the real entry width without changing
// what is sampled.
using var connection = OpenWithSchema();