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:
Joseph Doherty
2026-12-03 09:58:29 -05:00
parent 54416e33bf
commit 9f03726fc7
8 changed files with 395 additions and 13 deletions
@@ -51,7 +51,7 @@ namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Tracking;
/// path.
/// </para>
/// </remarks>
public class OperationTrackingStore : IOperationTrackingStore, IAsyncDisposable, IDisposable
public class OperationTrackingStore : IOperationTrackingStore, IOperationTrackingBatchReader, IAsyncDisposable, IDisposable
{
/// <summary>Queue bound; past it <c>Record*Async</c> waits (never drops).</summary>
internal const int MaxQueuedWrites = 8192;
@@ -536,7 +536,61 @@ public class OperationTrackingStore : IOperationTrackingStore, IAsyncDisposable,
return null;
}
return new TrackingStatusSnapshot(
return ReadSnapshot(reader);
}
/// <summary>Most ids bound into one <c>IN (…)</c> read (well under SQLite's parameter limit).</summary>
private const int MaxIdsPerStatusRead = 500;
/// <inheritdoc/>
/// <remarks>
/// AUD-7: one writer-queue barrier for the whole set, then chunked <c>IN (…)</c> reads on one
/// connection — instead of a barrier + connection + query per id.
/// </remarks>
public async Task<IReadOnlyDictionary<TrackedOperationId, TrackingStatusSnapshot>> GetStatusManyAsync(
IReadOnlyCollection<TrackedOperationId> ids,
CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(ids);
var result = new Dictionary<TrackedOperationId, TrackingStatusSnapshot>();
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));
}
/// <inheritdoc/>
public async Task PurgeTerminalAsync(