From 4070f7efca5d066153c2eb19fe17b6ad96af7635 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 10:08:20 -0500 Subject: [PATCH] fix(audit): reconciliation pulls every site node with a per-(site, node) cursor (AUD-1, WP4 task 4.8) --- docs/requirements/Component-AuditLog.md | 15 ++ docs/requirements/Component-SiteCallAudit.md | 7 + .../Central/GrpcPullAuditEventsClient.cs | 62 ++++++-- .../Central/GrpcPullSiteCallsClient.cs | 59 +++++-- .../Central/IPullAuditEventsClient.cs | 24 +++ .../Central/IPullSiteCallsClient.cs | 23 +++ .../Central/SiteAuditReconciliationActor.cs | 94 ++++++++++-- .../SiteCallAuditActor.cs | 92 ++++++++--- .../Central/ReconciliationPerNodeTests.cs | 145 ++++++++++++++++++ .../SiteCallAuditReconciliationTests.cs | 53 +++++++ 10 files changed, 514 insertions(+), 60 deletions(-) create mode 100644 tests/ZB.MOM.WW.ScadaBridge.AuditLog.Tests/Central/ReconciliationPerNodeTests.cs diff --git a/docs/requirements/Component-AuditLog.md b/docs/requirements/Component-AuditLog.md index f0af2960..492025e3 100644 --- a/docs/requirements/Component-AuditLog.md +++ b/docs/requirements/Component-AuditLog.md @@ -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 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 06/PERF-1).** `ReadPendingSinceAsync` returns `Pending`, `PushAbandoned` and `Rejected` rows — never `Forwarded`. It used to serve `Forwarded` rows too, so diff --git a/docs/requirements/Component-SiteCallAudit.md b/docs/requirements/Component-SiteCallAudit.md index 007cd740..b087d8ce 100644 --- a/docs/requirements/Component-SiteCallAudit.md +++ b/docs/requirements/Component-SiteCallAudit.md @@ -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 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)` 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 diff --git a/src/ZB.MOM.WW.ScadaBridge.AuditLog/Central/GrpcPullAuditEventsClient.cs b/src/ZB.MOM.WW.ScadaBridge.AuditLog/Central/GrpcPullAuditEventsClient.cs index 3ea53192..79b831db 100644 --- a/src/ZB.MOM.WW.ScadaBridge.AuditLog/Central/GrpcPullAuditEventsClient.cs +++ b/src/ZB.MOM.WW.ScadaBridge.AuditLog/Central/GrpcPullAuditEventsClient.cs @@ -47,7 +47,7 @@ namespace ZB.MOM.WW.ScadaBridge.AuditLog.Central; /// inject a fake invoker so no real HTTP/2 endpoint is required. /// /// -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); + } + + /// + public async Task 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); + } + + /// + /// + /// The per-endpoint path () 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). + /// + public void RetainOnly(IReadOnlyList 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; diff --git a/src/ZB.MOM.WW.ScadaBridge.AuditLog/Central/GrpcPullSiteCallsClient.cs b/src/ZB.MOM.WW.ScadaBridge.AuditLog/Central/GrpcPullSiteCallsClient.cs index f5d83431..644eef73 100644 --- a/src/ZB.MOM.WW.ScadaBridge.AuditLog/Central/GrpcPullSiteCallsClient.cs +++ b/src/ZB.MOM.WW.ScadaBridge.AuditLog/Central/GrpcPullSiteCallsClient.cs @@ -54,7 +54,7 @@ namespace ZB.MOM.WW.ScadaBridge.AuditLog.Central; /// inject a fake invoker so no real HTTP/2 endpoint is required. /// /// -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); + } + + /// + public async Task 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); + } + + /// + /// + /// 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). + /// + public void RetainOnly(IReadOnlyList 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; diff --git a/src/ZB.MOM.WW.ScadaBridge.AuditLog/Central/IPullAuditEventsClient.cs b/src/ZB.MOM.WW.ScadaBridge.AuditLog/Central/IPullAuditEventsClient.cs index e04357c7..3d13f1b0 100644 --- a/src/ZB.MOM.WW.ScadaBridge.AuditLog/Central/IPullAuditEventsClient.cs +++ b/src/ZB.MOM.WW.ScadaBridge.AuditLog/Central/IPullAuditEventsClient.cs @@ -59,4 +59,28 @@ public interface IPullAuditEventsClient string? afterId, int batchSize, CancellationToken ct); + + /// + /// Issues a PullAuditEvents 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 + /// . + /// + /// The site being pulled (selects the preshared key). + /// The node's gRPC authority to dial. + /// The node's composite-cursor timestamp half. + /// The node's composite-cursor id half (see ). + /// Maximum number of events to return per call. + /// Cancellation token. + /// A task that resolves to the next batch from that node. + Task PullFromEndpointAsync( + string siteId, + string endpoint, + DateTime sinceUtc, + string? afterId, + int batchSize, + CancellationToken ct) + => PullAsync(siteId, sinceUtc, afterId, batchSize, ct); } diff --git a/src/ZB.MOM.WW.ScadaBridge.AuditLog/Central/IPullSiteCallsClient.cs b/src/ZB.MOM.WW.ScadaBridge.AuditLog/Central/IPullSiteCallsClient.cs index f58c0ab7..1396874f 100644 --- a/src/ZB.MOM.WW.ScadaBridge.AuditLog/Central/IPullSiteCallsClient.cs +++ b/src/ZB.MOM.WW.ScadaBridge.AuditLog/Central/IPullSiteCallsClient.cs @@ -64,4 +64,27 @@ public interface IPullSiteCallsClient string? afterId, int batchSize, CancellationToken ct); + + /// + /// Issues a PullSiteCalls 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 . + /// + /// The site being pulled (selects the preshared key; re-stamped on rows). + /// The node's gRPC authority to dial. + /// The node's composite-cursor timestamp half. + /// The node's composite-cursor id half. + /// Maximum number of rows to return per call. + /// Cancellation token. + /// A task that resolves to the next batch from that node. + Task PullFromEndpointAsync( + string siteId, + string endpoint, + DateTime sinceUtc, + string? afterId, + int batchSize, + CancellationToken ct) + => PullAsync(siteId, sinceUtc, afterId, batchSize, ct); } diff --git a/src/ZB.MOM.WW.ScadaBridge.AuditLog/Central/SiteAuditReconciliationActor.cs b/src/ZB.MOM.WW.ScadaBridge.AuditLog/Central/SiteAuditReconciliationActor.cs index 0fb43806..4b681022 100644 --- a/src/ZB.MOM.WW.ScadaBridge.AuditLog/Central/SiteAuditReconciliationActor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.AuditLog/Central/SiteAuditReconciliationActor.cs @@ -106,7 +106,14 @@ public class SiteAuditReconciliationActor : ReceiveActor /// write, so the cursor is an optimization for exactness, never a correctness crutch. /// /// - private readonly Dictionary _cursors = new(); + /// + /// Keyed per (site, node endpoint) 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 MarkReconciledUpToAsync retire rows central never + /// received. + /// + private readonly Dictionary<(string SiteId, string Endpoint), (DateTime Since, string? AfterId)> _cursors = new(); /// /// 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 sites, Akka.Event.EventStream eventStream) { var live = new HashSet(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 } } - /// Test seam: number of sites with a held reconciliation cursor. - internal int TrackedSiteCountForTests => _cursors.Count; + /// Test seam: number of sites with at least one held reconciliation cursor. + internal int TrackedSiteCountForTests => _cursors.Keys.Select(k => k.SiteId).Distinct().Count(); + + /// Test seam: number of (site, node) cursors held. + internal int TrackedNodeCursorCountForTests => _cursors.Count; + + /// + /// 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). + /// + private static IEnumerable 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; + } + } /// /// 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); } /// @@ -403,16 +462,17 @@ public class SiteAuditReconciliationActor : ReceiveActor /// /// The site's response and whether the cursor moved. 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); diff --git a/src/ZB.MOM.WW.ScadaBridge.SiteCallAudit/SiteCallAuditActor.cs b/src/ZB.MOM.WW.ScadaBridge.SiteCallAudit/SiteCallAuditActor.cs index 47786f52..eba998c3 100644 --- a/src/ZB.MOM.WW.ScadaBridge.SiteCallAudit/SiteCallAuditActor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.SiteCallAudit/SiteCallAuditActor.cs @@ -132,7 +132,12 @@ public class SiteCallAuditActor : ReceiveActor /// next tick re-pulls from the start and idempotent upsert dedupes). Mirrors /// SiteAuditReconciliationActor's cursor (now composite). /// - private readonly Dictionary _reconciliationCursors = new(); + /// + /// Keyed per (site, node endpoint) 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. + /// + private readonly Dictionary<(string SiteId, string Endpoint), (DateTime Since, string? AfterId)> _reconciliationCursors = new(); /// /// Per-site "pinned" latch — true 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); } } + /// + /// 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). + /// + private static IEnumerable 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; + } + } + + /// Test seam: number of (site, node) reconciliation cursors held. + internal int ReconciliationCursorCountForTests => _reconciliationCursors.Count; + /// /// 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); + } + + /// + /// Drains one node of a site (see for the cursor, page and + /// pinned semantics). Returns true when the node's cursor is pinned (a legacy node that + /// ignores the after_id keyset). + /// + private async Task 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; } /// diff --git a/tests/ZB.MOM.WW.ScadaBridge.AuditLog.Tests/Central/ReconciliationPerNodeTests.cs b/tests/ZB.MOM.WW.ScadaBridge.AuditLog.Tests/Central/ReconciliationPerNodeTests.cs new file mode 100644 index 00000000..5d8f087c --- /dev/null +++ b/tests/ZB.MOM.WW.ScadaBridge.AuditLog.Tests/Central/ReconciliationPerNodeTests.cs @@ -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; + +/// +/// 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. +/// +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> EnumerateAsync(CancellationToken ct = default) => + Task.FromResult>(sites); + } + + /// + /// 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. + /// + 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 PullAsync( + string siteId, DateTime sinceUtc, string? afterId, int batchSize, CancellationToken ct) => + throw new InvalidOperationException("the actor must pull per node"); + + public Task 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(); + return Task.FromResult(new PullAuditEventsResponse(events, MoreAvailable: false)); + } + } + + /// + /// 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). + /// + [Fact] + public void BothNodesArePulled_EachWithItsOwnCursor() + { + var client = new PerNodeClient(); + var repo = Substitute.For(); + var inserted = new ConcurrentBag(); + repo.InsertManyIfNotExistsAsync(Arg.Any>(), Arg.Any(), Arg.Any()) + .Returns(ci => + { + foreach (var e in (IReadOnlyList)ci[0]) inserted.Add(e.EventId); + return Task.FromResult(((IReadOnlyList)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.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 Endpoints { get; } = new(); + + public Task InvokeAsync(string siteId, string endpoint, ProtoPullRequest request, CancellationToken ct) + { + Endpoints.Enqueue(endpoint); + throw new RpcException(new Grpc.Core.Status(StatusCode.Unavailable, "node down")); + } + } + + /// The per-node pull dials only the node it is given — no NodeA→NodeB failover. + /// A task that represents the asynchronous operation. + [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.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()); + } +} diff --git a/tests/ZB.MOM.WW.ScadaBridge.SiteCallAudit.Tests/SiteCallAuditReconciliationTests.cs b/tests/ZB.MOM.WW.ScadaBridge.SiteCallAudit.Tests/SiteCallAuditReconciliationTests.cs index 4141187d..e0adbafe 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.SiteCallAudit.Tests/SiteCallAuditReconciliationTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.SiteCallAudit.Tests/SiteCallAuditReconciliationTests.cs @@ -1192,4 +1192,57 @@ public class SiteCallAuditReconciliationTests : TestKit return new PullSiteCallsResponse(Array.Empty(), MoreAvailable: false); } } + + /// Records each per-node pull; only NodeB owes a row (an unreplicated pair after a NodeA restart). + private sealed class PerNodePullClient(SiteCall nodeBRow) : IPullSiteCallsClient + { + public System.Collections.Concurrent.ConcurrentQueue<(string Endpoint, DateTime Since)> Calls { get; } = new(); + + /// + public Task PullAsync( + string siteId, DateTime sinceUtc, string? afterId, int batchSize, CancellationToken ct) => + throw new InvalidOperationException("the actor must pull per node"); + + /// + public Task 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(); + return Task.FromResult(new PullSiteCallsResponse(rows, MoreAvailable: false)); + } + } + + /// + /// 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. + /// + [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); + } }