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<?) 0.06 ms
AUD-7: new optional Commons IOperationTrackingBatchReader (separate interface
so test doubles/implementations are untouched); OperationTrackingStore
implements GetStatusManyAsync (one writer-queue barrier, chunked IN reads on
one connection). SiteAuditTelemetryActor resolves a drain's distinct ids with
one batched read when available, else memoises per-id reads per drain.
A BatchSize-256 drain: 256 sequential barriers + 256 connections -> 1 barrier,
1 connection, 1 query (ids sharing an operation are read once).
This commit is contained in:
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// WP6 task 6.4: connection isolation (AUD-2) and the index shapes behind the reconciliation
|
||||
/// pull (AUD-3) and the retention purge (AUD-4).
|
||||
/// </summary>
|
||||
public class SqliteAuditWriterIndexingTests : IDisposable
|
||||
{
|
||||
private readonly string _dbPath = Path.Combine(Path.GetTempPath(), $"audit-idx-{Guid.NewGuid():N}.db");
|
||||
|
||||
/// <summary>Deletes the temp database files.</summary>
|
||||
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<SqliteAuditWriter>.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);
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[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");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[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<Guid>();
|
||||
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<Guid>();
|
||||
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"));
|
||||
}
|
||||
|
||||
/// <summary>AUD-4: the purge page seeks IX_fwd on (state, kind, age) rather than state alone.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[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<?"));
|
||||
}
|
||||
|
||||
private async Task<List<string>> 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<string>();
|
||||
await using var r = await cmd.ExecuteReaderAsync();
|
||||
while (await r.ReadAsync()) plan.Add(r.GetString(3));
|
||||
return plan;
|
||||
}
|
||||
}
|
||||
+49
@@ -416,6 +416,55 @@ public class SiteAuditTelemetryActorTests : TestKit
|
||||
Assert.Equal(expectedIds, emittedEventIds);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task CachedDrain_ResolvesTrackingWithOneBatchedRead()
|
||||
{
|
||||
var store = Substitute.For<IOperationTrackingStore, IOperationTrackingBatchReader>();
|
||||
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<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromResult<IReadOnlyList<AuditEvent>>(Array.Empty<AuditEvent>()));
|
||||
_queue.ReadPendingCachedTelemetryAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||
.Returns(
|
||||
Task.FromResult<IReadOnlyList<AuditEvent>>(cachedRows),
|
||||
Task.FromResult<IReadOnlyList<AuditEvent>>(Array.Empty<AuditEvent>()));
|
||||
((IOperationTrackingBatchReader)store)
|
||||
.GetStatusManyAsync(Arg.Any<IReadOnlyCollection<TrackedOperationId>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(c => Task.FromResult<IReadOnlyDictionary<TrackedOperationId, TrackingStatusSnapshot>>(
|
||||
c.Arg<IReadOnlyCollection<TrackedOperationId>>().ToDictionary(id => id, id => NewSnapshot(id))));
|
||||
_client.IngestCachedTelemetryAsync(Arg.Any<CachedTelemetryBatch>(), Arg.Any<CancellationToken>())
|
||||
.Returns(call =>
|
||||
{
|
||||
var ack = new IngestAck();
|
||||
foreach (var packet in call.Arg<CachedTelemetryBatch>().Packets)
|
||||
ack.AcceptedEventIds.Add(packet.AuditEvent.EventId);
|
||||
return Task.FromResult(ack);
|
||||
});
|
||||
|
||||
Sys.ActorOf(Props.Create(() => new SiteAuditTelemetryActor(
|
||||
_queue, _client, Opts(), NullLogger<SiteAuditTelemetryActor>.Instance,
|
||||
(IOperationTrackingStore?)store)));
|
||||
|
||||
await AwaitAssertAsync(async () =>
|
||||
await _queue.Received(1).MarkForwardedAsync(
|
||||
Arg.Is<IReadOnlyList<Guid>>(g => g.Count == 3), Arg.Any<CancellationToken>()),
|
||||
TimeSpan.FromSeconds(5));
|
||||
await ((IOperationTrackingBatchReader)store).Received(1).GetStatusManyAsync(
|
||||
Arg.Is<IReadOnlyCollection<TrackedOperationId>>(ids => ids.Count == 2), Arg.Any<CancellationToken>());
|
||||
await store.DidNotReceiveWithAnyArgs().GetStatusAsync(default, default);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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
|
||||
|
||||
@@ -282,6 +282,33 @@ public class OperationTrackingStoreTests : IDisposable
|
||||
Assert.Equal("node-a", snapshot!.SourceNode);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[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<TrackedOperationId>()));
|
||||
}
|
||||
|
||||
/// <summary>Verifies that recording an enqueue persists a null source node.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
|
||||
Reference in New Issue
Block a user