9f03726fc7
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).
139 lines
5.8 KiB
C#
139 lines
5.8 KiB
C#
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;
|
|
}
|
|
}
|