From 9f03726fc7613e68db7c2397951fc69aa6599ae0 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 09:58:29 -0500 Subject: [PATCH] perf(audit-log): private-cache connections, owed-range pull index, age-seekable purge, batched tracking reads (AUD-2, AUD-3, AUD-4, AUD-7, WP6 task 6.4) AUD-2: drop Cache=Shared from the file-backed site audit connection string (kept only by the in-memory test override). Two private WAL connections no longer share table-level locks. Test OpenReadTransaction_DoesNotStallTheWriter (deferred read txn open on a connection with the writer's connection string): with Cache=Shared the write timed out (>5 s; would retry to the 30 s command timeout and fault); without it the write completes in well under 1 s. AUD-3: new partial index IX_fwd_owed (OccurredAtUtc, EventId) WHERE ForwardState IN (owed states); ReadPendingSinceAsync names it (INDEXED BY), repeats the literal state list (bound parameters never satisfy a partial index's WHERE), and orders/keysets on fs.EventId (same value, no join for the sort). sqlite3 3.54, 1,000,000 audit rows (90% Pending), no ANALYZE stats, 256-row page: before: SEARCH fs USING INDEX IX_fwd (ForwardState=?) + TEMP B-TREE FOR ORDER BY; 2.6-3.5 s after: SEARCH fs USING INDEX IX_fwd_owed (OccurredAtUtc>?), no sort; 0.6-0.7 ms (keyset page with afterId: 3.6 s -> 0.6 ms) AUD-4: purge page adds IsCachedKind IN (0, 1) so IX_fwd seeks (state, kind, age). same DB, 100k Forwarded rows, nothing expiring (the final short page): before: SEARCH IX_fwd (ForwardState=?) 16.9 ms (linear in retained rows) after: SEARCH IX_fwd (ForwardState=? AND IsCachedKind=? AND OccurredAtUtc 1 barrier, 1 connection, 1 query (ids sharing an operation are read once). --- docs/requirements/Component-AuditLog.md | 11 ++ .../Site/SqliteAuditWriter.cs | 49 ++++++- .../Site/Telemetry/SiteAuditTelemetryActor.cs | 47 +++++- .../Services/IOperationTrackingBatchReader.cs | 28 ++++ .../Tracking/OperationTrackingStore.cs | 59 +++++++- .../Site/SqliteAuditWriterIndexingTests.cs | 138 ++++++++++++++++++ .../Telemetry/SiteAuditTelemetryActorTests.cs | 49 +++++++ .../Tracking/OperationTrackingStoreTests.cs | 27 ++++ 8 files changed, 395 insertions(+), 13 deletions(-) create mode 100644 src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Services/IOperationTrackingBatchReader.cs create mode 100644 tests/ZB.MOM.WW.ScadaBridge.AuditLog.Tests/Site/SqliteAuditWriterIndexingTests.cs diff --git a/docs/requirements/Component-AuditLog.md b/docs/requirements/Component-AuditLog.md index f0af2960..ac5eba56 100644 --- a/docs/requirements/Component-AuditLog.md +++ b/docs/requirements/Component-AuditLog.md @@ -270,6 +270,17 @@ know. `SourceNode` is stamped by the writing node itself (`node-a` / `node-b`) at append time and travels with the row through telemetry and reconciliation unchanged. +**Connections and indexes (WP6, 2026-12-03).** The writer and the read-only callers use +two *private-cache* WAL connections (AUD-2 — `Cache=Shared` made them share table-level +locks, so a long backlog scan stalled the batch writer); only the in-memory test override +keeps a shared cache. The reconciliation pull reads the owed states through the partial +index `IX_fwd_owed (OccurredAtUtc, EventId) WHERE ForwardState IN ('Pending','PushAbandoned','Rejected')`, +so each page is an ordered range read that stops at the limit (AUD-3; 1 M owed rows: +3.5 s → <1 ms per 256-row page), and the retention purge seeks `IX_fwd` on +`(ForwardState, IsCachedKind, OccurredAtUtc)` instead of walking each state's whole range +(AUD-4). The cached-telemetry drain resolves a batch's tracking snapshots with one batched +read of its distinct operation ids (AUD-7). + **Site SQLite retention rule (hard invariant):** > A row is eligible for purge only when both `OccurredAtUtc < retention threshold` AND `ForwardState IN ('Forwarded', 'Reconciled')`. Pending rows — and the owed push-exit states `PushAbandoned` / `Rejected` — are never purged. diff --git a/src/ZB.MOM.WW.ScadaBridge.AuditLog/Site/SqliteAuditWriter.cs b/src/ZB.MOM.WW.ScadaBridge.AuditLog/Site/SqliteAuditWriter.cs index b1728e1e..aaa06dc1 100644 --- a/src/ZB.MOM.WW.ScadaBridge.AuditLog/Site/SqliteAuditWriter.cs +++ b/src/ZB.MOM.WW.ScadaBridge.AuditLog/Site/SqliteAuditWriter.cs @@ -102,8 +102,18 @@ public class SqliteAuditWriter : IAuditWriter, ISiteAuditQueue, ISiteAuditPushLi _logger = logger; _nodeIdentity = nodeIdentity; + // AUD-2: a PRIVATE cache per connection. With Cache=Shared both connections shared one + // cache and its table-level locks, so WAL snapshot isolation did not apply between them — + // a long backlog scan on the read connection stalled the batch writer (in 150 ms + // SQLITE_LOCKED retry sleeps, up to the command timeout) and vice versa. Two private WAL + // connections let reads run against a snapshot while the writer commits. The busy + // timeout stays Microsoft.Data.Sqlite's default command timeout (30 s), which only a + // second writer could ever hit — there is one write connection. (The in-memory test + // override still uses Mode=Memory;Cache=Shared, which needs the shared cache to share + // one database at all.) var connectionString = connectionStringOverride - ?? $"Data Source={_options.DatabasePath};Cache=Shared"; + ?? $"Data Source={_options.DatabasePath}"; + ConnectionString = connectionString; _connection = new SqliteConnection(connectionString); _connection.Open(); @@ -227,7 +237,7 @@ public class SqliteAuditWriter : IAuditWriter, ISiteAuditQueue, ISiteAuditPushLi } using var cmd = _connection.CreateCommand(); - cmd.CommandText = """ + cmd.CommandText = $""" -- Canonical, append-only / write-once: the 10 fields of the canonical -- ZB.MOM.WW.Audit.AuditEvent stored directly (DetailsJson carries the -- ScadaBridge domain fields). No forwarding state lives here — that is @@ -268,6 +278,17 @@ public class SqliteAuditWriter : IAuditWriter, ISiteAuditQueue, ISiteAuditPushLi CREATE INDEX IF NOT EXISTS IX_fwd ON audit_forward_state (ForwardState, IsCachedKind, OccurredAtUtc); + -- AUD-3: the reconciliation pull reads the OWED states ordered by + -- (OccurredAtUtc, EventId); IX_fwd cannot serve that across an IN of three + -- states, so every page scanned + sorted the whole owed backlog. This partial + -- index is exactly the pull's range and order, so a page is an ordered range + -- read that stops at the limit. The query names it with INDEXED BY and repeats + -- the same literal state list (a partial index is only usable when the query's + -- WHERE implies the index's). Additive and idempotent. + CREATE INDEX IF NOT EXISTS IX_fwd_owed + ON audit_forward_state (OccurredAtUtc, EventId) + WHERE ForwardState IN ({OwedStatesSql}); + -- Node-local key/value state that must survive a process restart. Holds the -- reconciliation pull's served-rows high-water mark ('max_served_rowid'), so a -- restart no longer resets the bound that lets a covering cursor retire rows the @@ -866,7 +887,8 @@ public class SqliteAuditWriter : IAuditWriter, ISiteAuditQueue, ISiteAuditPushLi ? "fs.OccurredAtUtc >= $since" // Composite keyset, lexicographic on (OccurredAtUtc, EventId) — the same // ordering the query applies, so it is a strict "everything after this row". - : "(fs.OccurredAtUtc > $since OR (fs.OccurredAtUtc = $since AND ae.EventId > $afterId))"; + // The OccurredAtUtc >= $since conjunct is implied but lets the index seek. + : "fs.OccurredAtUtc >= $since AND (fs.OccurredAtUtc > $since OR (fs.OccurredAtUtc = $since AND fs.EventId > $afterId))"; // fs.rowid rides along as an 11th column purely to maintain // _maxServedRowId — the insertion-order high-water mark that bounds @@ -876,14 +898,13 @@ public class SqliteAuditWriter : IAuditWriter, ISiteAuditQueue, ISiteAuditPushLi SELECT ae.EventId, ae.OccurredAtUtc, ae.Actor, ae.Action, ae.Outcome, ae.Category, ae.Target, ae.SourceNode, ae.CorrelationId, ae.DetailsJson, fs.rowid - FROM audit_event ae - JOIN audit_forward_state fs ON fs.EventId = ae.EventId - WHERE fs.ForwardState IN ($pending, $pushAbandoned, $rejected) + FROM audit_forward_state fs INDEXED BY IX_fwd_owed + JOIN audit_event ae ON ae.EventId = fs.EventId + WHERE fs.ForwardState IN ({OwedStatesSql}) AND {cursorPredicate} - ORDER BY fs.OccurredAtUtc ASC, ae.EventId ASC + ORDER BY fs.OccurredAtUtc ASC, fs.EventId ASC LIMIT $limit; """; - AddOwedStateParameters(cmd); // Normalise to UTC ISO-8601 round-trip format to match how OccurredAtUtc // is stored on insert ("o" format) — string comparison is monotonic for // that encoding so we can index-scan against it. @@ -931,6 +952,17 @@ public class SqliteAuditWriter : IAuditWriter, ISiteAuditQueue, ISiteAuditPushLi /// Binds the three "owed to central" states — $pending, $pushAbandoned, /// $rejected — that the reconciliation pull serves and retires. /// + /// + /// AUD-3: the owed states as SQL literals, shared by the IX_fwd_owed partial-index + /// definition and the pull query that uses it — SQLite only uses a partial index when the + /// query's WHERE implies the index's, which a bound parameter never does. + /// + internal static readonly string OwedStatesSql = + $"'{AuditForwardState.Pending}', '{SiteAuditForwardStates.PushAbandoned}', '{SiteAuditForwardStates.Rejected}'"; + + /// The connection string both connections were opened with (AUD-2 regression surface). + internal string ConnectionString { get; } + private static void AddOwedStateParameters(SqliteCommand cmd) { cmd.Parameters.AddWithValue("$pending", AuditForwardState.Pending.ToString()); @@ -1535,6 +1567,7 @@ public class SqliteAuditWriter : IAuditWriter, ISiteAuditQueue, ISiteAuditPushLi CREATE TEMP TABLE purge_ids AS SELECT EventId FROM audit_forward_state WHERE ForwardState IN ($forwarded, $reconciled) + AND IsCachedKind IN (0, 1) -- AUD-4: lets IX_fwd seek (state, kind, age) instead of walking each state's whole range AND OccurredAtUtc < $cutoff LIMIT $limit; """; diff --git a/src/ZB.MOM.WW.ScadaBridge.AuditLog/Site/Telemetry/SiteAuditTelemetryActor.cs b/src/ZB.MOM.WW.ScadaBridge.AuditLog/Site/Telemetry/SiteAuditTelemetryActor.cs index 4fb0253e..3790800a 100644 --- a/src/ZB.MOM.WW.ScadaBridge.AuditLog/Site/Telemetry/SiteAuditTelemetryActor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.AuditLog/Site/Telemetry/SiteAuditTelemetryActor.cs @@ -233,6 +233,44 @@ public class SiteAuditTelemetryActor : ReceiveActor } } + /// + /// AUD-7: builds the per-drain tracking lookup. With an + /// the distinct ids are read in one batched call (a fault there surfaces per row, exactly as a + /// per-id fault did, so those rows stay Pending); otherwise each distinct id is read once and + /// memoised for the drain. + /// + private async Task>> PrefetchTrackingAsync( + IReadOnlyList pending, CancellationToken ct) + { + var store = _trackingStore!; + if (store is IOperationTrackingBatchReader batchReader) + { + var ids = pending + .Where(r => r.CorrelationId is not null) + .Select(r => new TrackedOperationId(r.CorrelationId!.Value)) + .Distinct() + .ToList(); + try + { + var found = await batchReader.GetStatusManyAsync(ids, ct).ConfigureAwait(false); + return id => Task.FromResult(found.TryGetValue(id, out var s) ? s : null); + } + catch (Exception ex) + { + return _ => Task.FromException(ex); + } + } + + var memo = new Dictionary(); + return async id => + { + if (memo.TryGetValue(id, out var cached)) return cached; + var snapshot = await store.GetStatusAsync(id, ct).ConfigureAwait(false); + memo[id] = snapshot; + return snapshot; + }; + } + /// /// Combined-telemetry drain. Reads cached-lifecycle audit /// rows, joins each with the matching @@ -287,6 +325,12 @@ public class SiteAuditTelemetryActor : ReceiveActor var graceSeconds = Math.Max(0, _options.CachedTrackingGraceSeconds); var abandonBefore = DateTime.UtcNow - TimeSpan.FromSeconds(graceSeconds); + // AUD-7: the tracking store is a single-writer queue whose every read waits behind + // all queued writes. Resolve the batch's distinct operation ids ONCE — one barrier + // for the drain when the store offers a batched read, and never the same id twice + // (several lifecycle rows of one operation share it) otherwise. + var lookup = await PrefetchTrackingAsync(pending, ct).ConfigureAwait(false); + foreach (var auditRow in pending) { if (auditRow.CorrelationId is null) @@ -302,8 +346,7 @@ public class SiteAuditTelemetryActor : ReceiveActor TrackingStatusSnapshot? snapshot; try { - snapshot = await _trackingStore - .GetStatusAsync(new TrackedOperationId(auditRow.CorrelationId.Value), ct) + snapshot = await lookup(new TrackedOperationId(auditRow.CorrelationId.Value)) .ConfigureAwait(false); } catch (Exception ex) diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Services/IOperationTrackingBatchReader.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Services/IOperationTrackingBatchReader.cs new file mode 100644 index 00000000..a3efb977 --- /dev/null +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Services/IOperationTrackingBatchReader.cs @@ -0,0 +1,28 @@ +using ZB.MOM.WW.ScadaBridge.Commons.Types; + +// Same namespace convention as IOperationTrackingStore (see the note there). +namespace ZB.MOM.WW.ScadaBridge.Commons.Interfaces; + +/// +/// Optional batched read surface of an (AUD-7). +/// +/// +/// Kept as a separate interface rather than a new member so +/// existing implementations and test doubles are untouched: a consumer probes for it and falls +/// back to per-id when it is absent. The +/// read has the same read-your-writes guarantee as GetStatusAsync, but pays the writer +/// queue barrier once for the whole set instead of once per id. +/// +public interface IOperationTrackingBatchReader +{ + /// + /// Returns the latest snapshot of each supplied id that has a tracking row. Ids with no row + /// (purged or never recorded) are absent from the result. + /// + /// The operation ids to read; duplicates are ignored. + /// Cancellation token. + /// The snapshots found, keyed by id. + Task> GetStatusManyAsync( + IReadOnlyCollection ids, + CancellationToken ct = default); +} diff --git a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Tracking/OperationTrackingStore.cs b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Tracking/OperationTrackingStore.cs index ec2e37b4..179607fb 100644 --- a/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Tracking/OperationTrackingStore.cs +++ b/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/Tracking/OperationTrackingStore.cs @@ -51,7 +51,7 @@ namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Tracking; /// path. /// /// -public class OperationTrackingStore : IOperationTrackingStore, IAsyncDisposable, IDisposable +public class OperationTrackingStore : IOperationTrackingStore, IOperationTrackingBatchReader, IAsyncDisposable, IDisposable { /// Queue bound; past it Record*Async waits (never drops). internal const int MaxQueuedWrites = 8192; @@ -536,7 +536,61 @@ public class OperationTrackingStore : IOperationTrackingStore, IAsyncDisposable, return null; } - return new TrackingStatusSnapshot( + return ReadSnapshot(reader); + } + + /// Most ids bound into one IN (…) read (well under SQLite's parameter limit). + private const int MaxIdsPerStatusRead = 500; + + /// + /// + /// AUD-7: one writer-queue barrier for the whole set, then chunked IN (…) reads on one + /// connection — instead of a barrier + connection + query per id. + /// + public async Task> GetStatusManyAsync( + IReadOnlyCollection ids, + CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(ids); + var result = new Dictionary(); + if (ids.Count == 0) + { + return result; + } + + await WaitForQueuedWritesAsync(ct).ConfigureAwait(false); + ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposeState) != 0, this); + + await using var readConnection = _localDb.CreateConnection(); + foreach (var chunk in ids.Select(i => i.ToString()).Distinct(StringComparer.Ordinal).Chunk(MaxIdsPerStatusRead)) + { + await using var cmd = readConnection.CreateCommand(); + var names = new string[chunk.Length]; + for (var i = 0; i < chunk.Length; i++) + { + names[i] = "$id" + i.ToString(CultureInfo.InvariantCulture); + cmd.Parameters.AddWithValue(names[i], chunk[i]); + } + + cmd.CommandText = + "SELECT TrackedOperationId, Kind, TargetSummary, Status, " + + "RetryCount, LastError, HttpStatus, CreatedAtUtc, UpdatedAtUtc, TerminalAtUtc, " + + "SourceInstanceId, SourceScript, SourceNode " + + "FROM OperationTracking WHERE TrackedOperationId IN (" + string.Join(", ", names) + ");"; + + await using var reader = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false); + while (await reader.ReadAsync(ct).ConfigureAwait(false)) + { + var snapshot = ReadSnapshot(reader); + result[snapshot.Id] = snapshot; + } + } + + return result; + } + + private static TrackingStatusSnapshot ReadSnapshot(SqliteDataReader reader) => + new TrackingStatusSnapshot( Id: TrackedOperationId.Parse(reader.GetString(0)), Kind: reader.GetString(1), TargetSummary: reader.IsDBNull(2) ? null : reader.GetString(2), @@ -550,7 +604,6 @@ public class OperationTrackingStore : IOperationTrackingStore, IAsyncDisposable, SourceInstanceId: reader.IsDBNull(10) ? null : reader.GetString(10), SourceScript: reader.IsDBNull(11) ? null : reader.GetString(11), SourceNode: reader.IsDBNull(12) ? null : reader.GetString(12)); - } /// public async Task PurgeTerminalAsync( diff --git a/tests/ZB.MOM.WW.ScadaBridge.AuditLog.Tests/Site/SqliteAuditWriterIndexingTests.cs b/tests/ZB.MOM.WW.ScadaBridge.AuditLog.Tests/Site/SqliteAuditWriterIndexingTests.cs new file mode 100644 index 00000000..ef712f01 --- /dev/null +++ b/tests/ZB.MOM.WW.ScadaBridge.AuditLog.Tests/Site/SqliteAuditWriterIndexingTests.cs @@ -0,0 +1,138 @@ +using Microsoft.Data.Sqlite; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using ZB.MOM.WW.Audit; +using ZB.MOM.WW.ScadaBridge.AuditLog.Site; +using ZB.MOM.WW.ScadaBridge.AuditLog.Tests.TestSupport; +using ZB.MOM.WW.ScadaBridge.Commons.Types.Audit; +using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums; + +namespace ZB.MOM.WW.ScadaBridge.AuditLog.Tests.Site; + +/// +/// WP6 task 6.4: connection isolation (AUD-2) and the index shapes behind the reconciliation +/// pull (AUD-3) and the retention purge (AUD-4). +/// +public class SqliteAuditWriterIndexingTests : IDisposable +{ + private readonly string _dbPath = Path.Combine(Path.GetTempPath(), $"audit-idx-{Guid.NewGuid():N}.db"); + + /// Deletes the temp database files. + public void Dispose() + { + SqliteConnection.ClearAllPools(); + foreach (var suffix in new[] { "", "-wal", "-shm" }) + { + try { File.Delete(_dbPath + suffix); } catch { /* best-effort */ } + } + } + + private SqliteAuditWriter CreateWriter() => new( + Options.Create(new SqliteAuditWriterOptions { DatabasePath = _dbPath }), + NullLogger.Instance, + new FakeNodeIdentityProvider()); + + private static AuditEvent NewEvent(DateTime occurredAtUtc) => ScadaBridgeAuditEventFactory.Create( + eventId: Guid.NewGuid(), + occurredAtUtc: occurredAtUtc, + channel: AuditChannel.ApiOutbound, + kind: AuditKind.ApiCall, + status: AuditStatus.Delivered); + + /// + /// AUD-2: an open read transaction on a connection opened like the writer's read connection + /// must not stall the batch writer (it did under Cache=Shared: table-level shared-cache locks). + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task OpenReadTransaction_DoesNotStallTheWriter() + { + await using var writer = CreateWriter(); + Assert.DoesNotContain("Cache=Shared", writer.ConnectionString, StringComparison.OrdinalIgnoreCase); + await writer.WriteAsync(NewEvent(DateTime.UtcNow)); + + await using var reader = new SqliteConnection(writer.ConnectionString); + await reader.OpenAsync(); + await using var tx = reader.BeginTransaction(deferred: true); + await using (var select = reader.CreateCommand()) + { + select.Transaction = tx; + select.CommandText = "SELECT COUNT(*) FROM audit_event"; + Assert.Equal(1L, (long)(await select.ExecuteScalarAsync())!); + } + + var sw = System.Diagnostics.Stopwatch.StartNew(); + await writer.WriteAsync(NewEvent(DateTime.UtcNow)).WaitAsync(TimeSpan.FromSeconds(5)); + sw.Stop(); + Assert.True(sw.ElapsedMilliseconds < 1000, $"writer stalled {sw.ElapsedMilliseconds} ms behind an open read"); + } + + /// + /// AUD-3: the pull pages the owed backlog as an ordered range of IX_fwd_owed (no temp sort), + /// and the keyset cursor still yields every owed row exactly once, in order. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task ReconciliationPull_IsAnOrderedRangeRead_AndPagesCorrectly() + { + await using var writer = CreateWriter(); + var t0 = new DateTime(2026, 11, 1, 0, 0, 0, DateTimeKind.Utc); + var ids = new List(); + for (var i = 0; i < 25; i++) + { + // pairs share an instant so the EventId tiebreak is exercised + var e = NewEvent(t0.AddSeconds(i / 2)); + ids.Add(e.EventId); + await writer.WriteAsync(e); + } + + var served = new List(); + var since = DateTime.MinValue.ToUniversalTime(); + string? afterId = null; + while (true) + { + var page = await writer.ReadPendingSinceAsync(since, 4, afterId); + if (page.Count == 0) break; + served.AddRange(page.Select(p => p.EventId)); + since = page[^1].OccurredAtUtc.UtcDateTime; + afterId = page[^1].EventId.ToString(); + } + Assert.Equal(ids.Count, served.Count); + Assert.Equal(served.Count, served.Distinct().Count()); + + var plan = await PlanAsync($""" + SELECT fs.EventId FROM audit_forward_state fs INDEXED BY IX_fwd_owed + JOIN audit_event ae ON ae.EventId = fs.EventId + WHERE fs.ForwardState IN ({SqliteAuditWriter.OwedStatesSql}) AND fs.OccurredAtUtc >= '2026' + ORDER BY fs.OccurredAtUtc ASC, fs.EventId ASC LIMIT 256 + """); + Assert.Contains(plan, p => p.Contains("IX_fwd_owed")); + Assert.DoesNotContain(plan, p => p.Contains("TEMP B-TREE")); + } + + /// AUD-4: the purge page seeks IX_fwd on (state, kind, age) rather than state alone. + /// A task that represents the asynchronous operation. + [Fact] + public async Task PurgePage_SeeksOnAge() + { + await using (CreateWriter()) { } + var plan = await PlanAsync(""" + SELECT EventId FROM audit_forward_state + WHERE ForwardState IN ('Forwarded', 'Reconciled') AND IsCachedKind IN (0, 1) + AND OccurredAtUtc < '2026' LIMIT 5000 + """); + Assert.Contains(plan, p => p.Contains("IX_fwd") && p.Contains("OccurredAtUtc> PlanAsync(string sql) + { + await using var connection = new SqliteConnection($"Data Source={_dbPath}"); + await connection.OpenAsync(); + await using var cmd = connection.CreateCommand(); + cmd.CommandText = "EXPLAIN QUERY PLAN " + sql; + var plan = new List(); + await using var r = await cmd.ExecuteReaderAsync(); + while (await r.ReadAsync()) plan.Add(r.GetString(3)); + return plan; + } +} diff --git a/tests/ZB.MOM.WW.ScadaBridge.AuditLog.Tests/Site/Telemetry/SiteAuditTelemetryActorTests.cs b/tests/ZB.MOM.WW.ScadaBridge.AuditLog.Tests/Site/Telemetry/SiteAuditTelemetryActorTests.cs index 8d4e4c43..2f5ffd09 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.AuditLog.Tests/Site/Telemetry/SiteAuditTelemetryActorTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.AuditLog.Tests/Site/Telemetry/SiteAuditTelemetryActorTests.cs @@ -416,6 +416,55 @@ public class SiteAuditTelemetryActorTests : TestKit Assert.Equal(expectedIds, emittedEventIds); } + /// + /// AUD-7 (WP6 6.4): a drain resolves its rows' tracking snapshots with ONE batched read of + /// the distinct ids when the store offers it, instead of one writer-queue barrier per row. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task CachedDrain_ResolvesTrackingWithOneBatchedRead() + { + var store = Substitute.For(); + var op = Guid.NewGuid(); + var other = Guid.NewGuid(); + var cachedRows = new[] + { + NewCachedEvent(AuditKind.CachedSubmit, correlationId: op), + NewCachedEvent(AuditKind.ApiCallCached, correlationId: op), + NewCachedEvent(AuditKind.CachedResolve, correlationId: other), + }; + _queue.ReadPendingAsync(Arg.Any(), Arg.Any()) + .Returns(Task.FromResult>(Array.Empty())); + _queue.ReadPendingCachedTelemetryAsync(Arg.Any(), Arg.Any()) + .Returns( + Task.FromResult>(cachedRows), + Task.FromResult>(Array.Empty())); + ((IOperationTrackingBatchReader)store) + .GetStatusManyAsync(Arg.Any>(), Arg.Any()) + .Returns(c => Task.FromResult>( + c.Arg>().ToDictionary(id => id, id => NewSnapshot(id)))); + _client.IngestCachedTelemetryAsync(Arg.Any(), Arg.Any()) + .Returns(call => + { + var ack = new IngestAck(); + foreach (var packet in call.Arg().Packets) + ack.AcceptedEventIds.Add(packet.AuditEvent.EventId); + return Task.FromResult(ack); + }); + + Sys.ActorOf(Props.Create(() => new SiteAuditTelemetryActor( + _queue, _client, Opts(), NullLogger.Instance, + (IOperationTrackingStore?)store))); + + await AwaitAssertAsync(async () => + await _queue.Received(1).MarkForwardedAsync( + Arg.Is>(g => g.Count == 3), Arg.Any()), + TimeSpan.FromSeconds(5)); + await ((IOperationTrackingBatchReader)store).Received(1).GetStatusManyAsync( + Arg.Is>(ids => ids.Count == 2), Arg.Any()); + await store.DidNotReceiveWithAnyArgs().GetStatusAsync(default, default); + } + /// /// Verifies that the tracking-row versions central ACCEPTED are recorded as central acks /// in the tracking store — and only those — so the SiteCalls reconciliation pull stops diff --git a/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Tracking/OperationTrackingStoreTests.cs b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Tracking/OperationTrackingStoreTests.cs index 68389a04..6fb73241 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Tracking/OperationTrackingStoreTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Tracking/OperationTrackingStoreTests.cs @@ -282,6 +282,33 @@ public class OperationTrackingStoreTests : IDisposable Assert.Equal("node-a", snapshot!.SourceNode); } + /// + /// AUD-7 (WP6 6.4): the batched read returns every recorded id (read-your-writes, across + /// more ids than one IN-chunk) and omits ids with no row. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task GetStatusManyAsync_ReturnsRecordedIds_AndOmitsMissing() + { + var (store, _) = CreateStore(nameof(GetStatusManyAsync_ReturnsRecordedIds_AndOmitsMissing)); + await using var _store = store; + + var recorded = Enumerable.Range(0, 1203).Select(_ => TrackedOperationId.New()).ToList(); + foreach (var id in recorded) + { + await store.RecordEnqueueAsync(id, kind: nameof(AuditKind.ApiCallCached), targetSummary: "ERP.GetOrder", + sourceInstanceId: null, sourceScript: null, sourceNode: "node-a"); + } + var missing = TrackedOperationId.New(); + + var found = await store.GetStatusManyAsync(recorded.Append(missing).Append(recorded[0]).ToList()); + + Assert.Equal(recorded.Count, found.Count); + Assert.All(recorded, id => Assert.Equal(id, found[id].Id)); + Assert.False(found.ContainsKey(missing)); + Assert.Empty(await store.GetStatusManyAsync(Array.Empty())); + } + /// Verifies that recording an enqueue persists a null source node. /// A task that represents the asynchronous operation. [Fact]