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
+15
View File
@@ -396,6 +396,21 @@ issues `PullAuditEvents(sinceUtc, batchSize[, afterId])` against each site and
inserts-if-not-exists. Same self-healing pattern as Site Call Audit's inserts-if-not-exists. Same self-healing pattern as Site Call Audit's
reconciliation of `SiteCalls`. reconciliation of `SiteCalls`.
**Both nodes, one cursor each (AUD-1, 2026-12).** The site audit store is a
per-node, unreplicated SQLite file, so each node owes its own rows. Every tick
pulls **every configured node** of the site (`GrpcNodeAAddress` and a distinct
`GrpcNodeBAddress`) through `IPullAuditEventsClient.PullFromEndpointAsync` —
one node, no NodeA→NodeB failover — and keeps a composite cursor per
**(site, node endpoint)**. Before, the pull went to NodeA whenever NodeA
answered: after any NodeA restart (NodeB active, NodeA a healthy standby with an
empty store) every pull reported "drained" and NodeB's `PushAbandoned`/`Rejected`
rows never reached central; and the single per-site cursor, fed by NodeA's rows,
could be sent to NodeB, skipping NodeB's owed rows and letting
`MarkReconciledUpToAsync` retire rows central never received. One node failing
does not skip the other; the stalled latch stays per site (non-draining when any
node is). An edited address drops that node's cursor and starts the new one from
the beginning of what it owes.
**The pull serves only rows central has not acknowledged (review 2026-10-21 **The pull serves only rows central has not acknowledged (review 2026-10-21
06/PERF-1).** `ReadPendingSinceAsync` returns `Pending`, `PushAbandoned` and 06/PERF-1).** `ReadPendingSinceAsync` returns `Pending`, `PushAbandoned` and
`Rejected` rows — never `Forwarded`. It used to serve `Forwarded` rows too, so `Rejected` rows — never `Forwarded`. It used to serve `Forwarded` rows too, so
@@ -120,6 +120,13 @@ reconnect — pulls "all tracking rows changed since cursor X" from each site.
Gaps left by lost telemetry self-heal. Central converges to the site; the site Gaps left by lost telemetry self-heal. Central converges to the site; the site
never depends on central. never depends on central.
**Every node is pulled, each with its own cursor (AUD-1, 2026-12).** On a site
pair without LocalDb replication each node's operation-tracking store is its
own, so the pass pulls every configured node (`PullFromEndpointAsync`, no
NodeA→NodeB failover) and keys the cursor below per **(site, node endpoint)**;
the pinned latch stays per site (pinned when any node is). Before, NodeA was
pulled whenever it answered, so a standby NodeA's empty store hid NodeB's rows.
The per-site cursor is a **composite `(UpdatedAtUtc, TrackedOperationId)` The per-site cursor is a **composite `(UpdatedAtUtc, TrackedOperationId)`
keyset**, not a single timestamp. Each pull asks for rows strictly greater than keyset**, not a single timestamp. Each pull asks for rows strictly greater than
the cursor pair and advances it to the maximum row seen; a burst of more rows the cursor pair and advances it to the maximum row seen; a burst of more rows
@@ -47,7 +47,7 @@ namespace ZB.MOM.WW.ScadaBridge.AuditLog.Central;
/// inject a fake invoker so no real HTTP/2 endpoint is required. /// inject a fake invoker so no real HTTP/2 endpoint is required.
/// </para> /// </para>
/// </remarks> /// </remarks>
public sealed class GrpcPullAuditEventsClient : IPullAuditEventsClient public sealed class GrpcPullAuditEventsClient : IPullAuditEventsClient, IGrpcChannelCachePruner
{ {
private readonly ISiteEnumerator _sites; private readonly ISiteEnumerator _sites;
private readonly IPullAuditEventsInvoker _invoker; private readonly IPullAuditEventsInvoker _invoker;
@@ -88,17 +88,7 @@ public sealed class GrpcPullAuditEventsClient : IPullAuditEventsClient
return Empty; return Empty;
} }
var request = new ProtoPullRequest var request = BuildRequest(sinceUtc, afterId, batchSize);
{
// 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 (reply, transportFault) = await TryInvokeAsync(endpoint, request, siteId, ct) var (reply, transportFault) = await TryInvokeAsync(endpoint, request, siteId, ct)
.ConfigureAwait(false); .ConfigureAwait(false);
@@ -119,6 +109,54 @@ public sealed class GrpcPullAuditEventsClient : IPullAuditEventsClient
(reply, _) = await TryInvokeAsync(fallback, request, siteId, ct).ConfigureAwait(false); (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) if (reply is null)
{ {
return Empty; 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. /// inject a fake invoker so no real HTTP/2 endpoint is required.
/// </para> /// </para>
/// </remarks> /// </remarks>
public sealed class GrpcPullSiteCallsClient : IPullSiteCallsClient public sealed class GrpcPullSiteCallsClient : IPullSiteCallsClient, IGrpcChannelCachePruner
{ {
private readonly ISiteEnumerator _sites; private readonly ISiteEnumerator _sites;
private readonly IPullSiteCallsInvoker _invoker; private readonly IPullSiteCallsInvoker _invoker;
@@ -95,17 +95,7 @@ public sealed class GrpcPullSiteCallsClient : IPullSiteCallsClient
return Empty; return Empty;
} }
var request = new ProtoPullRequest var request = BuildRequest(sinceUtc, afterId, batchSize);
{
// 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 (reply, transportFault) = await TryInvokeAsync(endpoint, request, siteId, ct) var (reply, transportFault) = await TryInvokeAsync(endpoint, request, siteId, ct)
.ConfigureAwait(false); .ConfigureAwait(false);
@@ -126,6 +116,51 @@ public sealed class GrpcPullSiteCallsClient : IPullSiteCallsClient
(reply, _) = await TryInvokeAsync(fallback, request, siteId, ct).ConfigureAwait(false); (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) if (reply is null)
{ {
return Empty; return Empty;
@@ -59,4 +59,28 @@ public interface IPullAuditEventsClient
string? afterId, string? afterId,
int batchSize, int batchSize,
CancellationToken ct); 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, string? afterId,
int batchSize, int batchSize,
CancellationToken ct); 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. /// write, so the cursor is an optimization for exactness, never a correctness crutch.
/// </para> /// </para>
/// </remarks> /// </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> /// <summary>
/// Per-site count of consecutive non-draining cycles. Resets to zero on the /// 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) private void PruneUnknownSites(IReadOnlyList<SiteEntry> sites, Akka.Event.EventStream eventStream)
{ {
var live = new HashSet<string>(sites.Select(s => s.SiteId), StringComparer.Ordinal); 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()) .Where(id => !live.Contains(id)).Distinct().ToList())
{ {
_cursors.Remove(siteId);
_nonDrainingCycles.Remove(siteId); _nonDrainingCycles.Remove(siteId);
if (_stalled.Remove(siteId, out var wasStalled) && wasStalled) 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> /// <summary>Test seam: number of sites with at least one held reconciliation cursor.</summary>
internal int TrackedSiteCountForTests => _cursors.Count; 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> /// <summary>
/// Initializes the reconciliation actor with its dependencies and registers the tick handler. /// 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 // 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. // as a fleet with no sites, and pruning on it would throw away every cursor.
PruneUnknownSites(sites, eventStream); PruneUnknownSites(sites, eventStream);
(_client as IGrpcChannelCachePruner)?.RetainOnly(sites);
// Use CreateAsyncScope + await using so scoped EF Core // Use CreateAsyncScope + await using so scoped EF Core
// services (IAsyncDisposable DbContexts) dispose asynchronously // 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) private async Task PullSiteAsync(SiteEntry site, IAuditLogRepository repository, Akka.Event.EventStream eventStream)
{ {
var maxPages = Math.Max(1, _options.MaxPagesPerTick); var maxPages = Math.Max(1, _options.MaxPagesPerTick);
var nonDraining = false; var siteNonDraining = false;
for (var page = 0; page < maxPages; page++)
// 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); var nonDraining = false;
nonDraining = response.MoreAvailable && response.Events.Count > 0; try
if (!nonDraining || !cursorAdvanced)
{ {
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> /// <summary>
@@ -403,16 +462,17 @@ public class SiteAuditReconciliationActor : ReceiveActor
/// </remarks> /// </remarks>
/// <returns>The site's response and whether the cursor moved.</returns> /// <returns>The site's response and whether the cursor moved.</returns>
private async Task<(PullAuditEventsResponse Response, bool CursorAdvanced)> PullPageAsync( 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 ? c
: (Since: DateTime.MinValue, AfterId: (string?)null); : (Since: DateTime.MinValue, AfterId: (string?)null);
var since = cursor.Since; var since = cursor.Since;
var afterId = cursor.AfterId; var afterId = cursor.AfterId;
var response = await _client.PullAsync( var response = await _client.PullFromEndpointAsync(
site.SiteId, since, afterId, _options.BatchSize, CancellationToken.None) site.SiteId, endpoint, since, afterId, _options.BatchSize, CancellationToken.None)
.ConfigureAwait(false); .ConfigureAwait(false);
var maxOccurred = since; var maxOccurred = since;
@@ -598,7 +658,7 @@ public class SiteAuditReconciliationActor : ReceiveActor
var next = hasUnresolvedFailure var next = hasUnresolvedFailure
? (since, afterId) ? (since, afterId)
: (maxOccurred, maxAfterId); : (maxOccurred, maxAfterId);
_cursors[site.SiteId] = next; _cursors[cursorKey] = next;
var advanced = next.Item1 != since || !string.Equals(next.Item2, afterId, StringComparison.Ordinal); var advanced = next.Item1 != since || !string.Equals(next.Item2, afterId, StringComparison.Ordinal);
return (response, advanced); return (response, advanced);
@@ -132,7 +132,12 @@ public class SiteCallAuditActor : ReceiveActor
/// next tick re-pulls from the start and idempotent upsert dedupes). Mirrors /// next tick re-pulls from the start and idempotent upsert dedupes). Mirrors
/// <c>SiteAuditReconciliationActor</c>'s cursor (now composite). /// <c>SiteAuditReconciliationActor</c>'s cursor (now composite).
/// </summary> /// </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> /// <summary>
/// Per-site "pinned" latch — <c>true</c> once a site's composite /// Per-site "pinned" latch — <c>true</c> once a site's composite
@@ -500,6 +505,7 @@ public class SiteCallAuditActor : ReceiveActor
} }
PruneRemovedSites(sites); PruneRemovedSites(sites);
(client as IGrpcChannelCachePruner)?.RetainOnly(sites);
if (sites.Count == 0) if (sites.Count == 0)
{ {
@@ -536,12 +542,35 @@ public class SiteCallAuditActor : ReceiveActor
_reconciliationPinned.Remove(siteId); _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> /// <summary>
/// Reconciles every site in the tick against a single resolved repository, /// 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 /// 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( private async Task ReconcileSiteAsync(
SiteEntry site, IPullSiteCallsClient client, ISiteCallAuditRepository repository) 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 ? c
: (Since: DateTime.MinValue, AfterId: (string?)null); : (Since: DateTime.MinValue, AfterId: (string?)null);
@@ -655,7 +714,7 @@ public class SiteCallAuditActor : ReceiveActor
var since = cursor.Since; var since = cursor.Since;
var afterId = cursor.AfterId; var afterId = cursor.AfterId;
var response = await client 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); .ConfigureAwait(false);
var maxUpdated = since; var maxUpdated = since;
@@ -694,19 +753,12 @@ public class SiteCallAuditActor : ReceiveActor
// Persist the advanced cursor after every page so a fault on a later // Persist the advanced cursor after every page so a fault on a later
// page (caught per-site upstream) still keeps the rows already drained. // page (caught per-site upstream) still keeps the rows already drained.
cursor = (maxUpdated, maxAfterId); cursor = (maxUpdated, maxAfterId);
_reconciliationCursors[site.SiteId] = cursor; _reconciliationCursors[cursorKey] = cursor;
// Progress resumed → clear any prior pinned latch (publishes the
// Pinned=false transition exactly once).
if (advanced)
{
SetReconciliationPinned(site.SiteId, pinned: false);
}
if (!response.MoreAvailable) if (!response.MoreAvailable)
{ {
// Backlog fully drained for this site this tick. // Backlog fully drained for this node this tick.
return; return false;
} }
if (!advanced) if (!advanced)
@@ -716,16 +768,16 @@ public class SiteCallAuditActor : ReceiveActor
// site), so a continuation would re-pull the identical window // site), so a continuation would re-pull the identical window
// forever. Latch + publish the pinned state and stop; the next tick // forever. Latch + publish the pinned state and stop; the next tick
// re-checks and unpins if the site catches up. // re-checks and unpins if the site catches up.
SetReconciliationPinned(site.SiteId, pinned: true);
_logger.LogWarning( _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}) " + "(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 " + "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.", + "(legacy). The backlog tail will not reconcile until the site is upgraded.",
site.SiteId, site.SiteId,
endpoint,
since, since,
afterId ?? "(none)"); afterId ?? "(none)");
return; return true;
} }
} }
@@ -734,11 +786,13 @@ public class SiteCallAuditActor : ReceiveActor
// simply more than MaxReconciliationPagesPerTick × batch-size of it. The // simply more than MaxReconciliationPagesPerTick × batch-size of it. The
// next tick resumes from the advanced cursor. // next tick resumes from the advanced cursor.
_logger.LogInformation( _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 " + "({MaxPages} pages); the cursor advanced each page and the remaining backlog "
+ "drains on the next tick.", + "drains on the next tick.",
site.SiteId, site.SiteId,
endpoint,
MaxReconciliationPagesPerTick); MaxReconciliationPagesPerTick);
return false;
} }
/// <summary> /// <summary>
@@ -0,0 +1,145 @@
using System.Collections.Concurrent;
using Akka.Actor;
using Akka.TestKit.Xunit2;
using Grpc.Core;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using NSubstitute;
using ZB.MOM.WW.Audit;
using ZB.MOM.WW.ScadaBridge.AuditLog.Central;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Integration;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Audit;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
using ProtoPullRequest = ZB.MOM.WW.ScadaBridge.Communication.Grpc.PullAuditEventsRequest;
using ProtoPullResponse = ZB.MOM.WW.ScadaBridge.Communication.Grpc.PullAuditEventsResponse;
namespace ZB.MOM.WW.ScadaBridge.AuditLog.Tests.Central;
/// <summary>
/// AUD-1: the site audit store is per node and unreplicated, so the reconciliation pull reaches
/// BOTH nodes of a site every tick, each with its own (site, node) cursor — not NodeA whenever
/// NodeA answers, with one cursor shared by two unrelated stores.
/// </summary>
public class ReconciliationPerNodeTests : TestKit
{
private const string NodeA = "http://site-a-node-a:8083";
private const string NodeB = "http://site-a-node-b:8083";
private static readonly DateTime OwedAt = new(2026, 12, 1, 8, 0, 0, DateTimeKind.Utc);
private sealed class StaticEnumerator(params SiteEntry[] sites) : ISiteEnumerator
{
public Task<IReadOnlyList<SiteEntry>> EnumerateAsync(CancellationToken ct = default) =>
Task.FromResult<IReadOnlyList<SiteEntry>>(sites);
}
/// <summary>
/// NodeA (a healthy standby after a restart) owes nothing; NodeB (active) owes one
/// PushAbandoned row. Records every per-node pull with the cursor it was sent.
/// </summary>
private sealed class PerNodeClient : IPullAuditEventsClient
{
public readonly AuditEvent NodeBRow = ScadaBridgeAuditEventFactory.Create(
eventId: Guid.NewGuid(),
occurredAtUtc: OwedAt,
channel: AuditChannel.ApiOutbound,
kind: AuditKind.ApiCall,
status: AuditStatus.Delivered,
sourceSiteId: "site-a");
public ConcurrentQueue<(string Endpoint, DateTime Since, string? AfterId)> Calls { get; } = new();
public Task<PullAuditEventsResponse> PullAsync(
string siteId, DateTime sinceUtc, string? afterId, int batchSize, CancellationToken ct) =>
throw new InvalidOperationException("the actor must pull per node");
public Task<PullAuditEventsResponse> PullFromEndpointAsync(
string siteId, string endpoint, DateTime sinceUtc, string? afterId, int batchSize, CancellationToken ct)
{
Calls.Enqueue((endpoint, sinceUtc, afterId));
var events = endpoint == NodeB && sinceUtc < OwedAt
? new[] { NodeBRow }
: Array.Empty<AuditEvent>();
return Task.FromResult(new PullAuditEventsResponse(events, MoreAvailable: false));
}
}
/// <summary>
/// Regression: the NodeB-owed row reaches central even though NodeA answers, and each node
/// keeps its own cursor (NodeA's never moves off its start; NodeB's advances past its row).
/// </summary>
[Fact]
public void BothNodesArePulled_EachWithItsOwnCursor()
{
var client = new PerNodeClient();
var repo = Substitute.For<IAuditLogRepository>();
var inserted = new ConcurrentBag<Guid>();
repo.InsertManyIfNotExistsAsync(Arg.Any<IReadOnlyList<AuditEvent>>(), Arg.Any<TimeSpan?>(), Arg.Any<CancellationToken>())
.Returns(ci =>
{
foreach (var e in (IReadOnlyList<AuditEvent>)ci[0]) inserted.Add(e.EventId);
return Task.FromResult(((IReadOnlyList<AuditEvent>)ci[0]).Count);
});
var services = new ServiceCollection();
services.AddScoped(_ => repo);
var actor = Sys.ActorOf(Props.Create(() => new SiteAuditReconciliationActor(
new StaticEnumerator(new SiteEntry("site-a", NodeA, NodeB)),
client,
services.BuildServiceProvider(),
Options.Create(new SiteAuditReconciliationOptions
{
ReconciliationIntervalOverride = TimeSpan.FromMilliseconds(100),
}),
NullLogger<SiteAuditReconciliationActor>.Instance)));
// Two ticks' worth of pulls on each node.
AwaitCondition(() => client.Calls.Count(c => c.Endpoint == NodeB) >= 2
&& client.Calls.Count(c => c.Endpoint == NodeA) >= 2,
TimeSpan.FromSeconds(10));
Assert.Contains(client.NodeBRow.EventId, inserted);
var nodeACalls = client.Calls.Where(c => c.Endpoint == NodeA).ToList();
Assert.All(nodeACalls, c => Assert.Equal(DateTime.MinValue, c.Since));
var nodeBCalls = client.Calls.Where(c => c.Endpoint == NodeB).ToList();
Assert.Equal(DateTime.MinValue, nodeBCalls[0].Since);
Assert.Equal(OwedAt, nodeBCalls[1].Since);
Assert.Equal(client.NodeBRow.EventId.ToString(), nodeBCalls[1].AfterId);
Watch(actor);
Sys.Stop(actor);
ExpectTerminated(actor);
}
private sealed class RecordingInvoker : GrpcPullAuditEventsClient.IPullAuditEventsInvoker
{
public ConcurrentQueue<string> Endpoints { get; } = new();
public Task<ProtoPullResponse> InvokeAsync(string siteId, string endpoint, ProtoPullRequest request, CancellationToken ct)
{
Endpoints.Enqueue(endpoint);
throw new RpcException(new Grpc.Core.Status(StatusCode.Unavailable, "node down"));
}
}
/// <summary>The per-node pull dials only the node it is given — no NodeA→NodeB failover.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task PullFromEndpoint_DialsOnlyThatNode_AndCollapsesAFaultToEmpty()
{
var invoker = new RecordingInvoker();
var client = new GrpcPullAuditEventsClient(
new StaticEnumerator(new SiteEntry("site-a", NodeA, NodeB)),
invoker,
NullLogger<GrpcPullAuditEventsClient>.Instance);
var response = await client.PullFromEndpointAsync("site-a", NodeA, DateTime.MinValue, null, 10, CancellationToken.None);
Assert.Empty(response.Events);
Assert.Equal(new[] { NodeA }, invoker.Endpoints.ToArray());
}
}
@@ -1192,4 +1192,57 @@ public class SiteCallAuditReconciliationTests : TestKit
return new PullSiteCallsResponse(Array.Empty<SiteCall>(), MoreAvailable: false); return new PullSiteCallsResponse(Array.Empty<SiteCall>(), MoreAvailable: false);
} }
} }
/// <summary>Records each per-node pull; only NodeB owes a row (an unreplicated pair after a NodeA restart).</summary>
private sealed class PerNodePullClient(SiteCall nodeBRow) : IPullSiteCallsClient
{
public System.Collections.Concurrent.ConcurrentQueue<(string Endpoint, DateTime Since)> Calls { get; } = new();
/// <inheritdoc />
public Task<PullSiteCallsResponse> PullAsync(
string siteId, DateTime sinceUtc, string? afterId, int batchSize, CancellationToken ct) =>
throw new InvalidOperationException("the actor must pull per node");
/// <inheritdoc />
public Task<PullSiteCallsResponse> PullFromEndpointAsync(
string siteId, string endpoint, DateTime sinceUtc, string? afterId, int batchSize, CancellationToken ct)
{
Calls.Enqueue((endpoint, sinceUtc));
var rows = endpoint == "http://nodeB:8083" && sinceUtc < nodeBRow.UpdatedAtUtc
? new[] { nodeBRow }
: Array.Empty<SiteCall>();
return Task.FromResult(new PullSiteCallsResponse(rows, MoreAvailable: false));
}
}
/// <summary>
/// AUD-1 regression: both nodes of the site are pulled every tick, each with its own cursor,
/// so a row owed only by NodeB reaches central although NodeA answers.
/// </summary>
[Fact]
public void Reconciliation_PullsBothNodes_EachWithItsOwnCursor()
{
var row = NewRow(TrackedOperationId.New(), "siteA", status: "Parked",
updatedAtUtc: new DateTime(2026, 12, 1, 8, 0, 0, DateTimeKind.Utc));
var client = new PerNodePullClient(row);
var repo = new RecordingRepo();
var actor = CreateActor(
new StaticEnumerator(new SiteEntry("siteA", "http://nodeA:8083", "http://nodeB:8083")),
client, repo, FastTickOptions());
AwaitCondition(() => client.Calls.Count(c => c.Endpoint == "http://nodeB:8083") >= 2
&& client.Calls.Count(c => c.Endpoint == "http://nodeA:8083") >= 2,
TimeSpan.FromSeconds(10));
Assert.True(repo.Upserted.ContainsKey(row.TrackedOperationId));
Assert.All(client.Calls.Where(c => c.Endpoint == "http://nodeA:8083"),
c => Assert.Equal(DateTime.MinValue, c.Since));
var nodeB = client.Calls.Where(c => c.Endpoint == "http://nodeB:8083").ToList();
Assert.Equal(DateTime.MinValue, nodeB[0].Since);
Assert.Equal(row.UpdatedAtUtc, nodeB[1].Since);
Watch(actor);
Sys.Stop(actor);
ExpectTerminated(actor);
}
} }