fix(audit): reconciliation pulls every site node with a per-(site, node) cursor (AUD-1, WP4 task 4.8)

This commit is contained in:
Joseph Doherty
2026-12-03 10:08:20 -05:00
parent c15bd210f7
commit 4070f7efca
10 changed files with 514 additions and 60 deletions
@@ -47,7 +47,7 @@ namespace ZB.MOM.WW.ScadaBridge.AuditLog.Central;
/// inject a fake invoker so no real HTTP/2 endpoint is required.
/// </para>
/// </remarks>
public sealed class GrpcPullAuditEventsClient : IPullAuditEventsClient
public sealed class GrpcPullAuditEventsClient : IPullAuditEventsClient, IGrpcChannelCachePruner
{
private readonly ISiteEnumerator _sites;
private readonly IPullAuditEventsInvoker _invoker;
@@ -88,17 +88,7 @@ public sealed class GrpcPullAuditEventsClient : IPullAuditEventsClient
return Empty;
}
var request = new ProtoPullRequest
{
// ReadPendingSinceAsync treats DateTime.MinValue as "from the start";
// EnsureUtc keeps Timestamp.FromDateTime happy (it requires UTC kind).
SinceUtc = Timestamp.FromDateTime(EnsureUtc(sinceUtc)),
BatchSize = batchSize,
// Composite-keyset tiebreak (proto field 3), mirroring PullSiteCalls exactly.
// proto3 has no nullable string — an unset/empty AfterId is the site's signal to
// keep the legacy inclusive-timestamp contract (also what a first pull sends).
AfterId = afterId ?? string.Empty,
};
var request = BuildRequest(sinceUtc, afterId, batchSize);
var (reply, transportFault) = await TryInvokeAsync(endpoint, request, siteId, ct)
.ConfigureAwait(false);
@@ -119,6 +109,54 @@ public sealed class GrpcPullAuditEventsClient : IPullAuditEventsClient
(reply, _) = await TryInvokeAsync(fallback, request, siteId, ct).ConfigureAwait(false);
}
return ToResponse(reply);
}
/// <inheritdoc />
public async Task<PullAuditEventsResponse> PullFromEndpointAsync(
string siteId,
string endpoint,
DateTime sinceUtc,
string? afterId,
int batchSize,
CancellationToken ct)
{
// AUD-1: one node, no failover. The node-local audit store owes its own rows, so the
// actor pulls each node with that node's cursor; a fault on this node is simply an
// empty batch for it (the other node is pulled separately on the same tick).
if (string.IsNullOrWhiteSpace(endpoint))
{
return Empty;
}
var (reply, _) = await TryInvokeAsync(endpoint, BuildRequest(sinceUtc, afterId, batchSize), siteId, ct)
.ConfigureAwait(false);
return ToResponse(reply);
}
/// <inheritdoc />
/// <remarks>
/// The per-endpoint path (<see cref="PullFromEndpointAsync"/>) does not enumerate sites, so the
/// reconciliation actor calls this once per tick to keep the invoker's channel cache pruned
/// (review 2026-10-21 06/MEM-2).
/// </remarks>
public void RetainOnly(IReadOnlyList<SiteEntry> liveSites)
=> (_invoker as IGrpcChannelCachePruner)?.RetainOnly(liveSites);
private static ProtoPullRequest BuildRequest(DateTime sinceUtc, string? afterId, int batchSize) => new()
{
// ReadPendingSinceAsync treats DateTime.MinValue as "from the start";
// EnsureUtc keeps Timestamp.FromDateTime happy (it requires UTC kind).
SinceUtc = Timestamp.FromDateTime(EnsureUtc(sinceUtc)),
BatchSize = batchSize,
// Composite-keyset tiebreak (proto field 3), mirroring PullSiteCalls exactly.
// proto3 has no nullable string — an unset/empty AfterId is the site's signal to
// keep the legacy inclusive-timestamp contract (also what a first pull sends).
AfterId = afterId ?? string.Empty,
};
private static PullAuditEventsResponse ToResponse(ProtoPullResponse? reply)
{
if (reply is null)
{
return Empty;
@@ -54,7 +54,7 @@ namespace ZB.MOM.WW.ScadaBridge.AuditLog.Central;
/// inject a fake invoker so no real HTTP/2 endpoint is required.
/// </para>
/// </remarks>
public sealed class GrpcPullSiteCallsClient : IPullSiteCallsClient
public sealed class GrpcPullSiteCallsClient : IPullSiteCallsClient, IGrpcChannelCachePruner
{
private readonly ISiteEnumerator _sites;
private readonly IPullSiteCallsInvoker _invoker;
@@ -95,17 +95,7 @@ public sealed class GrpcPullSiteCallsClient : IPullSiteCallsClient
return Empty;
}
var request = new ProtoPullRequest
{
// ReadChangedSinceAsync treats DateTime.MinValue as "from the start";
// EnsureUtc keeps Timestamp.FromDateTime happy (it requires UTC kind).
SinceUtc = Timestamp.FromDateTime(EnsureUtc(sinceUtc)),
BatchSize = batchSize,
// Composite-keyset tiebreak. proto3 has no nullable string —
// an unset/empty AfterId is the site's signal to keep the legacy
// inclusive-timestamp contract (also what a first pull sends).
AfterId = afterId ?? string.Empty,
};
var request = BuildRequest(sinceUtc, afterId, batchSize);
var (reply, transportFault) = await TryInvokeAsync(endpoint, request, siteId, ct)
.ConfigureAwait(false);
@@ -126,6 +116,51 @@ public sealed class GrpcPullSiteCallsClient : IPullSiteCallsClient
(reply, _) = await TryInvokeAsync(fallback, request, siteId, ct).ConfigureAwait(false);
}
return ToResponse(reply, siteId);
}
/// <inheritdoc />
public async Task<PullSiteCallsResponse> PullFromEndpointAsync(
string siteId,
string endpoint,
DateTime sinceUtc,
string? afterId,
int batchSize,
CancellationToken ct)
{
// AUD-1: one node, no failover — each node is pulled with its own cursor.
if (string.IsNullOrWhiteSpace(endpoint))
{
return Empty;
}
var (reply, _) = await TryInvokeAsync(endpoint, BuildRequest(sinceUtc, afterId, batchSize), siteId, ct)
.ConfigureAwait(false);
return ToResponse(reply, siteId);
}
/// <inheritdoc />
/// <remarks>
/// The per-endpoint path does not enumerate sites, so the reconciliation pass calls this once
/// per tick to keep the invoker's channel cache pruned (review 2026-10-21 06/MEM-2).
/// </remarks>
public void RetainOnly(IReadOnlyList<SiteEntry> liveSites)
=> (_invoker as IGrpcChannelCachePruner)?.RetainOnly(liveSites);
private static ProtoPullRequest BuildRequest(DateTime sinceUtc, string? afterId, int batchSize) => new()
{
// ReadChangedSinceAsync treats DateTime.MinValue as "from the start";
// EnsureUtc keeps Timestamp.FromDateTime happy (it requires UTC kind).
SinceUtc = Timestamp.FromDateTime(EnsureUtc(sinceUtc)),
BatchSize = batchSize,
// Composite-keyset tiebreak. proto3 has no nullable string —
// an unset/empty AfterId is the site's signal to keep the legacy
// inclusive-timestamp contract (also what a first pull sends).
AfterId = afterId ?? string.Empty,
};
private PullSiteCallsResponse ToResponse(ProtoPullResponse? reply, string siteId)
{
if (reply is null)
{
return Empty;
@@ -59,4 +59,28 @@ public interface IPullAuditEventsClient
string? afterId,
int batchSize,
CancellationToken ct);
/// <summary>
/// Issues a <c>PullAuditEvents</c> RPC against ONE specific node of the site — no
/// NodeA→NodeB failover (AUD-1). The site audit store is a per-node, unreplicated SQLite
/// file, so each node owes its own rows; the reconciliation actor pulls every configured
/// node with its own cursor through this method. The default implementation (for test
/// doubles and any client without per-endpoint dialling) falls back to the site-level
/// <see cref="PullAsync"/>.
/// </summary>
/// <param name="siteId">The site being pulled (selects the preshared key).</param>
/// <param name="endpoint">The node's gRPC authority to dial.</param>
/// <param name="sinceUtc">The node's composite-cursor timestamp half.</param>
/// <param name="afterId">The node's composite-cursor id half (see <see cref="PullAsync"/>).</param>
/// <param name="batchSize">Maximum number of events to return per call.</param>
/// <param name="ct">Cancellation token.</param>
/// <returns>A task that resolves to the next batch from that node.</returns>
Task<PullAuditEventsResponse> PullFromEndpointAsync(
string siteId,
string endpoint,
DateTime sinceUtc,
string? afterId,
int batchSize,
CancellationToken ct)
=> PullAsync(siteId, sinceUtc, afterId, batchSize, ct);
}
@@ -64,4 +64,27 @@ public interface IPullSiteCallsClient
string? afterId,
int batchSize,
CancellationToken ct);
/// <summary>
/// Issues a <c>PullSiteCalls</c> RPC against ONE specific node of the site — no NodeA→NodeB
/// failover (AUD-1). On a site pair that does not run LocalDb replication each node's
/// operation-tracking store is its own, so the reconciliation pass pulls every configured
/// node with its own cursor. The default implementation (test doubles) falls back to the
/// site-level <see cref="PullAsync"/>.
/// </summary>
/// <param name="siteId">The site being pulled (selects the preshared key; re-stamped on rows).</param>
/// <param name="endpoint">The node's gRPC authority to dial.</param>
/// <param name="sinceUtc">The node's composite-cursor timestamp half.</param>
/// <param name="afterId">The node's composite-cursor id half.</param>
/// <param name="batchSize">Maximum number of rows to return per call.</param>
/// <param name="ct">Cancellation token.</param>
/// <returns>A task that resolves to the next batch from that node.</returns>
Task<PullSiteCallsResponse> PullFromEndpointAsync(
string siteId,
string endpoint,
DateTime sinceUtc,
string? afterId,
int batchSize,
CancellationToken ct)
=> PullAsync(siteId, sinceUtc, afterId, batchSize, ct);
}
@@ -106,7 +106,14 @@ public class SiteAuditReconciliationActor : ReceiveActor
/// write, so the cursor is an optimization for exactness, never a correctness crutch.
/// </para>
/// </remarks>
private readonly Dictionary<string, (DateTime Since, string? AfterId)> _cursors = new();
/// <remarks>
/// Keyed per <b>(site, node endpoint)</b> since AUD-1 (2026-12): the site audit store is a
/// per-node, unreplicated SQLite file, so each node owes its own rows and a cursor produced by
/// one node's rows proves nothing about the other's. One shared per-site cursor used to skip
/// the other node's owed rows and let <c>MarkReconciledUpToAsync</c> retire rows central never
/// received.
/// </remarks>
private readonly Dictionary<(string SiteId, string Endpoint), (DateTime Since, string? AfterId)> _cursors = new();
/// <summary>
/// Per-site count of consecutive non-draining cycles. Resets to zero on the
@@ -212,10 +219,18 @@ public class SiteAuditReconciliationActor : ReceiveActor
private void PruneUnknownSites(IReadOnlyList<SiteEntry> sites, Akka.Event.EventStream eventStream)
{
var live = new HashSet<string>(sites.Select(s => s.SiteId), StringComparer.Ordinal);
foreach (var siteId in _cursors.Keys.Concat(_nonDrainingCycles.Keys).Concat(_stalled.Keys)
var liveNodes = new HashSet<(string, string)>(sites.SelectMany(s => NodeEndpoints(s).Select(e => (s.SiteId, e))));
// A node whose address was edited away (or a deleted site) drops its cursor; a new
// address starts from the beginning of what that node owes, which is conservative.
foreach (var key in _cursors.Keys.Where(k => !liveNodes.Contains(k)).ToList())
{
_cursors.Remove(key);
}
foreach (var siteId in _nonDrainingCycles.Keys.Concat(_stalled.Keys)
.Where(id => !live.Contains(id)).Distinct().ToList())
{
_cursors.Remove(siteId);
_nonDrainingCycles.Remove(siteId);
if (_stalled.Remove(siteId, out var wasStalled) && wasStalled)
{
@@ -224,8 +239,29 @@ public class SiteAuditReconciliationActor : ReceiveActor
}
}
/// <summary>Test seam: number of sites with a held reconciliation cursor.</summary>
internal int TrackedSiteCountForTests => _cursors.Count;
/// <summary>Test seam: number of sites with at least one held reconciliation cursor.</summary>
internal int TrackedSiteCountForTests => _cursors.Keys.Select(k => k.SiteId).Distinct().Count();
/// <summary>Test seam: number of (site, node) cursors held.</summary>
internal int TrackedNodeCursorCountForTests => _cursors.Count;
/// <summary>
/// The distinct node endpoints of a site: the primary (NodeA where configured) and, when a
/// distinct one exists, the second node (AUD-1 — both are pulled every tick).
/// </summary>
private static IEnumerable<string> NodeEndpoints(SiteEntry site)
{
if (!string.IsNullOrWhiteSpace(site.GrpcEndpoint))
{
yield return site.GrpcEndpoint;
}
if (!string.IsNullOrWhiteSpace(site.FallbackGrpcEndpoint)
&& !string.Equals(site.FallbackGrpcEndpoint, site.GrpcEndpoint, StringComparison.Ordinal))
{
yield return site.FallbackGrpcEndpoint;
}
}
/// <summary>
/// Initializes the reconciliation actor with its dependencies and registers the tick handler.
@@ -310,6 +346,7 @@ public class SiteAuditReconciliationActor : ReceiveActor
// After the empty guard: an empty enumeration is as likely a transient lookup glitch
// as a fleet with no sites, and pruning on it would throw away every cursor.
PruneUnknownSites(sites, eventStream);
(_client as IGrpcChannelCachePruner)?.RetainOnly(sites);
// Use CreateAsyncScope + await using so scoped EF Core
// services (IAsyncDisposable DbContexts) dispose asynchronously
@@ -364,18 +401,40 @@ public class SiteAuditReconciliationActor : ReceiveActor
private async Task PullSiteAsync(SiteEntry site, IAuditLogRepository repository, Akka.Event.EventStream eventStream)
{
var maxPages = Math.Max(1, _options.MaxPagesPerTick);
var nonDraining = false;
for (var page = 0; page < maxPages; page++)
var siteNonDraining = false;
// AUD-1: pull EVERY node of the site, each with its own cursor. The pull used to go to
// NodeA whenever NodeA answered — after any NodeA restart (NodeB active, NodeA a healthy
// standby with an empty store) every pull returned "drained" and NodeB's PushAbandoned /
// Rejected rows never reached central. One node failing must not skip the other.
foreach (var endpoint in NodeEndpoints(site))
{
var (response, cursorAdvanced) = await PullPageAsync(site, repository).ConfigureAwait(false);
nonDraining = response.MoreAvailable && response.Events.Count > 0;
if (!nonDraining || !cursorAdvanced)
var nonDraining = false;
try
{
break;
for (var page = 0; page < maxPages; page++)
{
var (response, cursorAdvanced) = await PullPageAsync(site, endpoint, repository).ConfigureAwait(false);
nonDraining = response.MoreAvailable && response.Events.Count > 0;
if (!nonDraining || !cursorAdvanced)
{
break;
}
}
}
catch (Exception ex)
{
// Per-node isolation: this node's cursor stays where it was; the other node
// is still pulled on this tick.
_logger.LogWarning(ex,
"Reconciliation pull failed for site {SiteId} node {Endpoint}; the site's other node continues.",
site.SiteId, endpoint);
}
siteNonDraining |= nonDraining;
}
UpdateStalledState(site.SiteId, draining: !nonDraining, eventStream);
UpdateStalledState(site.SiteId, draining: !siteNonDraining, eventStream);
}
/// <summary>
@@ -403,16 +462,17 @@ public class SiteAuditReconciliationActor : ReceiveActor
/// </remarks>
/// <returns>The site's response and whether the cursor moved.</returns>
private async Task<(PullAuditEventsResponse Response, bool CursorAdvanced)> PullPageAsync(
SiteEntry site, IAuditLogRepository repository)
SiteEntry site, string endpoint, IAuditLogRepository repository)
{
var cursor = _cursors.TryGetValue(site.SiteId, out var c)
var cursorKey = (site.SiteId, endpoint);
var cursor = _cursors.TryGetValue(cursorKey, out var c)
? c
: (Since: DateTime.MinValue, AfterId: (string?)null);
var since = cursor.Since;
var afterId = cursor.AfterId;
var response = await _client.PullAsync(
site.SiteId, since, afterId, _options.BatchSize, CancellationToken.None)
var response = await _client.PullFromEndpointAsync(
site.SiteId, endpoint, since, afterId, _options.BatchSize, CancellationToken.None)
.ConfigureAwait(false);
var maxOccurred = since;
@@ -598,7 +658,7 @@ public class SiteAuditReconciliationActor : ReceiveActor
var next = hasUnresolvedFailure
? (since, afterId)
: (maxOccurred, maxAfterId);
_cursors[site.SiteId] = next;
_cursors[cursorKey] = next;
var advanced = next.Item1 != since || !string.Equals(next.Item2, afterId, StringComparison.Ordinal);
return (response, advanced);
@@ -132,7 +132,12 @@ public class SiteCallAuditActor : ReceiveActor
/// next tick re-pulls from the start and idempotent upsert dedupes). Mirrors
/// <c>SiteAuditReconciliationActor</c>'s cursor (now composite).
/// </summary>
private readonly Dictionary<string, (DateTime Since, string? AfterId)> _reconciliationCursors = new();
/// <remarks>
/// Keyed per <b>(site, node endpoint)</b> since AUD-1 (2026-12): on a site pair that does not
/// run LocalDb replication each node's operation-tracking store is its own, so each node is
/// pulled with its own cursor; one per-site cursor fed by NodeA's rows skipped NodeB's.
/// </remarks>
private readonly Dictionary<(string SiteId, string Endpoint), (DateTime Since, string? AfterId)> _reconciliationCursors = new();
/// <summary>
/// Per-site "pinned" latch — <c>true</c> once a site's composite
@@ -500,6 +505,7 @@ public class SiteCallAuditActor : ReceiveActor
}
PruneRemovedSites(sites);
(client as IGrpcChannelCachePruner)?.RetainOnly(sites);
if (sites.Count == 0)
{
@@ -536,12 +542,35 @@ public class SiteCallAuditActor : ReceiveActor
_reconciliationPinned.Remove(siteId);
}
foreach (var siteId in _reconciliationCursors.Keys.Where(k => !live.Contains(k)).ToList())
var liveNodes = new HashSet<(string, string)>(
sites.SelectMany(s => NodeEndpoints(s).Select(e => (s.SiteId, e))));
foreach (var key in _reconciliationCursors.Keys.Where(k => !liveNodes.Contains(k)).ToList())
{
_reconciliationCursors.Remove(siteId);
_reconciliationCursors.Remove(key);
}
}
/// <summary>
/// The distinct node endpoints of a site: the primary (NodeA where configured) and, when a
/// distinct one exists, the second node (AUD-1 — both are pulled every tick).
/// </summary>
private static IEnumerable<string> NodeEndpoints(SiteEntry site)
{
if (!string.IsNullOrWhiteSpace(site.GrpcEndpoint))
{
yield return site.GrpcEndpoint;
}
if (!string.IsNullOrWhiteSpace(site.FallbackGrpcEndpoint)
&& !string.Equals(site.FallbackGrpcEndpoint, site.GrpcEndpoint, StringComparison.Ordinal))
{
yield return site.FallbackGrpcEndpoint;
}
}
/// <summary>Test seam: number of (site, node) reconciliation cursors held.</summary>
internal int ReconciliationCursorCountForTests => _reconciliationCursors.Count;
/// <summary>
/// Reconciles every site in the tick against a single resolved repository,
/// isolating per-site faults so one bad site never sinks the rest of the
@@ -640,7 +669,37 @@ public class SiteCallAuditActor : ReceiveActor
private async Task ReconcileSiteAsync(
SiteEntry site, IPullSiteCallsClient client, ISiteCallAuditRepository repository)
{
var cursor = _reconciliationCursors.TryGetValue(site.SiteId, out var c)
// AUD-1: pull EVERY node with its own cursor. One node faulting must not skip the
// other; the site is pinned when any node is.
var anyPinned = false;
foreach (var endpoint in NodeEndpoints(site))
{
try
{
anyPinned |= await ReconcileNodeAsync(site, endpoint, client, repository).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.LogWarning(ex,
"SiteCallAudit reconciliation pull failed for site {SiteId} node {Endpoint}; the site's other node continues.",
site.SiteId, endpoint);
anyPinned |= _reconciliationPinned.TryGetValue(site.SiteId, out var wasPinned) && wasPinned;
}
}
SetReconciliationPinned(site.SiteId, anyPinned);
}
/// <summary>
/// Drains one node of a site (see <see cref="ReconcileSiteAsync"/> for the cursor, page and
/// pinned semantics). Returns <c>true</c> when the node's cursor is pinned (a legacy node that
/// ignores the <c>after_id</c> keyset).
/// </summary>
private async Task<bool> ReconcileNodeAsync(
SiteEntry site, string endpoint, IPullSiteCallsClient client, ISiteCallAuditRepository repository)
{
var cursorKey = (site.SiteId, endpoint);
var cursor = _reconciliationCursors.TryGetValue(cursorKey, out var c)
? c
: (Since: DateTime.MinValue, AfterId: (string?)null);
@@ -655,7 +714,7 @@ public class SiteCallAuditActor : ReceiveActor
var since = cursor.Since;
var afterId = cursor.AfterId;
var response = await client
.PullAsync(site.SiteId, since, afterId, _options.ReconciliationBatchSize, CancellationToken.None)
.PullFromEndpointAsync(site.SiteId, endpoint, since, afterId, _options.ReconciliationBatchSize, CancellationToken.None)
.ConfigureAwait(false);
var maxUpdated = since;
@@ -694,19 +753,12 @@ public class SiteCallAuditActor : ReceiveActor
// Persist the advanced cursor after every page so a fault on a later
// page (caught per-site upstream) still keeps the rows already drained.
cursor = (maxUpdated, maxAfterId);
_reconciliationCursors[site.SiteId] = cursor;
// Progress resumed → clear any prior pinned latch (publishes the
// Pinned=false transition exactly once).
if (advanced)
{
SetReconciliationPinned(site.SiteId, pinned: false);
}
_reconciliationCursors[cursorKey] = cursor;
if (!response.MoreAvailable)
{
// Backlog fully drained for this site this tick.
return;
// Backlog fully drained for this node this tick.
return false;
}
if (!advanced)
@@ -716,16 +768,16 @@ public class SiteCallAuditActor : ReceiveActor
// site), so a continuation would re-pull the identical window
// forever. Latch + publish the pinned state and stop; the next tick
// re-checks and unpins if the site catches up.
SetReconciliationPinned(site.SiteId, pinned: true);
_logger.LogWarning(
"SiteCallAudit reconciliation for site {SiteId} is pinned: the composite "
"SiteCallAudit reconciliation for site {SiteId} node {Endpoint} is pinned: the composite "
+ "(UpdatedAtUtc, TrackedOperationId) cursor did not advance past ({CursorUtc:o}, {AfterId}) "
+ "yet the site reports more rows available — the site does not honour the after_id keyset "
+ "(legacy). The backlog tail will not reconcile until the site is upgraded.",
site.SiteId,
endpoint,
since,
afterId ?? "(none)");
return;
return true;
}
}
@@ -734,11 +786,13 @@ public class SiteCallAuditActor : ReceiveActor
// simply more than MaxReconciliationPagesPerTick × batch-size of it. The
// next tick resumes from the advanced cursor.
_logger.LogInformation(
"SiteCallAudit reconciliation for site {SiteId} hit the per-tick page ceiling "
"SiteCallAudit reconciliation for site {SiteId} node {Endpoint} hit the per-tick page ceiling "
+ "({MaxPages} pages); the cursor advanced each page and the remaining backlog "
+ "drains on the next tick.",
site.SiteId,
endpoint,
MaxReconciliationPagesPerTick);
return false;
}
/// <summary>