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
@@ -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 — <c>$pending</c>, <c>$pushAbandoned</c>,
/// <c>$rejected</c> — that the reconciliation pull serves and retires.
/// </summary>
/// <summary>
/// AUD-3: the owed states as SQL literals, shared by the <c>IX_fwd_owed</c> 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.
/// </summary>
internal static readonly string OwedStatesSql =
$"'{AuditForwardState.Pending}', '{SiteAuditForwardStates.PushAbandoned}', '{SiteAuditForwardStates.Rejected}'";
/// <summary>The connection string both connections were opened with (AUD-2 regression surface).</summary>
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;
""";
@@ -233,6 +233,44 @@ public class SiteAuditTelemetryActor : ReceiveActor
}
}
/// <summary>
/// AUD-7: builds the per-drain tracking lookup. With an <see cref="IOperationTrackingBatchReader"/>
/// 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.
/// </summary>
private async Task<Func<TrackedOperationId, Task<TrackingStatusSnapshot?>>> PrefetchTrackingAsync(
IReadOnlyList<AuditEvent> 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<TrackingStatusSnapshot?>(ex);
}
}
var memo = new Dictionary<TrackedOperationId, TrackingStatusSnapshot?>();
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;
};
}
/// <summary>
/// Combined-telemetry drain. Reads cached-lifecycle audit
/// rows, joins each with the matching <see cref="IOperationTrackingStore"/>
@@ -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)
@@ -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;
/// <summary>
/// Optional batched read surface of an <see cref="IOperationTrackingStore"/> (AUD-7).
/// </summary>
/// <remarks>
/// Kept as a separate interface rather than a new <see cref="IOperationTrackingStore"/> member so
/// existing implementations and test doubles are untouched: a consumer probes for it and falls
/// back to per-id <see cref="IOperationTrackingStore.GetStatusAsync"/> when it is absent. The
/// read has the same read-your-writes guarantee as <c>GetStatusAsync</c>, but pays the writer
/// queue barrier once for the whole set instead of once per id.
/// </remarks>
public interface IOperationTrackingBatchReader
{
/// <summary>
/// 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.
/// </summary>
/// <param name="ids">The operation ids to read; duplicates are ignored.</param>
/// <param name="ct">Cancellation token.</param>
/// <returns>The snapshots found, keyed by id.</returns>
Task<IReadOnlyDictionary<TrackedOperationId, TrackingStatusSnapshot>> GetStatusManyAsync(
IReadOnlyCollection<TrackedOperationId> ids,
CancellationToken ct = default);
}
@@ -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(