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
+3 -1
View File
@@ -761,7 +761,9 @@ MS SQL for direct-write events). Unredacted secrets never persist.
aid, not a compliance record) whose value is a retention window in days that
MUST be strictly shorter than the global `RetentionDays`. After the daily
partition switch-out, the purge actor runs a bounded, batched row DELETE
(`PurgeChannelOlderThanAsync`) for each channel whose override is shorter than
(`PurgeChannelOlderThanAsync`, seeking the partition-aligned
`IX_AuditLog_Channel_Occurred (Category, OccurredAtUtc)` with the channel bound as
`varchar(32)` — AUD-5) for each channel whose override is shorter than
the global window — expiring rows of that channel earlier than the global
partition switch would. Overrides equal to or longer than the global window are
silently skipped (the global switch already covers them). The DELETE runs under
@@ -194,6 +194,13 @@ Each event entry contains:
- Time range
- Instance ID
- Severity
The event-type, severity and instance-ID equality filters are each backed by a composite
index with `timestamp` (`idx_events_type_timestamp`, `idx_events_severity_timestamp` — #123;
`idx_events_instance_timestamp` — SEL-1, 2026-12-03, replacing the single-column
`idx_events_instance`), so a filtered page is read in `(timestamp, id)` order and stops at the
page limit. `SiteEventLogSchema.Apply` drops the superseded single-column indexes in place on
first boot.
- **Keyword search**: Free-text search on message and source fields (SQLite LIKE query). Useful for finding events by script name, alarm name, or error message across all instances. The `LIKE` is a leading-wildcard full scan, so a keyword search is **bounded to a time window**: a query with no `From` (or a range wider than `ScadaBridge:SiteEventLog:KeywordSearchMaxWindow`, default 7 days) is clamped server-side to `(To ?? now) - window`, not rejected (review 2026-10-21 02/P1).
- Results are **paginated** with a configurable page size (default: 500 events). Each response includes a continuation token for fetching additional pages. This prevents broad queries from overwhelming the communication channel.
- The site processes the query locally against SQLite and returns matching results to central. The query runs off the actor thread (`Task.Run` + `PipeTo`) on its own short-lived read connection — WAL readers do not block the single writer, so a slow scan can no longer hold the logger's write lock and overflow the bounded write queue (review 2026-10-21 02/P1). The storage-cap trim tracks its row count locally (re-read from the database after the first batch and every 10th batch) and runs `PRAGMA incremental_vacuum` once per tick rather than per batch (02/P4).
@@ -235,6 +235,14 @@ public class AuditLogEntityTypeConfiguration : IEntityTypeConfiguration<AuditLog
.IsDescending(false, false, true)
.HasDatabaseName("IX_AuditLog_Channel_Status_Occurred");
// AUD-5: the per-channel retention purge (DELETE TOP (@batch) ... WHERE Category =
// @channel AND OccurredAtUtc < @threshold) had no index with the two predicates
// adjacent — Status sits between them in IX_AuditLog_Channel_Status_Occurred — so each
// batch scanned most of the table. Created via raw SQL ON ps_AuditLog_Month so it stays
// partition-aligned for the partition-switch purge (AuditLogChannelOccurredIndex).
builder.HasIndex(e => new { e.Channel, e.OccurredAtUtc })
.HasDatabaseName("IX_AuditLog_Channel_Occurred");
builder.HasIndex(e => new { e.Target, e.OccurredAtUtc })
.IsDescending(false, true)
.HasFilter("[Target] IS NOT NULL")
@@ -769,10 +769,10 @@ VALUES
pBatch.Value = (int)Math.Min(batchSize, maxRows - totalDeleted);
cmd.Parameters.Add(pBatch);
var pChannel = cmd.CreateParameter();
pChannel.ParameterName = "@channel";
pChannel.Value = channel;
cmd.Parameters.Add(pChannel);
// AUD-5: bind as varchar(32) to match the Category column. An untyped string
// parameter goes out as nvarchar, which under a SQL collation converts the
// column side and rules out a seek on IX_AuditLog_Channel_Occurred.
AddParameter(cmd, "@channel", SqlDbType.VarChar, size: 32, channel);
var pThreshold = cmd.CreateParameter();
pThreshold.ParameterName = "@threshold";
@@ -90,9 +90,10 @@ public class EventLogPurgeService : BackgroundService
private const double TablePageFillFactor = 0.78;
/// <summary>
/// Number of secondary indexes on <c>site_events</c>: timestamp, instance_id,
/// Number of secondary indexes on <c>site_events</c>: timestamp, (instance_id, timestamp),
/// (event_type, timestamp) and (severity, timestamp). The sampled <c>indexed_bytes</c>
/// charges every covered column once per index, hence <c>3 * octet_length(timestamp)</c>.
/// charges every covered column once per index, hence <c>4 * octet_length(timestamp)</c>
/// (SEL-1 added timestamp to the instance index).
/// </summary>
private const int IndexedColumnCount = 4;
@@ -734,7 +735,7 @@ public class EventLogPurgeService : BackgroundService
+ octet_length(severity) + COALESCE(octet_length(instance_id), 0)
+ octet_length(source) + octet_length(message)
+ COALESCE(octet_length(details), 0) AS payload_bytes,
(3 * octet_length(timestamp)) + octet_length(event_type)
(4 * octet_length(timestamp)) + octet_length(event_type)
+ octet_length(severity) + COALESCE(octet_length(instance_id), 0)
AS indexed_bytes
FROM site_events LIMIT {SizeSampleRows}
@@ -746,7 +747,7 @@ public class EventLogPurgeService : BackgroundService
+ octet_length(severity) + COALESCE(octet_length(instance_id), 0)
+ octet_length(source) + octet_length(message)
+ COALESCE(octet_length(details), 0) AS payload_bytes,
(3 * octet_length(timestamp)) + octet_length(event_type)
(4 * octet_length(timestamp)) + octet_length(event_type)
+ octet_length(severity) + COALESCE(octet_length(instance_id), 0)
AS indexed_bytes
FROM site_events ORDER BY rowid DESC LIMIT {SizeSampleRows}
@@ -67,7 +67,8 @@ public static class SiteEventLogSchema
details TEXT
);
CREATE INDEX IF NOT EXISTS idx_events_timestamp ON site_events(timestamp);
CREATE INDEX IF NOT EXISTS idx_events_instance ON site_events(instance_id);
DROP INDEX IF EXISTS idx_events_instance;
CREATE INDEX IF NOT EXISTS idx_events_instance_timestamp ON site_events(instance_id, timestamp);
DROP INDEX IF EXISTS idx_events_type;
DROP INDEX IF EXISTS idx_events_severity;
CREATE INDEX IF NOT EXISTS idx_events_type_timestamp ON site_events(event_type, timestamp);
@@ -85,6 +86,11 @@ public static class SiteEventLogSchema
// part of LocalDb's replicated-table digest, so a pair may upgrade one node at a
// time as far as this change is concerned.
//
// SEL-1 (2026-12-03): the instance_id index got the same treatment — the Instances
// page drill-in filters by instance and orders by (timestamp, id), which the old
// single-column idx_events_instance could only answer by fetching and sorting every
// row of that instance. Dropped and rebuilt in place on first boot, like #123.
//
// The query service also supports keyword search via leading-wildcard
// LIKE on message/source. A leading-wildcard LIKE cannot use a B-tree
// index, so that path intentionally full-scans; severity/event_type/
@@ -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();