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
+11
View File
@@ -270,6 +270,17 @@ know. `SourceNode` is stamped by the
writing node itself (`node-a` / `node-b`) at append time and travels with the row
through telemetry and reconciliation unchanged.
**Connections and indexes (WP6, 2026-12-03).** The writer and the read-only callers use
two *private-cache* WAL connections (AUD-2 — `Cache=Shared` made them share table-level
locks, so a long backlog scan stalled the batch writer); only the in-memory test override
keeps a shared cache. The reconciliation pull reads the owed states through the partial
index `IX_fwd_owed (OccurredAtUtc, EventId) WHERE ForwardState IN ('Pending','PushAbandoned','Rejected')`,
so each page is an ordered range read that stops at the limit (AUD-3; 1 M owed rows:
3.5 s → <1 ms per 256-row page), and the retention purge seeks `IX_fwd` on
`(ForwardState, IsCachedKind, OccurredAtUtc)` instead of walking each state's whole range
(AUD-4). The cached-telemetry drain resolves a batch's tracking snapshots with one batched
read of its distinct operation ids (AUD-7).
**Site SQLite retention rule (hard invariant):**
> A row is eligible for purge only when both `OccurredAtUtc < retention threshold` AND `ForwardState IN ('Forwarded', 'Reconciled')`. Pending rows — and the owed push-exit states `PushAbandoned` / `Rejected` — are never purged.
@@ -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(
@@ -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;
}
}
@@ -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]