From 04e39690719d38a34fb6339a2ca9956e1e8759a2 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 10:00:42 -0500 Subject: [PATCH] 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 --- docs/requirements/Component-AuditLog.md | 4 +++- .../Component-SiteEventLogging.md | 7 ++++++ .../AuditLogEntityTypeConfiguration.cs | 8 +++++++ .../Repositories/AuditLogRepository.cs | 8 +++---- .../EventLogPurgeService.cs | 9 ++++---- .../SiteEventLogSchema.cs | 8 ++++++- .../Repositories/AuditPurgeBudgetTests.cs | 23 +++++++++++++++++++ .../SchemaIndexTests.cs | 3 ++- .../SiteEventLogSchemaTests.cs | 2 +- .../SiteEventsSchemaCalibrationTests.cs | 8 +++---- 10 files changed, 64 insertions(+), 16 deletions(-) diff --git a/docs/requirements/Component-AuditLog.md b/docs/requirements/Component-AuditLog.md index ac5eba56..b81587c8 100644 --- a/docs/requirements/Component-AuditLog.md +++ b/docs/requirements/Component-AuditLog.md @@ -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 diff --git a/docs/requirements/Component-SiteEventLogging.md b/docs/requirements/Component-SiteEventLogging.md index 01c592e0..edcbf412 100644 --- a/docs/requirements/Component-SiteEventLogging.md +++ b/docs/requirements/Component-SiteEventLogging.md @@ -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). diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Configurations/AuditLogEntityTypeConfiguration.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Configurations/AuditLogEntityTypeConfiguration.cs index 6a0fe5a3..df8cff37 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Configurations/AuditLogEntityTypeConfiguration.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Configurations/AuditLogEntityTypeConfiguration.cs @@ -235,6 +235,14 @@ public class AuditLogEntityTypeConfiguration : IEntityTypeConfiguration 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") diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/AuditLogRepository.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/AuditLogRepository.cs index 1c6daddc..9580b291 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/AuditLogRepository.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/AuditLogRepository.cs @@ -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"; diff --git a/src/ZB.MOM.WW.ScadaBridge.SiteEventLogging/EventLogPurgeService.cs b/src/ZB.MOM.WW.ScadaBridge.SiteEventLogging/EventLogPurgeService.cs index a9d12d7a..45cc347e 100644 --- a/src/ZB.MOM.WW.ScadaBridge.SiteEventLogging/EventLogPurgeService.cs +++ b/src/ZB.MOM.WW.ScadaBridge.SiteEventLogging/EventLogPurgeService.cs @@ -90,9 +90,10 @@ public class EventLogPurgeService : BackgroundService private const double TablePageFillFactor = 0.78; /// - /// Number of secondary indexes on site_events: timestamp, instance_id, + /// Number of secondary indexes on site_events: timestamp, (instance_id, timestamp), /// (event_type, timestamp) and (severity, timestamp). The sampled indexed_bytes - /// charges every covered column once per index, hence 3 * octet_length(timestamp). + /// charges every covered column once per index, hence 4 * octet_length(timestamp) + /// (SEL-1 added timestamp to the instance index). /// 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} diff --git a/src/ZB.MOM.WW.ScadaBridge.SiteEventLogging/SiteEventLogSchema.cs b/src/ZB.MOM.WW.ScadaBridge.SiteEventLogging/SiteEventLogSchema.cs index 04581b72..cd48a6b4 100644 --- a/src/ZB.MOM.WW.ScadaBridge.SiteEventLogging/SiteEventLogSchema.cs +++ b/src/ZB.MOM.WW.ScadaBridge.SiteEventLogging/SiteEventLogSchema.cs @@ -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/ diff --git a/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Repositories/AuditPurgeBudgetTests.cs b/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Repositories/AuditPurgeBudgetTests.cs index 3fe398fc..7b17962c 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Repositories/AuditPurgeBudgetTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Repositories/AuditPurgeBudgetTests.cs @@ -24,10 +24,31 @@ public class AuditPurgeBudgetTests Assert.Equal(ConnectionState.Closed, connection.State); } + /// + /// 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. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task ChannelParameter_IsBoundAsVarchar32() + { + using var connection = new BackloggedConnection(); + await using var context = new ScadaBridgeDbContext(new DbContextOptionsBuilder() + .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 { /// Gets the batch sizes requested by the purge, in order. public List RequestedBatches { get; } = new(); + /// Gets the SQL type and size of each bound @channel parameter, in order. + public List<(SqlDbType Type, int Size)> ChannelParameters { get; } = new(); private ConnectionState _state; /// [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; } /// diff --git a/tests/ZB.MOM.WW.ScadaBridge.SiteEventLogging.Tests/SchemaIndexTests.cs b/tests/ZB.MOM.WW.ScadaBridge.SiteEventLogging.Tests/SchemaIndexTests.cs index 86199a25..6c7d0ec8 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.SiteEventLogging.Tests/SchemaIndexTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.SiteEventLogging.Tests/SchemaIndexTests.cs @@ -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'"; diff --git a/tests/ZB.MOM.WW.ScadaBridge.SiteEventLogging.Tests/SiteEventLogSchemaTests.cs b/tests/ZB.MOM.WW.ScadaBridge.SiteEventLogging.Tests/SiteEventLogSchemaTests.cs index 86d37bee..8a0211a5 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.SiteEventLogging.Tests/SiteEventLogSchemaTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.SiteEventLogging.Tests/SiteEventLogSchemaTests.cs @@ -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); } diff --git a/tests/ZB.MOM.WW.ScadaBridge.SiteEventLogging.Tests/SiteEventsSchemaCalibrationTests.cs b/tests/ZB.MOM.WW.ScadaBridge.SiteEventLogging.Tests/SiteEventsSchemaCalibrationTests.cs index e11b3b45..c2e28e96 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.SiteEventLogging.Tests/SiteEventsSchemaCalibrationTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.SiteEventLogging.Tests/SiteEventsSchemaCalibrationTests.cs @@ -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 /// The columns the index is expected to cover, comma-separated, in key order. [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();