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
@@ -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)