diff --git a/docs/DataConnections.md b/docs/DataConnections.md index f8830312d..ab7426020 100644 --- a/docs/DataConnections.md +++ b/docs/DataConnections.md @@ -204,7 +204,15 @@ retained bytes, metadata and call lifetimes. Tune them together for measured wor defaults are admission bounds, not a throughput or capacity guarantee. Overload can reject work or reset a stream, requiring a fresh snapshot. Do not interpret that recovery as lossless replay. A reset reading "Source change history expired." (consumer `ResetHistory`) means the origin lost a -source's change history for an item it still serves. Until #962 a Subscribe-stream `Modify` command that +source's change history for an item it still serves. Since #1026 an origin names every other interest-reset +cause separately (they all used to read "history expired"): "Source invalidated (<reason>)." — one of the +stream's own sources was invalidated, `` a `SourceInvalidationReason` such as `SerializationContention` +(consumer `ResetSourceInvalidated`); "Source retired." (its producer retired it: the driver stopped or was redeployed, or +the origin is shutting down), "Source interest released.", "Source routing changed.", "Source partition reset." and +"Source binding replaced." (consumer `ResetInterestLost`). These texts are for people and counters +only; no peer branches on them. The origin also counts each invalidation by reason +(`otopcua.dataconn.source.invalidations{reason}`, and `Invalidate.` in `SourceIngressDiagnostics`) and +logs it at Debug (`PartitionedSampleHub`); a stream reset is logged at Information. Until #962 a Subscribe-stream `Modify` command that replaces the origin item (trigger, deadband or view change) could also produce it intermittently: the modify's acknowledgement released the replaced item's interest while a session tick was reading it. That release is no longer counted as a lost history; the replacement continues with its own snapshot. @@ -380,6 +388,35 @@ and the client kept it until the source changed again. The worker now records th version is queued), and a commit older than that version re-considers the source against the new baseline. Pre-existing (not caused by #1098's sample hand-off), and independent of whether the hub sample and the item share a serving. +### Large projected mappings (#1026) + +The #1026 scale gate (`scripts/validation/grpc-data/scale_gate.py`, a 160-item and an 1888-item mapping on one connection) +found two defects that only show at hundreds of items: + +- **Origin: a binding check no longer invalidates a live source.** The driver actor's source-binding retry re-walks every + desired reference (from the start, every ≤ 30 s once any one failed). For a reference already bound to the current + producer, that walk took the source's serialization gate; when the poll thread was publishing the same source at that + moment, both sides invalidated it (`BindingContention` here, `SerializationContention` on the publish), resetting every + origin stream holding it, on every pass. `EnsureDriverBinding` now answers an already-bound, current source without the + gate. Live: 10 own-source invalidations during the open (only those two reasons) ⇒ 1. +- **Consumer: a cohort renews its metadata leases in batches.** Each projected item renewed its own lease (15 s by default, + renewed in its second half) with its own capabilities + GetMetadata pair, each holding a 256 KiB unary-budget + reservation. At the default `MaxPendingBytes` (1 MiB) four could run at once; the rest failed and retried on the next + 250 ms renewal tick, so a cohort renewed ~16 items a second. A 2048-item cohort's leases lapsed faster than they renewed: + the lapsed items were stood down `BadUserAccessDenied`, the attempts tore down ("Renewal snapshot did not establish a + complete baseline"), and after an origin restart the serial per-item re-renewal never caught up (0 of 2048 recovered in + 240 s). Live counters: 155 703 renewals started, 153 019 refused by the unary budget, 2 564 committed. A cohort now renews + every due item of a tick in batches of up to 128 (`RemoteNamespaceResolver.RenewExactBatchAsync`: one capabilities call and + one GetMetadata per origin `MaxBatchItems`, under one reservation; every per-item check, lease bound and commit is the + single-item renewal's, which is now the batch with one item). The between-attempt renewal (after an origin restart every + item needs a new serving identity) is batched the same way. Cadences of one node still share one renewal (#969); two + demands of one node in one cohort (two clients' items at the same interval, or an abandoned subscription beside its + replacement) share it too — the batch publishes its verdict before it waits for the joining demand. +- **Diagnostics.** `ProjectedStreamDiagnostics` counts `RenewalStarted/Succeeded/Failed/Budget/Slots`, where a renewal did not + commit (`RenewalFail.`: the call, the item's answer, the commit fence, the catalog cache) and why a cohort attempt + ended (`AttemptEnd.[: ]` or `AttemptEnd.` such as `ServingMismatch` / + `InvalidDemandAtFreshness`); at most 64 distinct keys. + ### Mixed versions (X0 rollout) The remote history and alarm work (`docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md`) diff --git a/scripts/validation/grpc-data/README.md b/scripts/validation/grpc-data/README.md index db5de2652..6a445fa89 100644 --- a/scripts/validation/grpc-data/README.md +++ b/scripts/validation/grpc-data/README.md @@ -224,6 +224,10 @@ the consumer `ProjectedStreamDiagnostics` counters (`projection-diagnostics` nod scale block (`--churn-hz`, default 4) and `docker compose restart`s both SOURCE nodes; waits for the pair's readiness, stops the churn, sets a never-used value and requires every item Good with it again; then requires the consumer `ResetHistory` counter ("Source change history expired." resets) unchanged and no "history expired" line in the SOURCE/CONSUMER logs. +Since #1026 an origin names its other interest resets ("Source invalidated ().", "Source interest released.", …), so +the gate also requires the consumer `ResetSourceInvalidated` / `ResetInterestLost` deltas zero and no "stream reset: Source +invalidated (" log line, and records the SOURCE `SourceIngressDiagnostics` (`Invalidate.` per invalidation reason) +after the open, before the restart and at the end (`origin_counters_*` in the evidence). ## Scenario authoring and node probes diff --git a/scripts/validation/grpc-data/probe/ProbeEngine.cs b/scripts/validation/grpc-data/probe/ProbeEngine.cs index f3cbfaf32..068912d34 100644 --- a/scripts/validation/grpc-data/probe/ProbeEngine.cs +++ b/scripts/validation/grpc-data/probe/ProbeEngine.cs @@ -343,7 +343,10 @@ public static class ProbeEngine "Snapshot admission exhausted; retry later." or "Freshness snapshot admission exhausted; retry later." or "Pending snapshot memory exhausted." or "Pending value memory exhausted." or "Pending value capacity exhausted." or "Pending control capacity exhausted." or - "Transport capacity exhausted." => diagnostic, + "Transport capacity exhausted." or + "Source interest released." or "Source routing changed." or "Source partition reset." or "Source binding replaced." or "Source retired." => diagnostic, + // #1026: the suffix is a bounded SourceInvalidationReason name. + _ when diagnostic.StartsWith("Source invalidated (", StringComparison.Ordinal) && diagnostic.Length <= 64 => diagnostic, _ when diagnostic.StartsWith("Snapshot pacing; retry after ", StringComparison.Ordinal) => "Snapshot pacing", _ => "Other server control reason", }; diff --git a/scripts/validation/grpc-data/scale_gate.py b/scripts/validation/grpc-data/scale_gate.py index a13bdc7ee..65711896a 100644 --- a/scripts/validation/grpc-data/scale_gate.py +++ b/scripts/validation/grpc-data/scale_gate.py @@ -182,6 +182,18 @@ class ScaleGate: return found time.sleep(3) + def origin_counters(self): + """#1026 evidence: SOURCE `SourceIngressDiagnostics` (incl. `Invalidate.`), non-zero only; process-lifetime.""" + out = {} + for node in ("source-1", "source-2"): + try: + observed = self.runner.probe(node, "topology", timeout=30) + counters = (observed.get("originAccounting") or {}).get("sourceIngressCounters") or {} + out[node] = {key: value for key, value in counters.items() if value} + except (scenarios.ScenarioError, rig.RigError, OSError) as error: + out[node] = {"error": type(error).__name__} + return out + def counters(self, consumers): out = {} mapping = self.scale["mappings"][0] @@ -250,7 +262,10 @@ class ScaleGate: except rig.RigError: hits[node] = None continue - hits[node] = [line[-400:] for line in text.splitlines() if "history expired" in line.lower()][:20] + hits[node] = [line[-400:] for line in text.splitlines() + # #1026: an own-source invalidation used to read "history expired" too. (A released interest + # or a partition reset of the origin shutting down is the stream's own teardown, not a loss.) + if "history expired" in line.lower() or "stream reset: source invalidated (" in line.lower()][:20] return hits def run(self): @@ -295,6 +310,8 @@ class ScaleGate: counters_before = self.counters(consumers) self.evidence["counters_before"] = counters_before self.mark("counters-before", reset_history={n: c.get("ResetHistory") for n, c in counters_before.items()}) + self.evidence["origin_counters_after_open"] = self.origin_counters() + self.mark("origin-counters-after-open", **self.evidence["origin_counters_after_open"]) stop_churn = threading.Event() churn_steps = [] @@ -319,6 +336,9 @@ class ScaleGate: "good_now": sum(1 for item in s.view().values() if cli_gate.is_good_status(item["status"]))} for s in subscribers} self.mark("pre-restart-churn", **self.evidence["pre_restart_churn"]) + self.evidence["counters_before_restart"] = self.counters(consumers) + self.evidence["origin_counters_before_restart"] = self.origin_counters() + self.mark("origin-counters-before-restart", **self.evidence["origin_counters_before_restart"]) restart_at = time.monotonic() self.mark("origin-restart-begin", nodes=["source-1", "source-2"]) runner.rig.compose("restart", "--timeout", "10", "source-1", "source-2", timeout=180) @@ -343,13 +363,22 @@ class ScaleGate: counters_after = self.counters(consumers) self.evidence["counters_after"] = counters_after deltas = {node: {key: counters_after[node].get(key, 0) - counters_before[node].get(key, 0) - for key in ("Reset", "ResetHistory", "ResetUnavailable", "ResetSnapshot", "ResetOther", "Attempt", "SnapshotEnd")} + for key in ("Reset", "ResetHistory", "ResetUnavailable", "ResetSnapshot", "ResetSourceInvalidated", + "ResetInterestLost", "ResetOther", "Attempt", "SnapshotEnd")} for node in consumers} self.evidence["counter_deltas"] = deltas self.mark("counters-after", deltas=deltas) + self.evidence["origin_counters_end"] = self.origin_counters() + self.mark("origin-counters-end", **self.evidence["origin_counters_end"]) self.check(all(delta["ResetHistory"] == 0 for delta in deltas.values()), "no 'Source change history expired.' reset reached either CONSUMER (ResetHistory delta 0)", reset_history={node: delta["ResetHistory"] for node, delta in deltas.items()}) + # #1026: before the origin named its reset causes, an own-source invalidation and a lost interest also read + # "Source change history expired."; they must stay zero too or the renamed text would pass the gate vacuously. + self.check(all(delta["ResetSourceInvalidated"] == 0 and delta["ResetInterestLost"] == 0 for delta in deltas.values()), + "no origin interest reset of any other cause either (ResetSourceInvalidated / ResetInterestLost delta 0)", + source_invalidated={node: delta["ResetSourceInvalidated"] for node, delta in deltas.items()}, + interest_lost={node: delta["ResetInterestLost"] for node, delta in deltas.items()}) self.check(all(counters_after[n].get("ResetHistory", 0) == 0 for n in consumers), "ResetHistory is 0 since CONSUMER process start", totals={n: counters_after[n].get("ResetHistory") for n in consumers}) for s in subscribers: diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs index 893364fa2..e245c3a48 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs @@ -68,7 +68,8 @@ public static class DataConnectionRegistration ConditionKeys = ReportConditionKeys(sp.GetRequiredService(), LoggerFor(sp)) }; }); - services.AddSingleton(sp => new PartitionedSampleHub(options.Hub, sp.GetRequiredService())); + services.AddSingleton(sp => new PartitionedSampleHub(options.Hub, sp.GetRequiredService()) + { Logger = LoggerFor(sp) }); services.AddSingleton(sp => new SourceSamplePublisher(sp.GetRequiredService(), () => sp.GetRequiredService().Serving, sp.GetRequiredService().ClusterId)); services.AddSingleton(sp => new DataOperationPolicy(sp.GetRequiredService(), diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs index c28093660..c83b91b5c 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataSubscriptionSession.cs @@ -1,6 +1,7 @@ using System.Threading.Channels; using System.Collections.Concurrent; using System.Runtime.CompilerServices; +using Microsoft.Extensions.Logging; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; @@ -906,7 +907,13 @@ internal sealed partial class DataSubscriptionSession : IDataSubscriptionTranspo bool released; lock (_gate) released = group.Released; if (released) continue; - CloseWithReset("Source change history expired."); return; + // #1026: name the actual cause; every one of them used to read "Source change history expired.". + var resetReason = group.Lease.ResetReason; + var diagnostic = InterestResetDiagnostics.Describe(resetReason, group.Lease.ResetSourceReason); + // A Released lease is normally this stream's own teardown (its cancellation disposed the lease first): Debug. + _services.Logger.Log(resetReason == InterestResetReason.Released ? LogLevel.Debug : LogLevel.Information, + "Origin subscription stream reset: {Diagnostic} (interest {Reason})", diagnostic, resetReason); + CloseWithReset(diagnostic); return; } foreach (var change in changes) MarkDirty(change.Ticket.Key); behind |= more; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/InterestResetDiagnostics.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/InterestResetDiagnostics.cs new file mode 100644 index 000000000..594ba0ce1 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/InterestResetDiagnostics.cs @@ -0,0 +1,30 @@ +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// +/// #1026: the human-readable Reset diagnostic an origin Subscribe stream sends when its interest lease stops. These are wire +/// text for people and diagnostics only; the consumer classifies them for counters +/// and never branches behaviour on them. Before #1026 every cause read "Source change history expired.". +/// +public static class InterestResetDiagnostics +{ + public const string HistoryExpired = "Source change history expired."; + public const string Released = "Source interest released."; + public const string RoutingChanged = "Source routing changed."; + public const string PartitionReset = "Source partition reset."; + public const string SourceInvalidatedPrefix = "Source invalidated ("; + public const string BindingReplaced = "Source binding replaced."; + /// The source's producer retired it (its driver stopped, was redeployed, or the origin is shutting down). + public const string Retired = "Source retired."; + + public static string Describe(InterestResetReason reason, SourceInvalidationReason source) => reason switch + { + InterestResetReason.Released => Released, + InterestResetReason.RoutingEpoch => RoutingChanged, + InterestResetReason.PartitionEpoch => PartitionReset, + InterestResetReason.SourceInvalidated when source == SourceInvalidationReason.Retired => Retired, + InterestResetReason.SourceInvalidated when source == SourceInvalidationReason.PartitionInvalidated => PartitionReset, + InterestResetReason.SourceInvalidated => SourceInvalidatedPrefix + source + ").", + InterestResetReason.SourceNotCurrent => BindingReplaced, + _ => HistoryExpired + }; +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/PartitionedSampleHub.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/PartitionedSampleHub.cs index 52b55cb46..6d2b6ffd4 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/PartitionedSampleHub.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/PartitionedSampleHub.cs @@ -1,4 +1,6 @@ using System.Collections.Concurrent; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; @@ -238,7 +240,19 @@ public sealed class PartitionedSampleHub : ISourceSampleHub, IDisposable { ArgumentException.ThrowIfNullOrWhiteSpace(reason); if (!IsDisposed && ValidKey(key)) Partition(key).InvalidatePartition(); } public bool TryReserveIngress(SourceTicket ticket, long estimatedRetainedBytes, out IIngressReservation? reservation) { if (!IsDisposed && ValidKey(ticket.Key)) return Partition(ticket.Key).TryReserve(ticket, estimatedRetainedBytes, out reservation); reservation = null; return false; } - public void Invalidate(SourceTicket ticket, string reason) { ArgumentException.ThrowIfNullOrWhiteSpace(reason); if (!IsDisposed && ValidKey(ticket.Key)) Partition(ticket.Key).Invalidate(ticket); } + public void Invalidate(SourceTicket ticket, string reason) + { + ArgumentException.ThrowIfNullOrWhiteSpace(reason); + if (!IsDisposed && ValidKey(ticket.Key)) Partition(ticket.Key).Invalidate(ticket, SourceInvalidationReasons.Classify(reason)); + } + /// #1026: Debug-level record of each source invalidation (reason, source kind and id; never a value). + public ILogger Logger { get; init; } = NullLogger.Instance; + internal void LogInvalidation(BackingSourceKey key, SourceInvalidationReason reason, bool retired) + { + if (!Logger.IsEnabled(LogLevel.Debug)) return; + Logger.LogDebug("Origin source invalidated: {Reason} ({SourceKind} {SourceId}, retired {Retired})", + reason, key.SourceKind, key.StableSourceId, retired); + } public bool TryPublishStatus(SourceTicket ticket, long sequence, uint statusCode, DateTimeOffset? sourceTimestampUtc, DateTimeOffset? serverTimestampUtc) => !IsDisposed && ValidKey(ticket.Key) && Partition(ticket.Key).TryStatus(ticket, sequence, statusCode, sourceTimestampUtc, serverTimestampUtc); public bool TryRemove(SourceTicket ticket, long sequence) => !IsDisposed && ValidKey(ticket.Key) && Partition(ticket.Key).TryRemove(ticket, sequence); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedCatalogCache.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedCatalogCache.cs index 9767c3965..fe7deb2d5 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedCatalogCache.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedCatalogCache.cs @@ -448,39 +448,45 @@ public sealed class ProjectedCatalogCache var retainedPrevious = current is not null && ReferenceEquals(current.Proof, previous) && !current.Retired || _retiredByProof.ContainsKey(previous); var mapping = previous.Metadata.View.MappingId; - if (!retainedPrevious || mapping is null || _saturated || - !_mappingGenerations.TryGetValue(mapping, out var generation) || frozen.Generation != generation || - !SameRenewalLineage(previous, frozen) || overlap && (!Valid(previous) || !SameOverlap(previous, frozen)) || - !Valid(frozen)) return false; + if (!retainedPrevious) { ProjectedStreamDiagnostics.CountRenewalFailure("Cache.PreviousGone"); return false; } + if (mapping is null || _saturated || + !_mappingGenerations.TryGetValue(mapping, out var generation) || frozen.Generation != generation) + { ProjectedStreamDiagnostics.CountRenewalFailure("Cache.Generation"); return false; } + if (!SameRenewalLineage(previous, frozen)) { ProjectedStreamDiagnostics.CountRenewalFailure("Cache.Lineage"); return false; } + if (overlap && !Valid(previous)) { ProjectedStreamDiagnostics.CountRenewalFailure("Cache.PreviousInvalid"); return false; } + if (overlap && !SameOverlap(previous, frozen)) { ProjectedStreamDiagnostics.CountRenewalFailure("Cache.NotSameOverlap"); return false; } + if (!Valid(frozen)) { ProjectedStreamDiagnostics.CountRenewalFailure("Cache.ReplacementInvalid"); return false; } if (current is not null && !ReferenceEquals(current.Proof, previous)) { // A previous SDK transaction can lose its final guard after the cache // committed. Only an exact descendant of the still-pinned old proof may // be adopted/replaced; never overwrite an unrelated current binding. - if (!SameRenewalLineage(previous, current.Proof)) return false; + if (!SameRenewalLineage(previous, current.Proof)) { ProjectedStreamDiagnostics.CountRenewalFailure("Cache.CurrentLineage"); return false; } if (Valid(current.Proof)) { if (overlap && (current.Predecessor is not { Pins: > 0 } predecessor || - !ReferenceEquals(predecessor.Proof, previous) || !SameOverlap(previous, current.Proof))) return false; + !ReferenceEquals(predecessor.Proof, previous) || !SameOverlap(previous, current.Proof))) + { ProjectedStreamDiagnostics.CountRenewalFailure("Cache.AdoptPredecessor"); return false; } if (current.Proof.Lease.Serving != frozen.Lease.Serving || !SameMetadata(current.Proof.Metadata, frozen.Metadata) || - !SameMetadata(current.Proof.OriginMetadata, frozen.OriginMetadata)) return false; + !SameMetadata(current.Proof.OriginMetadata, frozen.OriginMetadata)) { ProjectedStreamDiagnostics.CountRenewalFailure("Cache.AdoptShape"); return false; } committed = current.Proof; return true; } } var addsEntry = current is null || current.Pins > 0; - if (overlap && (current is null || current.Pins <= 0 || !ReferenceEquals(current.Proof, previous))) return false; - if (_nodes.Count + _retiredPinned.Count + (addsEntry ? 1 : 0) > _maxNodes) return false; + if (overlap && (current is null || current.Pins <= 0 || !ReferenceEquals(current.Proof, previous))) + { ProjectedStreamDiagnostics.CountRenewalFailure(current is null ? "Cache.OverlapNoCurrent" : current.Pins <= 0 ? "Cache.OverlapUnpinned" : "Cache.OverlapNotCurrent"); return false; } + if (_nodes.Count + _retiredPinned.Count + (addsEntry ? 1 : 0) > _maxNodes) { ProjectedStreamDiagnostics.CountRenewalFailure("Cache.MaxNodes"); return false; } // A replacement and one still-pinned predecessor are distinct physical owners, // but only one logical projected node. Never admit a chain of predecessors. _retiredPerNode.TryGetValue(key, out var oldCount); - if ((long)oldCount + (current is { Pins: > 0 } ? 1 : 0) + 1 > 2) return false; + if ((long)oldCount + (current is { Pins: > 0 } ? 1 : 0) + 1 > 2) { ProjectedStreamDiagnostics.CountRenewalFailure("Cache.PredecessorChain"); return false; } _mappingNodeCounts.TryGetValue(mapping, out var count); var physicalMappingLimit = (long)maximumMappingNodes + Math.Min((long)maximumMappingNodes, _maxNodes); - if ((long)count + (addsEntry ? 1 : 0) > physicalMappingLimit) return false; + if ((long)count + (addsEntry ? 1 : 0) > physicalMappingLimit) { ProjectedStreamDiagnostics.CountRenewalFailure("Cache.MappingNodes"); return false; } var delta = Bytes(frozen) - (current is { Pins: 0 } ? Bytes(current.Proof) : 0); - if (delta > _maxBytes - _retainedBytes) return false; + if (delta > _maxBytes - _retainedBytes) { ProjectedStreamDiagnostics.CountRenewalFailure("Cache.Bytes"); return false; } AddNode(key, frozen); if (overlap) _nodes[key].Predecessor = current; committed = frozen; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs index f711da556..309db67d7 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs @@ -460,6 +460,39 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable /// by ). One that did not commit is no verdict for this cadence, which renews for /// itself. /// + /// #1026: whether another cadence is already renewing this predecessor for this node (#969 — join it, do not batch it). + private bool IsOverlapRenewing(ProjectedNodeProof predecessor, NodeId nodeId) + { + lock (_sync) + return DeduplicateOverlapRenewalsForTests && _overlapRenewals.TryGetValue(predecessor, out var running) && running.NodeId == nodeId; + } + + /// + /// #1026: a batched cadence renewal claims each predecessor it renews, exactly as owns + /// one, so another cadence reaching the same predecessor waits for it (#969). Null when not deduplicating or when the + /// predecessor is already claimed (a racing pair still commits one successor and the second adopts it). + /// + private TaskCompletionSource? ClaimOverlapRenewal(ProjectedNodeProof predecessor, NodeId nodeId, out bool running) + { + running = false; + lock (_sync) + { + if (!DeduplicateOverlapRenewalsForTests) return null; + // Claimed meanwhile by another cadence of this node: the caller joins it (RenewOverlapOnceAsync) instead. + if (_overlapRenewals.TryGetValue(predecessor, out var existing)) { running = existing.NodeId == nodeId; return null; } + var claim = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + _overlapRenewals.Add(predecessor, (nodeId, claim.Task)); + return claim; + } + } + + private void ReleaseOverlapRenewal(ProjectedNodeProof predecessor, TaskCompletionSource? claim, bool renewed) + { + if (claim is null) return; + lock (_sync) _overlapRenewals.Remove(predecessor); + claim.TrySetResult(renewed); + } + private async Task RenewOverlapOnceAsync(ProjectedNodeProof predecessor, NodeId nodeId, Func> renew, CancellationToken cancellationToken) { @@ -1566,28 +1599,41 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable var prepared = new List<(Demand Demand, Demand.Binding Old, Demand.Binding Next)>(); try { + void Prepare(Demand demand, Demand.Binding old, Demand.Binding replacement) + { + if (requireNewServing && replacement.Proof.Lease.Serving == _key.Serving) + { replacement.NodePin.Dispose(); replacement.Pin.Dispose(); return; } + prepared.Add((demand, old, replacement)); + } + // #1026: the demands that need an origin renewal are renewed in batches (one call per RenewalBatchItems), not one + // call pair after another. After an origin restart EVERY demand needs one (a new serving identity), and a + // 2048-item cohort renewed serially for longer than the leases it renewed lasted, so it never re-opened. + var resolver = _owner._catalog as RemoteNamespaceResolver; + var sink = _owner._renewalSink; + var renew = new List<(Demand Demand, Demand.Binding Old)>(); foreach (var demand in owned) { if (_stop.IsCancellationRequested) return; if (demand.Disposed) { ReleaseDemand(demand); continue; } if (demand.IsValid && !requireNewServing) continue; var old = demand.CurrentBinding; - using var demandStop = CancellationTokenSource.CreateLinkedTokenSource(_stop.Token, demand.CancellationToken); - var attempted = false; - if (requireNewServing && _owner._catalog is RemoteNamespaceResolver refresh && _owner._renewalSink is { } refreshSink) + // A new serving identity renews first; otherwise a still-usable proof is prepared without an origin call. + if (requireNewServing && resolver is not null && sink is not null) { renew.Add((demand, old)); continue; } + if (demand.TryPrepareBinding(old, out var replacement) && replacement is not null) { Prepare(demand, old, replacement); continue; } + if (resolver is not null && sink is not null) renew.Add((demand, old)); + } + if (resolver is not null && sink is not null) + for (var offset = 0; offset < renew.Count; offset += RenewalBatchItems) { - attempted = true; - await RenewOwnedAsync(demand, old, refresh, refreshSink, demandStop.Token).ConfigureAwait(false); + if (_stop.IsCancellationRequested) return; + await RenewOwnedBatchAsync(renew.GetRange(offset, Math.Min(RenewalBatchItems, renew.Count - offset)), resolver, sink, + _stop.Token).ConfigureAwait(false); } - if (!demand.TryPrepareBinding(old, out var replacement) || replacement is null) - { - if (attempted || _owner._catalog is not RemoteNamespaceResolver resolver || _owner._renewalSink is null) continue; - if (!await RenewOwnedAsync(demand, old, resolver, _owner._renewalSink, demandStop.Token).ConfigureAwait(false) || - !demand.TryPrepareBinding(old, out replacement) || replacement is null) continue; - } - if (requireNewServing && replacement.Proof.Lease.Serving == _key.Serving) - { replacement.NodePin.Dispose(); replacement.Pin.Dispose(); continue; } - prepared.Add((demand, old, replacement)); + foreach (var (demand, old) in renew) + { + if (_stop.IsCancellationRequested) return; + if (demand.Disposed || !demand.TryPrepareBinding(old, out var replacement) || replacement is null) continue; + Prepare(demand, old, replacement); } var installed = new HashSet(); var retired = new List(); @@ -1651,6 +1697,67 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable } finally { foreach (var item in prepared) { item.Next.NodePin.Dispose(); item.Next.Pin.Dispose(); } } } + /// #1026: how many owned items one renewal call carries (one capabilities call, one GetMetadata per origin batch). + internal const int RenewalBatchItems = 128; + /// + /// #1026: for up to demands under ONE unary-budget + /// reservation and one resolver call (). An overlap item whose + /// predecessor has under a second left renews alone, so it does not shorten the whole batch's deadline. + /// + private async Task RenewOwnedBatchAsync(IReadOnlyList<(Demand Demand, Demand.Binding Old)> items, RemoteNamespaceResolver resolver, + IProjectedNamespacePageSink sink, CancellationToken cancellationToken, bool overlap = false) + { + var results = new bool[items.Count]; + var batched = new List(items.Count); + var alone = new List(); + var timeout = TimeSpan.FromSeconds(5); + for (var i = 0; i < items.Count; i++) + { + if (items[i].Demand.Disposed) continue; + if (overlap && items[i].Old.Proof.Lease is BoundProjectionLease authority) + { + var remaining = authority.Remaining; + if (remaining <= TimeSpan.FromMilliseconds(1)) continue; + var bound = TimeSpan.FromTicks(remaining.Ticks - remaining.Ticks / 4); + if (bound < TimeSpan.FromSeconds(1)) { alone.Add(i); continue; } + if (bound < timeout) timeout = bound; + } + batched.Add(i); + } + if (batched.Count > 0) + { + var budget = new DataBudget(timeout, batched.Count, Math.Min(LapseRenewalBytes, _owner._limits.MaxUnaryBytes)); + var reserved = false; + lock (_owner._sync) + { + if (!_owner._disposed) + { + if (_owner._unaryCount >= _owner._limits.MaxUnaryOperations || budget.MaxBytes > _owner._limits.MaxUnaryBytes - _owner._unaryBytes) + ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.RenewalBudget); + else { _owner._unaryCount++; _owner._unaryBytes += budget.MaxBytes; reserved = true; } + } + } + if (reserved) + { + try + { + var batch = new RemoteNamespaceResolver.ExactRenewal[batched.Count]; + for (var j = 0; j < batched.Count; j++) + { + var (demand, old) = items[batched[j]]; + batch[j] = new(old.Proof, old.Definition, demand.NodeId, demand.Caller, demand.Configured, + () => !demand.Disposed && (!overlap || ReferenceEquals(demand.CurrentBinding, old) && demand.IsValid)); + } + var outcomes = await resolver.RenewExactBatchAsync(batch, sink, budget, cancellationToken, overlap).ConfigureAwait(false); + for (var j = 0; j < batched.Count; j++) results[batched[j]] = outcomes[j] == ProjectedRenewalResult.Renewed; + } + finally { lock (_owner._sync) { _owner._unaryCount--; _owner._unaryBytes -= budget.MaxBytes; } } + } + } + foreach (var i in alone) + results[i] = await RenewOwnedAsync(items[i].Demand, items[i].Old, resolver, sink, cancellationToken, overlap).ConfigureAwait(false); + return results; + } private async Task RenewOwnedAsync(Demand demand, Demand.Binding old, RemoteNamespaceResolver resolver, IProjectedNamespacePageSink sink, CancellationToken cancellationToken, bool overlap = false) { @@ -1666,8 +1773,9 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable var budget = new DataBudget(timeout, 1, Math.Min(LapseRenewalBytes, _owner._limits.MaxUnaryBytes)); lock (_owner._sync) { - if (_owner._disposed || demand.Disposed || _owner._unaryCount >= _owner._limits.MaxUnaryOperations || - budget.MaxBytes > _owner._limits.MaxUnaryBytes - _owner._unaryBytes) return false; + if (_owner._disposed || demand.Disposed) return false; + if (_owner._unaryCount >= _owner._limits.MaxUnaryOperations || budget.MaxBytes > _owner._limits.MaxUnaryBytes - _owner._unaryBytes) + { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.RenewalBudget); return false; } _owner._unaryCount++; _owner._unaryBytes += budget.MaxBytes; } try @@ -1823,26 +1931,93 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable else if (_owner._catalog is RemoteNamespaceResolver resolver && _owner._renewalSink is { } sink) { using var linked = CancellationTokenSource.CreateLinkedTokenSource(token, demand.CancellationToken); + ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.RenewalStarted); success = await _owner.RenewOverlapOnceAsync(expected.Proof, demand.NodeId, () => RenewOwnedAsync(demand, expected, resolver, sink, linked.Token, overlap: true), linked.Token).ConfigureAwait(false); + ProjectedStreamDiagnostics.Count(success ? ProjectedStreamDiagnostics.Event.RenewalSucceeded : ProjectedStreamDiagnostics.Event.RenewalFailed); } await _events.Writer.WriteAsync(new RenewedEvent(demand, expected, success), token).ConfigureAwait(false); } catch (Exception ex) when (ex is not OutOfMemoryException) { } } + // #1026: RenewAsync for a batch of due demands — the same per-item short cut, #969 predecessor claim and RenewedEvent, + // with one origin call for the batch. + async Task RenewBatchAsync(List<(Demand Demand, Demand.Binding Old)> batch, CancellationToken token) + { + var success = new bool[batch.Count]; + var claims = new TaskCompletionSource?[batch.Count]; + var pending = new List(batch.Count); + try + { + for (var i = 0; i < batch.Count; i++) + { + var (demand, expected) = batch[i]; + if (_owner._catalog.TryResolveProjected(expected.Definition.Realm, expected.Definition.LocalIdentifier, out var current) && + current is not null && !ReferenceEquals(current, expected.Proof) && _owner._catalog.IsUsableProof(expected.Proof) && + _owner._nodes.TryResolve(demand.NodeId, out var definition) && definition is not null && + RemoteNamespaceResolver.DefinitionOwnsProof(definition, current)) success[i] = true; + else pending.Add(i); + } + if (pending.Count > 0 && _owner._catalog is RemoteNamespaceResolver resolver && _owner._renewalSink is { } sink) + { + var owned = new List(pending.Count); + var joining = new List<(int Index, Task Renewal)>(); + foreach (var i in pending) + { + var (demand, expected) = batch[i]; + ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.RenewalStarted); + claims[i] = _owner.ClaimOverlapRenewal(expected.Proof, demand.NodeId, out var running); + if (!running) { owned.Add(i); continue; } + // #969: another cadence of this node claimed the predecessor since the tick looked: join it. + joining.Add((i, _owner.RenewOverlapOnceAsync(expected.Proof, demand.NodeId, + () => RenewOwnedAsync(demand, expected, resolver, sink, token, overlap: true), token))); + } + var items = new (Demand Demand, Demand.Binding Old)[owned.Count]; + for (var j = 0; j < owned.Count; j++) items[j] = batch[owned[j]]; + var renewed = items.Length == 0 ? [] : await RenewOwnedBatchAsync(items, resolver, sink, token, overlap: true).ConfigureAwait(false); + for (var j = 0; j < owned.Count; j++) + { + var i = owned[j]; + success[i] = renewed[j]; + // Publish the verdict BEFORE awaiting the joiners: a joiner may be waiting on a claim of THIS batch + // (two demands of one node in one cohort — two clients' items, or an abandoned subscription's). + _owner.ReleaseOverlapRenewal(batch[i].Old.Proof, claims[i], success[i]); + claims[i] = null; + } + foreach (var (i, renewal) in joining) + { + try { success[i] = await renewal.ConfigureAwait(false); } + catch (Exception ex) when (ex is not OutOfMemoryException) { success[i] = false; } + } + foreach (var i in pending) + ProjectedStreamDiagnostics.Count(success[i] ? ProjectedStreamDiagnostics.Event.RenewalSucceeded : ProjectedStreamDiagnostics.Event.RenewalFailed); + } + } + catch (Exception ex) when (ex is not OutOfMemoryException) { } + finally + { + for (var i = 0; i < batch.Count; i++) _owner.ReleaseOverlapRenewal(batch[i].Old.Proof, claims[i], success[i]); + } + try + { + for (var i = 0; i < batch.Count; i++) + await _events.Writer.WriteAsync(new RenewedEvent(batch[i].Demand, batch[i].Old, success[i]), token).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OutOfMemoryException) { } + } try { Demand[] initial; lock (_owner._sync) initial = _owner._demandCohorts.Where(x => ReferenceEquals(x.Value, this)).Select(x => x.Key).ToArray(); foreach (var demand in initial) if (demand.Disposed) ReleaseDemand(demand); initial = initial.Where(demand => !demand.Disposed && demand.IsValid && demand.Serving == _key.Serving).ToArray(); - if (initial.Length == 0) return; + if (initial.Length == 0) { ProjectedStreamDiagnostics.CountAttemptEnd("NoValidDemand"); return; } connection = await _owner._connections.AcquireAsync(_connectionId, attemptStop.Token).ConfigureAwait(false); if (connection is null || !ReferenceEquals(connection.Connection.Clock, _owner.Clock) || connection.CancellationToken.IsCancellationRequested) return; route = CancellationTokenSource.CreateLinkedTokenSource(attemptStop.Token, connection.CancellationToken); stream = await connection.Connection.SubscribeAsync(route.Token).ConfigureAwait(false); if (stream is not IDataSubscriptionProvenance provenance || provenance.Serving != _key.Serving) - { Interlocked.Exchange(ref _servingMismatch, 1); return; } + { Interlocked.Exchange(ref _servingMismatch, 1); ProjectedStreamDiagnostics.CountAttemptEnd("ServingMismatch"); return; } freshnessTimer = _owner.Clock.CreateTimer(_ => { if (Interlocked.Exchange(ref _freshnessQueued, 1) == 0 && !_events.Writer.TryWrite(new FreshnessEvent())) @@ -1880,7 +2055,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable } // A temporarily unavailable proof must not leave an unopened stream parked // forever. Retry the bounded attempt after backoff so renewal can make it usable. - if (addQueue.Count == 0) return; + if (addQueue.Count == 0) { ProjectedStreamDiagnostics.CountAttemptEnd("NothingToAdd"); return; } await FlushAsync(route.Token).ConfigureAwait(false); var sinceFlush = 0; while (true) @@ -1963,7 +2138,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable else if (message is FreshnessEvent) { Interlocked.Exchange(ref _freshnessQueued, 0); - if (_registrations.Values.Any(x => !x.Removed && !x.Demand.IsValid)) break; + if (_registrations.Values.Any(x => !x.Removed && !x.Demand.IsValid)) { ProjectedStreamDiagnostics.CountAttemptEnd("InvalidDemandAtFreshness"); break; } foreach (var registration in _registrations.Values) registration.NeedsChallenge = true; } else if (message is RenewalEvent) @@ -1978,6 +2153,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable // #1057: in place — a LINQ copy per source per renewal tick was O(sources) allocations. for (var i = witnesses.Count - 1; i >= 0; i--) if (!witnesses[i].LeaseValid) { witnesses[i].Close(); witnesses.RemoveAt(i); } + var due = new List<(Demand Demand, Demand.Binding Old)>(); foreach (var registration in _registrations.Values.ToArray()) { var demand = registration.Demand; @@ -1985,7 +2161,16 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable demand.Proof.Lease is not BoundProjectionLease lease || lease.RouteIdentity is null || lease.Remaining <= TimeSpan.Zero || lease.Remaining > lease.UsableDuration / 2) continue; var expected = demand.CurrentBinding; - renewals[demand] = RenewAsync(demand, expected, route.Token); + // #969: a predecessor another cadence is already renewing joins that renewal. + if (_owner.IsOverlapRenewing(expected.Proof, demand.NodeId)) renewals[demand] = RenewAsync(demand, expected, route.Token); + else due.Add((demand, expected)); + } + // #1026: the rest renew in batches — one call per RenewalBatchItems items, not one call pair per item. + for (var offset = 0; offset < due.Count; offset += RenewalBatchItems) + { + var slice = due.GetRange(offset, Math.Min(RenewalBatchItems, due.Count - offset)); + var batchTask = RenewBatchAsync(slice, route.Token); + foreach (var (demand, _) in slice) renewals[demand] = batchTask; } } finally { Interlocked.Increment(ref _owner._renewalTicksHandled); } @@ -2010,7 +2195,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable registration.RenewalPredecessor = renewed.Expected.Proof.Lease; if (registration.Handle is not null) removeQueue.Add(registration); } - else if (message is EndEvent) break; + else if (message is EndEvent) { ProjectedStreamDiagnostics.CountAttemptEnd("StreamEnded"); break; } else if (entry.Frame is not null) { var delivered = entry; @@ -2078,7 +2263,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable } else if (frame is DataSubscriptionControl control) { - if (control.CatalogEpoch != _key.Serving.CatalogEpoch || control.AuthorityEpoch != _key.Serving.AuthorityEpoch) break; + if (control.CatalogEpoch != _key.Serving.CatalogEpoch || control.AuthorityEpoch != _key.Serving.AuthorityEpoch) { ProjectedStreamDiagnostics.CountAttemptEnd("ControlEpoch"); break; } if (control.Kind == DataStreamControlKind.SnapshotBegin) { if (inSnapshot) throw new InvalidDataException("Overlapping snapshots."); @@ -2120,14 +2305,8 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable else if (control.Kind is DataStreamControlKind.Reset or DataStreamControlKind.CatalogInvalidated or DataStreamControlKind.AuthorityInvalidated) { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.Reset); - ProjectedStreamDiagnostics.Count(control.Diagnostic switch - { - "Source change history expired." => ProjectedStreamDiagnostics.Event.ResetHistory, - "Source became unavailable." => ProjectedStreamDiagnostics.Event.ResetUnavailable, - "Snapshot catch-up expired; retry later." or "Snapshot lifetime expired; retry later." => ProjectedStreamDiagnostics.Event.ResetSnapshot, - _ => ProjectedStreamDiagnostics.Event.ResetOther - }); - break; + ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.ClassifyReset(control.Diagnostic)); + ProjectedStreamDiagnostics.CountAttemptEnd("Reset"); break; } } else if (frame is DataSubscriptionValues values) @@ -2201,7 +2380,11 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable } } } - catch (Exception ex) { ProjectedStreamDiagnostics.Count(ex is OperationCanceledException ? ProjectedStreamDiagnostics.Event.AttemptCanceled : ex is InvalidDataException ? ProjectedStreamDiagnostics.Event.AttemptInvalidData : ProjectedStreamDiagnostics.Event.AttemptOther); } + catch (Exception ex) + { + ProjectedStreamDiagnostics.Count(ex is OperationCanceledException ? ProjectedStreamDiagnostics.Event.AttemptCanceled : ex is InvalidDataException ? ProjectedStreamDiagnostics.Event.AttemptInvalidData : ProjectedStreamDiagnostics.Event.AttemptOther); + ProjectedStreamDiagnostics.CountAttemptEnd(ex); + } finally { foreach (var proof in evidence.Values.SelectMany(witnesses => witnesses)) proof.Close(); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedStreamDiagnostics.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedStreamDiagnostics.cs index 7a6418557..77dcc218a 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedStreamDiagnostics.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedStreamDiagnostics.cs @@ -1,3 +1,5 @@ +using System.Collections.Concurrent; + namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; /// Bounded aggregate observations of projected stream admission and delivery. @@ -5,9 +7,58 @@ public static class ProjectedStreamDiagnostics { internal enum Event { AcquireInvalid, AcquireDefinition, AcquireAuthorization, AcquirePin, AcquireCapacity, AcquireStale, AcquireAccepted, AcquireException, Attempt, Frame, Reset, SnapshotEnd, Value, UnknownAge, StaleAge, FreshAge, PublishDemand, PublishStale, PublishVersion, PublishProof, PublishSink, PublishAccepted, - AttemptCanceled, AttemptInvalidData, AttemptOther, ResetHistory, ResetUnavailable, ResetSnapshot, ResetOther } + AttemptCanceled, AttemptInvalidData, AttemptOther, ResetHistory, ResetUnavailable, ResetSnapshot, ResetOther, + // #1026: an origin interest reset that is not history loss (see InterestResetDiagnostics). + ResetSourceInvalidated, ResetInterestLost, + // #1026: a cohort's per-item metadata lease renewals (started, committed, not committed, refused by the unary budget). + RenewalStarted, RenewalSucceeded, RenewalFailed, RenewalBudget, RenewalSlots } + /// #1026: classifies an origin Reset diagnostic (human text) into a bounded counter; never drives behaviour. + internal static Event ClassifyReset(string? diagnostic) => diagnostic switch + { + InterestResetDiagnostics.HistoryExpired => Event.ResetHistory, + "Source became unavailable." => Event.ResetUnavailable, + "Snapshot catch-up expired; retry later." or "Snapshot lifetime expired; retry later." => Event.ResetSnapshot, + InterestResetDiagnostics.Released or InterestResetDiagnostics.RoutingChanged or InterestResetDiagnostics.PartitionReset or + InterestResetDiagnostics.BindingReplaced or InterestResetDiagnostics.Retired => Event.ResetInterestLost, + _ when diagnostic?.StartsWith(InterestResetDiagnostics.SourceInvalidatedPrefix, StringComparison.Ordinal) == true => Event.ResetSourceInvalidated, + _ => Event.ResetOther + }; private static readonly long[] Counts = new long[Enum.GetValues().Length]; + private const int MaxAttemptEndKinds = 32; + private static readonly ConcurrentDictionary AttemptEnds = new(StringComparer.Ordinal); internal static void Count(Event value) => Interlocked.Increment(ref Counts[(int)value]); + /// + /// #1026: why a cohort attempt ended, keyed by exception type (and an InvalidDataException's constant message), at most + /// distinct keys; never an identifier or payload. + /// + internal static void CountAttemptEnd(Exception ex) + { + // Only this runtime's own InvalidDataException messages are constants; any other exception is keyed by its type alone. + var message = ex is InvalidDataException ? ": " + (ex.Message.Length > 96 ? ex.Message[..96] : ex.Message) : ""; + var key = "AttemptEnd." + ex.GetType().Name + message; + if (!AttemptEnds.ContainsKey(key) && AttemptEnds.Count >= MaxAttemptEndKinds) key = "AttemptEnd.(other)"; + AttemptEnds.AddOrUpdate(key, 1, static (_, count) => count + 1); + } + /// #1026: a constant-named point where a subscription lease renewal did not commit (bounded like attempt ends). + internal static void CountRenewalFailure(string point, int count = 1) + { + if (count <= 0) return; + var key = "RenewalFail." + point; + if (!AttemptEnds.ContainsKey(key) && AttemptEnds.Count >= 2 * MaxAttemptEndKinds) key = "RenewalFail.(other)"; + AttemptEnds.AddOrUpdate(key, count, (_, value) => value + count); + } + /// #1026: a constant-named reason a cohort attempt ended without an exception. + internal static void CountAttemptEnd(string reason) + { + var key = "AttemptEnd." + reason; + if (!AttemptEnds.ContainsKey(key) && AttemptEnds.Count >= 2 * MaxAttemptEndKinds) key = "AttemptEnd.(other)"; + AttemptEnds.AddOrUpdate(key, 1, static (_, value) => value + 1); + } /// Captures process-wide counters without source identifiers or payloads. - public static IReadOnlyDictionary Capture() => Enum.GetValues().ToDictionary(x => x.ToString(), x => Interlocked.Read(ref Counts[(int)x])); + public static IReadOnlyDictionary Capture() + { + var result = Enum.GetValues().ToDictionary(x => x.ToString(), x => Interlocked.Read(ref Counts[(int)x])); + foreach (var pair in AttemptEnds) result[pair.Key] = pair.Value; + return result; + } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/RemoteNamespaceResolver.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/RemoteNamespaceResolver.cs index b8e3e58e8..6efd3fec3 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/RemoteNamespaceResolver.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/RemoteNamespaceResolver.cs @@ -330,43 +330,78 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp NodeId nodeId, DataCallerIdentity? caller, ConfiguredProjectionCapability? configured, IProjectedNamespacePageSink sink, DataBudget budget, Func demandActive, CancellationToken cancellationToken, bool overlap = false, OpcUaOperation authorizeAs = OpcUaOperation.CreateMonitoredItems, DataOperations required = DataOperations.Subscribe, + bool onDemand = false) => + (await RenewExactBatchAsync([new ExactRenewal(previous, definition, nodeId, caller, configured, demandActive)], sink, budget, + cancellationToken, overlap, authorizeAs, required, onDemand).ConfigureAwait(false))[0]; + + /// #1026: one already-owned projected item of a call. + internal sealed record ExactRenewal(ProjectedNodeProof Previous, ProjectedVariableDefinition Definition, NodeId NodeId, + DataCallerIdentity? Caller, ConfiguredProjectionCapability? Configured, Func DemandActive); + + /// + /// #1026: renews several already-owned projected items of ONE data connection with one capabilities call and one + /// GetMetadata per origin batch () — every per-item check, lease bound and + /// commit is exactly 's (which is this with one item). A cohort used to renew each of its + /// items with its own call pair, each holding a unary-budget reservation; at the default budget only four could run at once + /// and the rest retried on the 250 ms renewal tick, so a cohort could renew ~16 items a second — a 2048-item cohort's leases + /// (15 s, renewed in their second half) lapsed faster than they renewed. An item of another connection is left Failed. + /// + internal async Task RenewExactBatchAsync(IReadOnlyList items, IProjectedNamespacePageSink sink, + DataBudget budget, CancellationToken cancellationToken, bool overlap = false, + OpcUaOperation authorizeAs = OpcUaOperation.CreateMonitoredItems, DataOperations required = DataOperations.Subscribe, bool onDemand = false) { const ProjectedRenewalResult Failed = ProjectedRenewalResult.Failed; const ProjectedRenewalResult Refused = ProjectedRenewalResult.Refused; + ArgumentNullException.ThrowIfNull(items); + var results = new ProjectedRenewalResult[items.Count]; + Array.Fill(results, Failed); // #922: a subscription renews for CreateMonitoredItems/Subscribe (the default); an on-demand renewal of a lapsed node // renews for the operation the caller is performing (Read / HistoryRead / #940 Write / Subscribe) and requires exactly // that bit at the origin. - if (authorizeAs is not (OpcUaOperation.CreateMonitoredItems or OpcUaOperation.Read or OpcUaOperation.HistoryRead or OpcUaOperation.WriteOperate) || - required is not (DataOperations.Subscribe or DataOperations.Read or DataOperations.HistoryRead or DataOperations.Write)) return Failed; - var mapping = previous.Metadata.View.MappingId; - if (mapping is null || previous.Subject.Scope.Segments.Count == 0) return Failed; - ProjectedMappingBinding binding; - lock (_sync) + if (items.Count == 0 || + authorizeAs is not (OpcUaOperation.CreateMonitoredItems or OpcUaOperation.Read or OpcUaOperation.HistoryRead or OpcUaOperation.WriteOperate) || + required is not (DataOperations.Subscribe or DataOperations.Read or DataOperations.HistoryRead or DataOperations.Write)) return results; + var eligible = new List(items.Count); + string? connectionId = null; + for (var index = 0; index < items.Count; index++) { - if (_disposed || !_mappings.TryGetValue(mapping, out binding!)) return Failed; + var item = items[index]; + var previous = item.Previous; + var mapping = previous.Metadata.View.MappingId; + if (mapping is null || previous.Subject.Scope.Segments.Count == 0) { ProjectedStreamDiagnostics.CountRenewalFailure("Item.NoMapping"); continue; } + ProjectedMappingBinding binding; + lock (_sync) + { + if (_disposed || !_mappings.TryGetValue(mapping, out binding!)) { ProjectedStreamDiagnostics.CountRenewalFailure("Item.NoBinding"); continue; } + } + var callerAllowed = CallerAllowedFor(item, mapping, binding, authorizeAs); + if (!IsCurrent(binding) || !binding.LocalAuthority.IsActive || !callerAllowed() || + previous.Metadata.View.MappingRevision != binding.Mapping.Revision || previous.Metadata.View.Realm != binding.Mapping.Realm || + previous.OriginMetadata.View.MappingId is not null || + previous.Subject.Scope.Kind != binding.LocalScope.Kind || + !string.Equals(previous.Subject.Scope.ClusterId, binding.LocalScope.ClusterId, StringComparison.OrdinalIgnoreCase) || + previous.Subject.Scope.Segments.Count < binding.LocalScope.Segments.Count || + !previous.Subject.Scope.Segments.Take(binding.LocalScope.Segments.Count).SequenceEqual(binding.LocalScope.Segments, StringComparer.Ordinal) || + !previous.Subject.LocalAncestry.SequenceEqual(binding.LocalAncestry, StringComparer.OrdinalIgnoreCase)) { ProjectedStreamDiagnostics.CountRenewalFailure("Item.Precheck"); continue; } + connectionId ??= binding.Mapping.DataConnectionId; + if (!string.Equals(connectionId, binding.Mapping.DataConnectionId, StringComparison.OrdinalIgnoreCase)) { ProjectedStreamDiagnostics.CountRenewalFailure("Item.OtherConnection"); continue; } + eligible.Add(new(index, mapping, binding, callerAllowed)); } - bool CallerAllowed() => demandActive() && (configured is not null - ? configured.Matches(mapping, previous.Metadata.View, binding.LocalAuthority) - : caller is not null && _policy.IsCallerUsable(caller) && - _policy.AuthorizeLocal(caller, authorizeAs, previous.Subject.Scope)); - if (!IsCurrent(binding) || !binding.LocalAuthority.IsActive || !CallerAllowed() || - previous.Metadata.View.MappingRevision != binding.Mapping.Revision || previous.Metadata.View.Realm != binding.Mapping.Realm || - previous.OriginMetadata.View.MappingId is not null || - previous.Subject.Scope.Kind != binding.LocalScope.Kind || - !string.Equals(previous.Subject.Scope.ClusterId, binding.LocalScope.ClusterId, StringComparison.OrdinalIgnoreCase) || - previous.Subject.Scope.Segments.Count < binding.LocalScope.Segments.Count || - !previous.Subject.Scope.Segments.Take(binding.LocalScope.Segments.Count).SequenceEqual(binding.LocalScope.Segments, StringComparer.Ordinal) || - !previous.Subject.LocalAncestry.SequenceEqual(binding.LocalAncestry, StringComparer.OrdinalIgnoreCase)) return Failed; + if (eligible.Count == 0 || connectionId is null) return results; // A subscription renewal never queues (it retries on its own cadence); an on-demand renewal waits for its own pool within // its budget, and the wait is charged to that budget. var slots = onDemand ? _onDemandSlots : _fetchSlots; var queued = System.Diagnostics.Stopwatch.GetTimestamp(); - if (!await slots.WaitAsync(onDemand ? budget.Timeout : TimeSpan.Zero, cancellationToken).ConfigureAwait(false)) return Failed; + if (!await slots.WaitAsync(onDemand ? budget.Timeout : TimeSpan.Zero, cancellationToken).ConfigureAwait(false)) + { + if (!onDemand) ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.RenewalSlots); + return results; + } if (onDemand) { var left = budget.Timeout - System.Diagnostics.Stopwatch.GetElapsedTime(queued); - if (left <= TimeSpan.Zero) { slots.Release(); return Failed; } + if (left <= TimeSpan.Zero) { slots.Release(); return results; } budget = budget with { Timeout = left }; } IGrpcDataAdapterConnectionLease? connection = null; @@ -375,9 +410,12 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp var started = Clock.GetTimestamp(); using var timeout = new CancellationTokenSource(budget.Timeout, Clock); using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeout.Token); - connection = await _source.AcquireAsync(binding.Mapping.DataConnectionId, linked.Token).ConfigureAwait(false); - if (connection is null || !ReferenceEquals(connection.Connection.Clock, Clock) || - !string.Equals(connection.Connection.Target.ExpectedClusterId, previous.OriginMetadata.View.Address.OriginClusterId, StringComparison.OrdinalIgnoreCase)) return Failed; + connection = await _source.AcquireAsync(connectionId, linked.Token).ConfigureAwait(false); + if (connection is null || !ReferenceEquals(connection.Connection.Clock, Clock)) { ProjectedStreamDiagnostics.CountRenewalFailure("Call.NoConnection", eligible.Count); return results; } + var expectedCluster = connection.Connection.Target.ExpectedClusterId; + eligible.RemoveAll(entry => !string.Equals(expectedCluster, items[entry.Index].Previous.OriginMetadata.View.Address.OriginClusterId, + StringComparison.OrdinalIgnoreCase)); + if (eligible.Count == 0) { ProjectedStreamDiagnostics.CountRenewalFailure("Call.ClusterMismatch", items.Count); return results; } using var route = CancellationTokenSource.CreateLinkedTokenSource(linked.Token, connection.CancellationToken); var capabilities = await connection.Connection.GetCapabilitiesAsync(budget, route.Token).ConfigureAwait(false); capabilities.Validate(); @@ -385,77 +423,53 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp var target = connection.Connection.Target; if (!capabilities.MetadataItemLeases || capabilities.Readiness != DataReadiness.Ready || serving.ServingGeneration <= 0 || !(string.Equals(serving.Role, "Primary", StringComparison.OrdinalIgnoreCase) || - target.Mode == DataTargetMode.Node && target.Consistency == DataConsistency.ReadyReplica && string.Equals(serving.Role, "Secondary", StringComparison.OrdinalIgnoreCase))) return Failed; + target.Mode == DataTargetMode.Node && target.Consistency == DataConsistency.ReadyReplica && string.Equals(serving.Role, "Secondary", StringComparison.OrdinalIgnoreCase))) { ProjectedStreamDiagnostics.CountRenewalFailure("Call.OriginNotReady", eligible.Count); return results; } // #939: a ready, authenticated origin that no longer grants this principal Metadata at all has refused the renewal. - if ((capabilities.Operations & DataOperations.Metadata) == 0) return Refused; - var elapsed = Clock.GetElapsedTime(started, Clock.GetTimestamp()); - if (elapsed < TimeSpan.Zero || elapsed >= budget.Timeout) return Failed; - var results = await connection.Connection.GetMetadataAsync(new([previous.OriginMetadata.View], - budget with { MaxItems = 1, Timeout = budget.Timeout - elapsed }), route.Token).ConfigureAwait(false); - elapsed = Clock.GetElapsedTime(started, Clock.GetTimestamp()); - if (elapsed < TimeSpan.Zero || elapsed >= budget.Timeout || linked.IsCancellationRequested) return Failed; - // #939: the origin's own verdict on this item — Denied, or a Good answer that no longer grants the operation — is a - // definitive refusal (the consumer answers BadUserAccessDenied), not a lapse to retry. #957: so is NotFound — an - // origin answers a node its ACL now hides from this peer (or one outside its grant, #943) exactly like a missing - // one, so for a node this consumer already projected it is the same verdict, not a lapse. - if (results.Count == 1 && results[0].CorrelationId == "0" && - (results[0].Status is DataItemStatus.Denied or DataItemStatus.NotFound || - results[0].Status == DataItemStatus.Good && results[0].Value is { } granted && granted.View == previous.OriginMetadata.View && - (binding.Mapping.AllowedOperations & required) == required && - ((granted.AllowedOperations & required) == 0 || required == DataOperations.Write && !granted.Writable))) - return Refused; - if (results.Count != 1 || results[0].CorrelationId != "0" || results[0].Status != DataItemStatus.Good || - results[0].Value is not { } metadata || results[0].Lease is not { } remoteLease || - metadata.View != previous.OriginMetadata.View || metadata.Serving != serving || metadata.CatalogRevision != serving.CatalogEpoch || - remoteLease.CatalogEpoch != serving.CatalogEpoch || remoteLease.AuthorityEpoch != serving.AuthorityEpoch || - remoteLease.Duration <= TimeSpan.Zero || remoteLease.Duration > capabilities.Limits.MaxMetadataLease || - metadata.BrowseName != previous.OriginMetadata.BrowseName || metadata.NodeKind != previous.OriginMetadata.NodeKind || - metadata.ValueKind != previous.OriginMetadata.ValueKind || metadata.ValueRank != previous.OriginMetadata.ValueRank || - metadata.ArrayElementKind != previous.OriginMetadata.ArrayElementKind || - !metadata.Dimensions.SequenceEqual(previous.OriginMetadata.Dimensions) || - (metadata.AllowedOperations & binding.Mapping.AllowedOperations & required) == 0 || - !IsCurrent(binding) || !CallerAllowed() || connection.CancellationToken.IsCancellationRequested) return Failed; - metadata.Validate(); remoteLease.Validate(); - var generation = _cache.CaptureGeneration(mapping); - var maximumLease = TimeSpan.FromMilliseconds(binding.Mapping.MetadataLeaseMilliseconds); - if (caller?.CredentialExpiresUtc is { } expiry) + if ((capabilities.Operations & DataOperations.Metadata) == 0) { - var remaining = expiry - Clock.GetUtcNow(); - if (remaining <= TimeSpan.Zero) return Failed; - if (remaining < maximumLease) maximumLease = remaining; + foreach (var entry in eligible) results[entry.Index] = Refused; + return results; } - var lease = new BoundProjectionLease(new MetadataAuthorityLease(serving, remoteLease, started, maximumLease, TimeSpan.Zero, Clock), - connection.CancellationToken, binding.LocalAuthority, _cache, mapping, generation, () => IsCurrent(binding), connection.RouteCurrent, - connection.RouteIdentity, connection.Connection.Target, binding); - var subject = previous.Subject with { Serving = serving, AllowedOperations = binding.Mapping.AllowedOperations & metadata.AllowedOperations, - WriteThrough = binding.Mapping.WriteThrough && metadata.Writable }; - var mapped = metadata with { View = previous.Metadata.View }; - var resolver = new MappedSubjectResolver([subject], serving.CatalogEpoch, binding.LocalAuthority); - var renewed = new ProjectedNodeProof(previous.LocalIdentifier, mapped, subject, resolver, lease, generation, metadata, - TimeSpan.FromMilliseconds(binding.Mapping.StaleTimeoutMilliseconds)); - var guard = new ExactAuthority(renewed); - if (!guard.IsCurrent() || caller is not null && !_policy.AuthorizeMapped(caller, authorizeAs, - mapped.View, serving, subject, resolver, lease)) return Failed; - var newDefinition = new ProjectedVariableDefinition(definition.Realm, definition.LocalIdentifier, definition.Parent, - mapped, generation, guard.IsCurrent) { Lifetime = definition.Lifetime, Historizing = ProjectedHistoryAccess.Advertises(renewed) }; - var committedRenewal = sink.TryRenewExact(nodeId, definition, newDefinition, () => + var answers = new DataItemResult[eligible.Count]; + var chunk = Math.Max(1, capabilities.Limits.MaxBatchItems); + for (var offset = 0; offset < eligible.Count; offset += chunk) { - var duration = Clock.GetElapsedTime(started, Clock.GetTimestamp()); - if (linked.IsCancellationRequested || cancellationToken.IsCancellationRequested || connection.CancellationToken.IsCancellationRequested || - duration < TimeSpan.Zero || duration >= budget.Timeout || - !IsCurrent(binding) || !CallerAllowed() || !guard.IsCurrent()) return false; - ProjectedNodeProof? actual; - var committed = overlap ? _cache.TryRenewOverlap(previous, renewed, binding.Mapping.MaxProjectionNodes, out actual) : - _cache.TryRenewExact(previous, renewed, binding.Mapping.MaxProjectionNodes, out actual); - if (!committed || actual is null) return false; - guard.Adopt(actual); - return guard.IsCurrent(); - }); - return committedRenewal ? ProjectedRenewalResult.Renewed : Failed; + var count = Math.Min(chunk, eligible.Count - offset); + var elapsed = Clock.GetElapsedTime(started, Clock.GetTimestamp()); + if (elapsed < TimeSpan.Zero || elapsed >= budget.Timeout) { ProjectedStreamDiagnostics.CountRenewalFailure("Call.TimeoutBeforeMetadata", eligible.Count); return results; } + var views = new DataView[count]; + for (var i = 0; i < count; i++) views[i] = items[eligible[offset + i].Index].Previous.OriginMetadata.View; + var page = await connection.Connection.GetMetadataAsync(new(views, + budget with { MaxItems = count, Timeout = budget.Timeout - elapsed }), route.Token).ConfigureAwait(false); + if (page.Count != count) { ProjectedStreamDiagnostics.CountRenewalFailure("Call.PageCount", eligible.Count); return results; } + for (var i = 0; i < count; i++) + { + if (page[i].CorrelationId != i.ToString(System.Globalization.CultureInfo.InvariantCulture)) { ProjectedStreamDiagnostics.CountRenewalFailure("Call.PageCorrelation", eligible.Count); return results; } + answers[offset + i] = page[i]; + } + } + var done = Clock.GetElapsedTime(started, Clock.GetTimestamp()); + if (done < TimeSpan.Zero || done >= budget.Timeout || linked.IsCancellationRequested) { ProjectedStreamDiagnostics.CountRenewalFailure("Call.TimeoutAfterMetadata", eligible.Count); return results; } + for (var k = 0; k < eligible.Count; k++) + { + try + { + results[eligible[k].Index] = CommitExact(items[eligible[k].Index], eligible[k], answers[k], capabilities, connection, + started, budget, linked, cancellationToken, sink, overlap, authorizeAs, required); + } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) + { results[eligible[k].Index] = Failed; ProjectedStreamDiagnostics.CountRenewalFailure("Item.CommitException"); } + } + return results; } // #939: the origin answered the call itself PERMISSION_DENIED (e.g. the operation is no longer granted to this // principal). The connection reports it as the cause of its "no ready endpoint" failure. - catch (Exception ex) when (ex is not OutOfMemoryException) { return IsOriginPermissionDenied(ex) ? Refused : Failed; } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + ProjectedStreamDiagnostics.CountRenewalFailure("Call." + ex.GetType().Name, eligible.Count); + if (IsOriginPermissionDenied(ex)) foreach (var entry in eligible) results[entry.Index] = Refused; + return results; + } finally { try { if (connection is not null) await connection.DisposeAsync().ConfigureAwait(false); } @@ -463,6 +477,90 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp finally { slots.Release(); } } } + + private sealed record Eligible(int Index, string Mapping, ProjectedMappingBinding Binding, Func CallerAllowed); + + private Func CallerAllowedFor(ExactRenewal item, string mapping, ProjectedMappingBinding binding, OpcUaOperation authorizeAs) => + () => item.DemandActive() && (item.Configured is not null + ? item.Configured.Matches(mapping, item.Previous.Metadata.View, binding.LocalAuthority) + : item.Caller is not null && _policy.IsCallerUsable(item.Caller) && + _policy.AuthorizeLocal(item.Caller, authorizeAs, item.Previous.Subject.Scope)); + + /// #1026: one item's verdict on its origin answer and its commit — unchanged from the one-item renewal. + private ProjectedRenewalResult CommitExact(ExactRenewal item, Eligible entry, DataItemResult answer, DataCapabilities capabilities, + IGrpcDataAdapterConnectionLease connection, long started, DataBudget budget, CancellationTokenSource linked, + CancellationToken cancellationToken, IProjectedNamespacePageSink sink, bool overlap, OpcUaOperation authorizeAs, DataOperations required) + { + const ProjectedRenewalResult Failed = ProjectedRenewalResult.Failed; + var previous = item.Previous; + var binding = entry.Binding; + var mapping = entry.Mapping; + var serving = capabilities.Serving; + // #939: the origin's own verdict on this item — Denied, or a Good answer that no longer grants the operation — is a + // definitive refusal (the consumer answers BadUserAccessDenied), not a lapse to retry. #957: so is NotFound — an + // origin answers a node its ACL now hides from this peer (or one outside its grant, #943) exactly like a missing + // one, so for a node this consumer already projected it is the same verdict, not a lapse. + if (answer.Status is DataItemStatus.Denied or DataItemStatus.NotFound || + answer.Status == DataItemStatus.Good && answer.Value is { } granted && granted.View == previous.OriginMetadata.View && + (binding.Mapping.AllowedOperations & required) == required && + ((granted.AllowedOperations & required) == 0 || required == DataOperations.Write && !granted.Writable)) + { ProjectedStreamDiagnostics.CountRenewalFailure("Item.Refused"); return ProjectedRenewalResult.Refused; } + if (answer.Status != DataItemStatus.Good) { ProjectedStreamDiagnostics.CountRenewalFailure("Item.Status." + answer.Status); return Failed; } + if (answer.Status != DataItemStatus.Good || + answer.Value is not { } metadata || answer.Lease is not { } remoteLease || + metadata.View != previous.OriginMetadata.View || metadata.Serving != serving || metadata.CatalogRevision != serving.CatalogEpoch || + remoteLease.CatalogEpoch != serving.CatalogEpoch || remoteLease.AuthorityEpoch != serving.AuthorityEpoch || + remoteLease.Duration <= TimeSpan.Zero || remoteLease.Duration > capabilities.Limits.MaxMetadataLease || + metadata.BrowseName != previous.OriginMetadata.BrowseName || metadata.NodeKind != previous.OriginMetadata.NodeKind || + metadata.ValueKind != previous.OriginMetadata.ValueKind || metadata.ValueRank != previous.OriginMetadata.ValueRank || + metadata.ArrayElementKind != previous.OriginMetadata.ArrayElementKind || + !metadata.Dimensions.SequenceEqual(previous.OriginMetadata.Dimensions) || + (metadata.AllowedOperations & binding.Mapping.AllowedOperations & required) == 0 || + !IsCurrent(binding) || !entry.CallerAllowed() || connection.CancellationToken.IsCancellationRequested) + { ProjectedStreamDiagnostics.CountRenewalFailure("Item.AnswerMismatch"); return Failed; } + metadata.Validate(); remoteLease.Validate(); + var generation = _cache.CaptureGeneration(mapping); + var maximumLease = TimeSpan.FromMilliseconds(binding.Mapping.MetadataLeaseMilliseconds); + if (item.Caller?.CredentialExpiresUtc is { } expiry) + { + var remaining = expiry - Clock.GetUtcNow(); + if (remaining <= TimeSpan.Zero) return Failed; + if (remaining < maximumLease) maximumLease = remaining; + } + var lease = new BoundProjectionLease(new MetadataAuthorityLease(serving, remoteLease, started, maximumLease, TimeSpan.Zero, Clock), + connection.CancellationToken, binding.LocalAuthority, _cache, mapping, generation, () => IsCurrent(binding), connection.RouteCurrent, + connection.RouteIdentity, connection.Connection.Target, binding); + var subject = previous.Subject with { Serving = serving, AllowedOperations = binding.Mapping.AllowedOperations & metadata.AllowedOperations, + WriteThrough = binding.Mapping.WriteThrough && metadata.Writable }; + var mapped = metadata with { View = previous.Metadata.View }; + var resolver = new MappedSubjectResolver([subject], serving.CatalogEpoch, binding.LocalAuthority); + var renewed = new ProjectedNodeProof(previous.LocalIdentifier, mapped, subject, resolver, lease, generation, metadata, + TimeSpan.FromMilliseconds(binding.Mapping.StaleTimeoutMilliseconds)); + var guard = new ExactAuthority(renewed); + if (!guard.IsCurrent() || item.Caller is not null && !_policy.AuthorizeMapped(item.Caller, authorizeAs, + mapped.View, serving, subject, resolver, lease)) { ProjectedStreamDiagnostics.CountRenewalFailure("Item.Authorize"); return Failed; } + var definition = item.Definition; + var newDefinition = new ProjectedVariableDefinition(definition.Realm, definition.LocalIdentifier, definition.Parent, + mapped, generation, guard.IsCurrent) { Lifetime = definition.Lifetime, Historizing = ProjectedHistoryAccess.Advertises(renewed) }; + var reached = false; + var committedRenewal = sink.TryRenewExact(item.NodeId, definition, newDefinition, () => + { + reached = true; + var duration = Clock.GetElapsedTime(started, Clock.GetTimestamp()); + if (linked.IsCancellationRequested || cancellationToken.IsCancellationRequested || connection.CancellationToken.IsCancellationRequested) + { ProjectedStreamDiagnostics.CountRenewalFailure("Commit.Canceled"); return false; } + if (duration < TimeSpan.Zero || duration >= budget.Timeout) { ProjectedStreamDiagnostics.CountRenewalFailure("Commit.Deadline"); return false; } + if (!IsCurrent(binding) || !entry.CallerAllowed() || !guard.IsCurrent()) { ProjectedStreamDiagnostics.CountRenewalFailure("Commit.Fence"); return false; } + ProjectedNodeProof? actual; + var committed = overlap ? _cache.TryRenewOverlap(previous, renewed, binding.Mapping.MaxProjectionNodes, out actual) : + _cache.TryRenewExact(previous, renewed, binding.Mapping.MaxProjectionNodes, out actual); + if (!committed || actual is null) { ProjectedStreamDiagnostics.CountRenewalFailure("Commit.Cache"); return false; } + guard.Adopt(actual); + return guard.IsCurrent(); + }); + if (!committedRenewal) ProjectedStreamDiagnostics.CountRenewalFailure(reached ? "Item.Commit" : "Item.CommitSink"); + return committedRenewal ? ProjectedRenewalResult.Renewed : Failed; + } internal static bool IsOriginPermissionDenied(Exception? ex) { for (var depth = 0; ex is not null && depth < 8; ex = ex.InnerException, depth++) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SamplePartition.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SamplePartition.cs index 19cfb04eb..a468ce1d8 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SamplePartition.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SamplePartition.cs @@ -134,11 +134,15 @@ internal sealed class SamplePartition : IDisposable state.AppliedInvalidations = signal; } } - private void Signal(SourceTicket ticket, bool retired = false) + private void Signal(SourceTicket ticket, SourceInvalidationReason reason, bool retired = false) { if (!_sources.TryGetValue(ticket.Key, out var state)) return; var gate = Volatile.Read(ref state.Gate); if (gate.Generation != ticket.Generation || !ReferenceEquals(gate.Binding, ticket.Binding)) return; + // #1026: the reason is recorded before the quiet bump, so a lease that sees this source's quiet version move can name it. + Volatile.Write(ref state.LastInvalidation, (int)reason); + SourceIngressDiagnostics.CountInvalidation(reason); + _hub.LogInvalidation(ticket.Key, reason, retired); Control.BeginQuiet(); try { @@ -199,10 +203,10 @@ internal sealed class SamplePartition : IDisposable { ReleaseMetadataOwner(state); return false; } if (estimated <= 0 || estimated > long.MaxValue - PartitionedSampleHub.SampleOverhead || !TryIncrementBounded(ref _reservations, (int)Math.Min(int.MaxValue, (long)_hub.Limits.MaxIngressItemsPerPartition + _hub.Limits.MaxDirtySourcesPerPartition))) - { ReleaseMetadataOwner(state); SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.ReserveCapacity); Signal(ticket); return false; } + { ReleaseMetadataOwner(state); SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.ReserveCapacity); Signal(ticket, SourceInvalidationReason.ReserveCapacity); return false; } var charge = estimated + PartitionedSampleHub.SampleOverhead; if (!_hub.Resources.TryReserve(charge)) - { Interlocked.Decrement(ref _reservations); ReleaseMetadataOwner(state); SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.ReserveCapacity); Signal(ticket); return false; } + { Interlocked.Decrement(ref _reservations); ReleaseMetadataOwner(state); SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.ReserveCapacity); Signal(ticket, SourceInvalidationReason.ReserveCapacity); return false; } Interlocked.Increment(ref state.Reservations); if (!IsTicketCurrentNonBlocking(ticket) || !ReferenceEquals(gate, Volatile.Read(ref state.Gate)) || Interlocked.Read(ref _epoch) != epoch || Interlocked.Read(ref gate.ProducerStamp) != stamp || Interlocked.Read(ref gate.Invalidated) != signal) @@ -216,7 +220,7 @@ internal sealed class SamplePartition : IDisposable if (!TryEnterProducer()) { ReleaseReservation(state); _hub.Resources.Release(charge); return false; } if (Interlocked.CompareExchange(ref gate.Committing, 1, 0) != 0) { - ReleaseReservation(state); _hub.Resources.Release(charge); Signal(ticket); ExitProducer(); return false; + ReleaseReservation(state); _hub.Resources.Release(charge); Signal(ticket, SourceInvalidationReason.CommitCollision); ExitProducer(); return false; } try { return CommitEntered(state, gate, ticket, estimate, charge, stamp, signal, partitionEpoch, receivedTimestamp, sample, sequence); } finally { Volatile.Write(ref gate.Committing, 0); ExitProducer(); } @@ -234,12 +238,12 @@ internal sealed class SamplePartition : IDisposable throw new ArgumentException("Invalid ingress sample."); } catch (Exception e) when (e is ArgumentException or ObjectDisposedException or OverflowException) - { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.CommitInvalid); ReleaseReservation(state); _hub.Resources.Release(charge); Signal(ticket); return false; } + { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.CommitInvalid); ReleaseReservation(state); _hub.Resources.Release(charge); Signal(ticket, SourceInvalidationReason.CommitInvalid); return false; } if (!IsTicketCurrentNonBlocking(ticket) || !ReferenceEquals(gate, Volatile.Read(ref state.Gate)) || partitionEpoch != Interlocked.Read(ref _epoch) || stamp != Interlocked.Read(ref gate.ProducerStamp) || signal != Interlocked.Read(ref gate.Invalidated)) { ReleaseReservation(state); _hub.Resources.Release(charge); return false; } if (!TryAdvance(gate, sequence)) - { ReleaseReservation(state); _hub.Resources.Release(charge); Signal(ticket); return false; } + { ReleaseReservation(state); _hub.Resources.Release(charge); Signal(ticket, SourceInvalidationReason.SequenceRegression); return false; } _hub.AfterValueSequenceForTests?.Invoke(); var pending = new Pending(ticket, sequence, Interlocked.Increment(ref _ordinal), sample, charge, receivedTimestamp) { PartitionEpoch = partitionEpoch, Owner = state, Gate = gate, ProducerStamp = stamp, SignalStamp = signal }; @@ -248,7 +252,7 @@ internal sealed class SamplePartition : IDisposable { ReleaseReservation(state); _hub.Resources.Release(charge); if (admitted == EnqueueResult.Capacity) InvalidatePartition(); - else Signal(ticket); + else Signal(ticket, SourceInvalidationReason.EnqueueStale); return false; } // The mailbox owns the metadata pin; the in-flight copy permit ends at transfer. @@ -305,9 +309,10 @@ internal sealed class SamplePartition : IDisposable if (lastReservation && Volatile.Read(ref state.Gate.Retired) != 0 && !Volatile.Read(ref _disposed)) RequestReclaim(); } private void Abandon(SourceState state, long charge) { ReleaseReservation(state); _hub.Resources.Release(charge); } - internal void Invalidate(SourceTicket ticket) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.ExternalInvalidate); Signal(ticket); } - private void InvalidateSource(SourceState state) + internal void Invalidate(SourceTicket ticket, SourceInvalidationReason reason) { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.ExternalInvalidate); Signal(ticket, reason); } + private void InvalidateSource(SourceState state, SourceInvalidationReason? reason = null) { + if (reason is { } recorded) Volatile.Write(ref state.LastInvalidation, (int)recorded); Control.BeginQuiet(); try { state.Readiness = DataReadiness.Invalidated; Interlocked.Increment(ref state.InvalidationVersion); Interlocked.Increment(ref state.QuietVersion); ReleaseCache(state); } finally { Control.EndQuiet(); } @@ -315,7 +320,7 @@ internal sealed class SamplePartition : IDisposable internal bool TryStatus(SourceTicket ticket, long sequence, uint status, DateTimeOffset? source, DateTimeOffset? server) { - if (!Monitor.TryEnter(_gate)) { Signal(ticket); return false; } + if (!Monitor.TryEnter(_gate)) { Signal(ticket, SourceInvalidationReason.PartitionStatusContention); return false; } try { var partitionEpoch = Interlocked.Read(ref _epoch); @@ -332,7 +337,7 @@ internal sealed class SamplePartition : IDisposable } internal bool TryRemove(SourceTicket ticket, long sequence) { - if (!Monitor.TryEnter(_gate)) { Signal(ticket, retired: true); return false; } + if (!Monitor.TryEnter(_gate)) { Signal(ticket, SourceInvalidationReason.PartitionRemovalContention, retired: true); return false; } try { // Retirement must still be able to release a source after its shared fence closed. @@ -344,6 +349,7 @@ internal sealed class SamplePartition : IDisposable { if (_queuedControls >= _hub.Limits.MaxControlItemsPerPartition || !_hub.Resources.TryReserve(ControlOverhead)) { state.Removed = true; ticket.Binding!.Retire(); Interlocked.Exchange(ref state.Gate.Retired, 1); RequestReclaim(); InvalidatePartition(); return false; } + Volatile.Write(ref state.LastInvalidation, (int)SourceInvalidationReason.Retired); state.Removed = true; ticket.Binding!.Retire(); Interlocked.Exchange(ref state.Gate.Retired, 1); state.Readiness = DataReadiness.Invalidated; Interlocked.Increment(ref state.InvalidationVersion); Interlocked.Increment(ref state.Gate.ProducerStamp); Interlocked.Increment(ref state.QuietVersion); ReleaseCache(state); } finally { Control.EndQuiet(); } @@ -466,7 +472,7 @@ internal sealed class SamplePartition : IDisposable private void ApplyPartitionEpoch(SourceState state) { if (state.PartitionEpoch == _epoch) return; - InvalidateSource(state); + InvalidateSource(state, SourceInvalidationReason.PartitionInvalidated); state.PartitionEpoch = _epoch; } private void CleanupInvalidatedEpoch() @@ -487,7 +493,7 @@ internal sealed class SamplePartition : IDisposable if (Volatile.Read(ref state.Gate.Retired) == 0) continue; ApplyGate(state); state.Removed = true; - InvalidateSource(state); + InvalidateSource(state, SourceInvalidationReason.Retired); RequestReclaim(); } } @@ -617,6 +623,8 @@ internal sealed class SamplePartition : IDisposable internal void ReleaseInterest(object source) => ReleaseMetadataOwner((SourceState)source); /// #994 (R-9): the source's quiet version (see ); lock-free. internal static long QuietVersionOf(object source) => Interlocked.Read(ref ((SourceState)source).QuietVersion); + /// #1026: the reason of the source's latest signalled invalidation ( if none). + internal static SourceInvalidationReason LastInvalidationOf(object source) => (SourceInvalidationReason)Volatile.Read(ref ((SourceState)source).LastInvalidation); internal bool ReadInterestChanges(long epoch, ref long position, IReadOnlyDictionary tickets, int maximum, List changes, out int scanned) => @@ -665,6 +673,8 @@ internal sealed class SamplePartition : IDisposable return true; } } + /// #1026: whether this partition is still on (lock-free; for naming a lease reset). + internal bool IsEpochCurrentNonBlocking(long epoch) => !Volatile.Read(ref _disposed) && Interlocked.Read(ref _epoch) == epoch; internal void ReleaseSnapshot(object source) { var state = (SourceState)source; @@ -749,6 +759,8 @@ internal sealed class SamplePartition : IDisposable /// so an interest lease can tell its own sources' invalidation from a sibling's partition-wide quiet bump. /// public long QuietVersion; + /// #1026: the of this source's latest signalled invalidation. + public int LastInvalidation; } private sealed class Pending { diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SourceIngressDiagnostics.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SourceIngressDiagnostics.cs index ae5ec0630..4ddb384ee 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SourceIngressDiagnostics.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SourceIngressDiagnostics.cs @@ -1,12 +1,115 @@ +using System.Diagnostics.Metrics; +using ZB.MOM.WW.OtOpcUa.Commons.Observability; + namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; /// Bounded aggregate observations of origin source admission and retained history. +/// +/// #1026: every source invalidation that actually lands on a current source generation is also counted by its +/// — in as Invalidate.<Reason> and on +/// tagged reason (the enum name; never a source id). Before, every cause +/// (lock contention, a rejected commit, status ordering, serving identity…) looked the same, and the stream it reset said +/// "Source change history expired.". +/// public static class SourceIngressDiagnostics { + public const string InvalidationsCounterName = "otopcua.dataconn.source.invalidations"; + internal enum Event { ReserveLock, CommitLock, ReserveCapacity, CommitInvalid, PartitionInvalidated, ExternalInvalidate, ReadNotReady, ReadInvalidated, ReadExhausted, InterestReset, InterestQuiet, InterestEpoch, InterestHistoryGap, InterestTicket } private static readonly long[] Counts = new long[Enum.GetValues().Length]; + private static readonly long[] Invalidations = new long[Enum.GetValues().Length]; + private static readonly Counter InvalidationsCounter = OtOpcUaTelemetry.Meter.CreateCounter(InvalidationsCounterName, + unit: "{invalidation}", description: "Origin source generations invalidated (the stream items on them re-snapshot), by reason."); internal static void Count(Event value) => Interlocked.Increment(ref Counts[(int)value]); + internal static void CountInvalidation(SourceInvalidationReason reason) + { + Interlocked.Increment(ref Invalidations[(int)reason]); + InvalidationsCounter.Add(1, new KeyValuePair("reason", reason.ToString())); + } /// Captures process-wide counters without source identifiers or payloads. - public static IReadOnlyDictionary Capture() => Enum.GetValues().ToDictionary(x => x.ToString(), x => Interlocked.Read(ref Counts[(int)x])); + public static IReadOnlyDictionary Capture() + { + var result = Enum.GetValues().ToDictionary(x => x.ToString(), x => Interlocked.Read(ref Counts[(int)x])); + foreach (var reason in Enum.GetValues()) + result["Invalidate." + reason] = Interlocked.Read(ref Invalidations[(int)reason]); + return result; + } +} + +/// #1026: why an origin source generation was invalidated (bounded; a metric tag and a log field). +public enum SourceInvalidationReason +{ + /// A caller-supplied reason this build does not name. + Other, + // SourceSamplePublisher + BindingContention, RebindUnavailable, IngressCapacity, SerializationContention, ServingIdentityUnavailable, CommitRejected, + UnsupportedSample, StagedContention, StagedIdentityUnavailable, StagedAdmissionRejected, StagedCommitFailed, + StagedIngressCapacity, StagedValueInvalid, StatusContention, StatusOvertookInFlight, StatusAdmissionFailed, + StatusSequenceExhausted, StatusFenceFailed, StatusFenceOvertook, StatusCapacity, RemovalCapacity, + // DriverInstanceActor + LegacyStagingOverflow, MalformedCallback, CallbackFailed, + // SamplePartition (internal admission) + PartitionStatusContention, PartitionRemovalContention, ReserveCapacity, CommitInvalid, CommitCollision, + SequenceRegression, EnqueueStale, + // Recorded on the source only (never counted here): the partition epoch moved, or the binding was retired. + PartitionInvalidated, Retired, +} + +/// #1026: the reason strings production callers pass to , and their classification. +public static class SourceInvalidationReasons +{ + public const string BindingContention = "source binding contention"; + public const string RebindUnavailable = "source rebind unavailable"; + public const string IngressCapacity = "source ingress capacity"; + public const string SerializationContention = "source serialization contention"; + public const string ServingIdentityUnavailable = "serving identity unavailable"; + public const string CommitRejected = "source commit rejected"; + public const string UnsupportedSample = "unsupported or oversized source sample"; + public const string StagedContention = "staged source contention"; + public const string StagedIdentityUnavailable = "staged source identity unavailable"; + public const string StagedAdmissionRejected = "staged source admission rejected"; + public const string StagedCommitFailed = "staged source commit failed"; + public const string StagedIngressCapacity = "staged source ingress capacity"; + public const string StagedValueInvalid = "staged source value invalid"; + public const string StatusContention = "source status contention"; + public const string StatusOvertookInFlight = "source status overtook in-flight sample"; + public const string StatusAdmissionFailed = "source status admission failed"; + public const string StatusSequenceExhausted = "source status sequence exhausted"; + public const string StatusFenceFailed = "source status fence failed"; + public const string StatusFenceOvertook = "status overtook in-flight source sample"; + public const string StatusCapacity = "source status capacity"; + public const string RemovalCapacity = "source removal capacity"; + public const string LegacyStagingOverflow = "legacy callback staging overflow"; + public const string MalformedCallback = "malformed driver callback"; + public const string CallbackFailed = "source callback failed"; + + public static SourceInvalidationReason Classify(string? reason) => reason switch + { + BindingContention => SourceInvalidationReason.BindingContention, + RebindUnavailable => SourceInvalidationReason.RebindUnavailable, + IngressCapacity => SourceInvalidationReason.IngressCapacity, + SerializationContention => SourceInvalidationReason.SerializationContention, + ServingIdentityUnavailable => SourceInvalidationReason.ServingIdentityUnavailable, + CommitRejected => SourceInvalidationReason.CommitRejected, + UnsupportedSample => SourceInvalidationReason.UnsupportedSample, + StagedContention => SourceInvalidationReason.StagedContention, + StagedIdentityUnavailable => SourceInvalidationReason.StagedIdentityUnavailable, + StagedAdmissionRejected => SourceInvalidationReason.StagedAdmissionRejected, + StagedCommitFailed => SourceInvalidationReason.StagedCommitFailed, + StagedIngressCapacity => SourceInvalidationReason.StagedIngressCapacity, + StagedValueInvalid => SourceInvalidationReason.StagedValueInvalid, + StatusContention => SourceInvalidationReason.StatusContention, + StatusOvertookInFlight => SourceInvalidationReason.StatusOvertookInFlight, + StatusAdmissionFailed => SourceInvalidationReason.StatusAdmissionFailed, + StatusSequenceExhausted => SourceInvalidationReason.StatusSequenceExhausted, + StatusFenceFailed => SourceInvalidationReason.StatusFenceFailed, + StatusFenceOvertook => SourceInvalidationReason.StatusFenceOvertook, + StatusCapacity => SourceInvalidationReason.StatusCapacity, + RemovalCapacity => SourceInvalidationReason.RemovalCapacity, + LegacyStagingOverflow => SourceInvalidationReason.LegacyStagingOverflow, + MalformedCallback => SourceInvalidationReason.MalformedCallback, + CallbackFailed => SourceInvalidationReason.CallbackFailed, + _ => SourceInvalidationReason.Other + }; } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SourceInterestLease.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SourceInterestLease.cs index 6191bbee6..8b29310ba 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SourceInterestLease.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SourceInterestLease.cs @@ -25,6 +25,8 @@ public sealed class SourceInterestLease : IDisposable private long _charge; private CancellationTokenRegistration _cancellation; private int _released, _next; + private InterestResetReason _resetReason; + private SourceInvalidationReason _resetSource; internal SourceInterestLease(PartitionedSampleHub hub, Dictionary owners, @@ -58,6 +60,16 @@ public sealed class SourceInterestLease : IDisposable get { lock (_gate) return IsResetLocked(); } } + /// #1026: why this lease reset (or was released); while it is live. + public InterestResetReason ResetReason { get { lock (_gate) return _resetReason; } } + /// #1026: for , the own source's invalidation reason. + public SourceInvalidationReason ResetSourceReason { get { lock (_gate) return _resetSource; } } + private void NoteReset(InterestResetReason reason, SourceInvalidationReason source = SourceInvalidationReason.Other) + { + if (_resetReason != InterestResetReason.None) return; + _resetReason = reason; _resetSource = source; + } + /// /// #994 (R-9): a partition's quiet stamp moves for ANY source's invalidation (including ordinary lock contention on a /// sibling). It resets this lease only when one of its OWN sources was invalidated (its quiet version moved) or its @@ -66,7 +78,8 @@ public sealed class SourceInterestLease : IDisposable /// private bool IsResetLocked() { - if (_released != 0 || _hub.IsDisposed || _hub.RoutingEpoch != _routingEpoch) return true; + if (_released != 0) { NoteReset(InterestResetReason.Released); return true; } + if (_hub.IsDisposed || _hub.RoutingEpoch != _routingEpoch) { NoteReset(InterestResetReason.RoutingEpoch); return true; } foreach (var cursor in _cursors) { var quiet = cursor.Partition.Control.Quiet; @@ -76,11 +89,18 @@ public sealed class SourceInterestLease : IDisposable { if (!_owners.TryGetValue(ticket, out var owner) || !_quietVersions.TryGetValue(ticket, out var captured) || SamplePartition.QuietVersionOf(owner.Source) != captured || !cursor.Partition.IsTicketCurrentNonBlocking(ticket)) - { SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.InterestQuiet); return true; } + { + SourceIngressDiagnostics.Count(SourceIngressDiagnostics.Event.InterestQuiet); + if (!cursor.Partition.IsEpochCurrentNonBlocking(cursor.Epoch)) NoteReset(InterestResetReason.PartitionEpoch); + else NoteReset(InterestResetReason.SourceInvalidated, + owner.Source is null ? SourceInvalidationReason.Other : SamplePartition.LastInvalidationOf(owner.Source)); + return true; + } } cursor.QuietControl = now; } - return _hub.IsDisposed || _hub.RoutingEpoch != _routingEpoch; + if (_hub.IsDisposed || _hub.RoutingEpoch != _routingEpoch) { NoteReset(InterestResetReason.RoutingEpoch); return true; } + return false; } /// Scans at most maximum retained partition changes, returning false on a gap or epoch reset. @@ -120,7 +140,10 @@ public sealed class SourceInterestLease : IDisposable if (scanned >= maximumScanned || matched >= maximumMatches) { more = true; break; } if (!cursor.Partition.ReadInterestChanges(cursor.Epoch, ref cursor.Position, cursor.Tickets, maximumMatches - matched, maximumScanned - scanned, into, out var used, out var behind)) - { Release(); into.RemoveRange(start, into.Count - start); return false; } + { + NoteReset(cursor.Partition.IsEpochCurrentNonBlocking(cursor.Epoch) ? InterestResetReason.SourceNotCurrent : InterestResetReason.PartitionEpoch); + Release(); into.RemoveRange(start, into.Count - start); return false; + } scanned += used; more |= behind; } if (IsResetLocked()) @@ -145,3 +168,19 @@ public sealed class SourceInterestLease : IDisposable } public void Dispose() { lock (_gate) Release(); } } + +/// #1026: why an origin interest lease stopped (each maps to its own stream reset text). +public enum InterestResetReason +{ + None, + /// The lease was disposed (its stream/item cancelled or released it) before the read. + Released, + /// The hub was disposed or repartitioned. + RoutingEpoch, + /// A partition-wide invalidation moved the partition epoch. + PartitionEpoch, + /// One of the lease's own sources was invalidated (see ). + SourceInvalidated, + /// An own source's binding was replaced, removed or retired. + SourceNotCurrent, +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SourceSamplePublisher.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SourceSamplePublisher.cs index d029d5601..03f445993 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SourceSamplePublisher.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SourceSamplePublisher.cs @@ -211,11 +211,21 @@ public sealed class SourceSamplePublisher if (serving is null || string.IsNullOrWhiteSpace(cluster)) return false; var key = SourceKey.ForDriver(cluster, driver, reference, serving.NodeId, serving.Incarnation); if (!_slots.TryGetValue(key, out var slot)) return EnsureBinding(key, incarnation); + // #1026: already bound to this producer and current in the hub — exactly EnsureBinding's no-op answer, decided + // without the source's serialization gate. The driver actor's binding retry re-walks EVERY desired reference + // (offset 0, backing off to 30 s, forever once any one failed), and each walk used to take each bound source's + // gate. Under a 2048-source acquisition that collided with the poll thread's TryPublish holding the same gate, + // and BOTH sides invalidate on contention (binding contention here, serialization contention there), so a live, + // correctly bound source was invalidated and every origin stream holding it was reset — every retry pass. + var bound = Volatile.Read(ref slot.Current); + if (bound is not null && ReferenceEquals(bound.Producer, producer) && bound.Active && + bound.Ticket.Generation.Incarnation == incarnation && _tickets.TryGetValue(key, out var recorded) && + recorded == bound.Ticket && _hub.IsTicketCurrentNonBlocking(bound.Ticket)) return true; if (!Monitor.TryEnter(slot.Gate)) { var binding = Volatile.Read(ref slot.Current); if (binding?.Producer is { } current && ReferenceEquals(current, producer) && !current.IsRetired) - _hub.Invalidate(binding.Ticket, "source binding contention"); + _hub.Invalidate(binding.Ticket, SourceInvalidationReasons.BindingContention); return false; } try { return EnsureBinding(key, incarnation); } @@ -289,7 +299,7 @@ public sealed class SourceSamplePublisher if (existing.Generation.Incarnation == incarnation) { try { Bind(key, existing.Generation with { Lifecycle = checked(existing.Generation.Lifecycle + 1) }); return true; } - catch (InvalidOperationException) { _hub.Invalidate(existing, "source rebind unavailable"); return false; } + catch (InvalidOperationException) { _hub.Invalidate(existing, SourceInvalidationReasons.RebindUnavailable); return false; } } // A failed removal has already retired/fenced the old generation in the hub. TryRemove(existing); @@ -334,27 +344,27 @@ public sealed class SourceSamplePublisher var size = OwnedDataSample.Estimate(snapshot.Value, binding.Shape); if (!_hub.TryReserveIngress(ticket, size, out reservation) || reservation is null) { - _hub.Invalidate(ticket, "source ingress capacity"); + _hub.Invalidate(ticket, SourceInvalidationReasons.IngressCapacity); if (!_hub.IsTicketCurrentNonBlocking(ticket)) ScheduleRepair(slot, ticket); return false; } value = OwnedDataSample.Copy(snapshot.Value, binding.Shape); if (!Monitor.TryEnter(slot.Gate)) - { _hub.Invalidate(ticket, "source serialization contention"); return false; } + { _hub.Invalidate(ticket, SourceInvalidationReasons.SerializationContention); return false; } try { if (!binding.Active || !ReferenceEquals(Volatile.Read(ref slot.Current), binding)) return false; var serving = _serving(); if (serving is null || serving.NodeId != ticket.Key.ServingNodeId || serving.Incarnation != ticket.Key.ServingIncarnation || string.IsNullOrWhiteSpace(serving.Role) || serving.CatalogEpoch < 0 || serving.AuthorityEpoch < 0) - { _hub.Invalidate(ticket, "serving identity unavailable"); return false; } + { _hub.Invalidate(ticket, SourceInvalidationReasons.ServingIdentityUnavailable); return false; } var sequence = checked(++slot.Sequence); sample = new DataSample(value, snapshot.StatusCode, OwnedDataSample.Timestamp(snapshot.SourceTimestampUtc), OwnedDataSample.Timestamp(snapshot.ServerTimestampUtc), serving, sequence); value = null; if (!reservation.TryCommit(sample, sequence)) { - _hub.Invalidate(ticket, "source commit rejected"); + _hub.Invalidate(ticket, SourceInvalidationReasons.CommitRejected); if (!_hub.IsTicketCurrentNonBlocking(ticket)) ScheduleRepair(slot, ticket); return false; } @@ -364,7 +374,7 @@ public sealed class SourceSamplePublisher finally { Monitor.Exit(slot.Gate); } } catch (Exception ex) when (ex is ArgumentException or OverflowException or InvalidOperationException) - { _hub.Invalidate(ticket, "unsupported or oversized source sample"); return false; } + { _hub.Invalidate(ticket, SourceInvalidationReasons.UnsupportedSample); return false; } finally { value?.Dispose(); @@ -404,26 +414,26 @@ public sealed class SourceSamplePublisher try { var slot = _binding.Slot; - if (!Monitor.TryEnter(slot.Gate)) { _owner._hub.Invalidate(_ticket, "staged source contention"); return false; } + if (!Monitor.TryEnter(slot.Gate)) { _owner._hub.Invalidate(_ticket, SourceInvalidationReasons.StagedContention); return false; } try { if (!_binding.Active || !ReferenceEquals(Volatile.Read(ref slot.Current), _binding)) return false; var serving = _owner._serving(); if (serving is null || serving.NodeId != _ticket.Key.ServingNodeId || serving.Incarnation != _ticket.Key.ServingIncarnation || string.IsNullOrWhiteSpace(serving.Role)) - { _owner._hub.Invalidate(_ticket, "staged source identity unavailable"); return false; } + { _owner._hub.Invalidate(_ticket, SourceInvalidationReasons.StagedIdentityUnavailable); return false; } var sequence = checked(++slot.Sequence); sample = new DataSample(value, _status, _source, _server, serving, sequence); value = null!; if (!reservation.TryCommit(sample, sequence)) - { _owner._hub.Invalidate(_ticket, "staged source admission rejected"); return false; } + { _owner._hub.Invalidate(_ticket, SourceInvalidationReasons.StagedAdmissionRejected); return false; } sample = null; return true; } finally { Monitor.Exit(slot.Gate); } } catch (Exception ex) when (ex is ArgumentException or OverflowException or InvalidOperationException) - { _owner._hub.Invalidate(_ticket, "staged source commit failed"); return false; } + { _owner._hub.Invalidate(_ticket, SourceInvalidationReasons.StagedCommitFailed); return false; } finally { value?.Dispose(); sample?.Dispose(); reservation.Dispose(); @@ -455,14 +465,14 @@ public sealed class SourceSamplePublisher if (!binding.Active || !ReferenceEquals(Volatile.Read(ref slot.Current), binding)) return false; var size = OwnedDataSample.Estimate(snapshot.Value, binding.Shape); if (!_hub.TryReserveIngress(ticket, size, out reservation) || reservation is null) - { _hub.Invalidate(ticket, "staged source ingress capacity"); return false; } + { _hub.Invalidate(ticket, SourceInvalidationReasons.StagedIngressCapacity); return false; } value = OwnedDataSample.Copy(snapshot.Value, binding.Shape); staged = new StagedSourceSample(this, binding, ticket, snapshot, reservation, value); reservation = null; value = null; return true; } catch (Exception ex) when (ex is ArgumentException or OverflowException or InvalidOperationException) - { _hub.Invalidate(ticket, "staged source value invalid"); return false; } + { _hub.Invalidate(ticket, SourceInvalidationReasons.StagedValueInvalid); return false; } finally { if (staged is null) { value?.Dispose(); reservation?.Dispose(); Interlocked.Decrement(ref binding.InFlight); } @@ -475,7 +485,7 @@ public sealed class SourceSamplePublisher if (!_slots.TryGetValue(ticket.Key, out var slot)) return false; if (!Monitor.TryEnter(slot.Gate)) { - _hub.Invalidate(ticket, "source status contention"); + _hub.Invalidate(ticket, SourceInvalidationReasons.StatusContention); return false; } try @@ -484,16 +494,16 @@ public sealed class SourceSamplePublisher if (binding is null || binding.Ticket != ticket || !binding.Active) return false; if (Volatile.Read(ref binding.InFlight) != 0) { - _hub.Invalidate(ticket, "source status overtook in-flight sample"); + _hub.Invalidate(ticket, SourceInvalidationReasons.StatusOvertookInFlight); return false; } if (_hub.TryPublishStatus(ticket, checked(++slot.Sequence), status, null, null)) return true; - _hub.Invalidate(ticket, "source status admission failed"); + _hub.Invalidate(ticket, SourceInvalidationReasons.StatusAdmissionFailed); return false; } catch (OverflowException) { - _hub.Invalidate(ticket, "source status sequence exhausted"); + _hub.Invalidate(ticket, SourceInvalidationReasons.StatusSequenceExhausted); return false; } finally { Monitor.Exit(slot.Gate); } @@ -580,14 +590,14 @@ public sealed class SourceSamplePublisher try { next = Bind(ticket.Key, ticket.Generation with { Lifecycle = checked(ticket.Generation.Lifecycle + 1) }); } catch (InvalidOperationException) { - _hub.Invalidate(ticket, "source status fence failed"); + _hub.Invalidate(ticket, SourceInvalidationReasons.StatusFenceFailed); if (!_hub.IsTicketCurrentNonBlocking(ticket)) ScheduleRepair(slot, ticket); return false; } - _hub.Invalidate(next, "status overtook in-flight source sample"); + _hub.Invalidate(next, SourceInvalidationReasons.StatusFenceOvertook); } if (_hub.TryPublishStatus(next, checked(++slot.Sequence), status, null, null)) return true; - _hub.Invalidate(next, "source status capacity"); + _hub.Invalidate(next, SourceInvalidationReasons.StatusCapacity); if (!_hub.IsTicketCurrentNonBlocking(next)) ScheduleRepair(slot, next); return false; } @@ -615,7 +625,7 @@ public sealed class SourceSamplePublisher else if (ticket.Key.SourceKind == "virtual") { _virtuals.Remove(ticket.Key.StableSourceId); _virtualRoutes.TryRemove(ticket.Key.StableSourceId, out _); } if (_hub.TryRemove(ticket, checked(++slot.Sequence))) return true; - _hub.Invalidate(ticket, "source removal capacity"); + _hub.Invalidate(ticket, SourceInvalidationReasons.RemovalCapacity); return false; } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs index f98f3b294..a5a5607a8 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs @@ -2231,7 +2231,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers if (_sourcePublisher is null || _sourceIncarnation is not { } incarnation) return; foreach (var item in items) if (item is not null && _sourcePublisher.TryCaptureDriver(_driverInstanceId, item.FullReference, incarnation, out var ticket)) - _sourcePublisher.Invalidate(ticket, "legacy callback staging overflow"); + _sourcePublisher.Invalidate(ticket, ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceInvalidationReasons.LegacyStagingOverflow); } private sealed class SharedAcquisitionReservation(IDisposable reservation) @@ -2978,12 +2978,12 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers _sourcePublisher.EnsureDriverBinding(_clusterId, _driverInstanceId, reference, current)) found = _sourcePublisher.TryCaptureDriver(_driverInstanceId, reference, current, out ticket); if (!found) return; - if (snapshot is null) _sourcePublisher.Invalidate(ticket, "malformed driver callback"); + if (snapshot is null) _sourcePublisher.Invalidate(ticket, ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceInvalidationReasons.MalformedCallback); else _sourcePublisher.TryPublish(ticket, snapshot); } catch (Exception ex) when (ex is not OutOfMemoryException) { - if (found) _sourcePublisher.Invalidate(ticket, "source callback failed"); + if (found) _sourcePublisher.Invalidate(ticket, ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceInvalidationReasons.CallbackFailed); _log.Warning(ex, "DriverInstance {Id}: source callback unavailable; legacy publication continues", _driverInstanceId); } } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcData1026BindingContentionTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcData1026BindingContentionTests.cs new file mode 100644 index 000000000..a218519f5 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcData1026BindingContentionTests.cs @@ -0,0 +1,97 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +/// +/// #1026: the driver actor's source-binding retry re-walks every desired reference through +/// (from offset 0, every ≤ 30 s once any one failed). For a source +/// that was ALREADY bound to the current producer, that walk took the source's serialization gate; when the poll thread was +/// publishing the same source at that instant, the walk invalidated it ("source binding contention") — and the publish, +/// finding the gate held, invalidated it too ("source serialization contention"). The live scale gate (2048 sources) showed +/// only those two reasons, resetting every origin stream holding the source, on every retry pass. +/// +[Trait("Feature", "GrpcData")] +[Trait("Category", "Unit")] +public sealed class GrpcData1026BindingContentionTests +{ + private const string Driver = "modscale"; + private static readonly ServingIdentity Serving = new("node-a", "instance-a", "Primary", 1, 1); + private static readonly TimeSpan Wait = TimeSpan.FromSeconds(10); + + [Fact] + public async Task Re_ensuring_a_current_binding_while_its_publisher_holds_the_source_gate_neither_invalidates_nor_resets_the_stream() + { + var token = TestContext.Current.CancellationToken; + using var hub = HubTest.Create(partitions: 1, bytes: 1_000_000, ingress: 100, dirty: 100); + var publisher = new SourceSamplePublisher(hub, () => Serving, "cluster-a"); + publisher.RegisterDriverShape(Driver, "t0000", SourceValueShape.FromDriverType("UInt16", false)).ShouldBeTrue(); + var producer = publisher.RegisterDriverIncarnation(Driver); + publisher.EnsureDriverBinding("cluster-a", Driver, "t0000", producer).ShouldBeTrue(); + publisher.TryCaptureDriver(Driver, "t0000", producer, out var ticket).ShouldBeTrue(); + publisher.TryPublish(ticket, new DataValueSnapshot((ushort)7, OpcUaStatus.Good, DateTime.UtcNow, DateTime.UtcNow)).ShouldBeTrue(); + hub.ProcessPending(); + hub.TryCaptureInterestSnapshot([ticket], HubTest.Budget, CancellationToken.None, out var snapshot, out var interest).ShouldBeTrue(); + using (interest!) + { + snapshot!.Dispose(); + var before = SourceIngressDiagnostics.Capture()["Invalidate.BindingContention"]; + using var held = new ManualResetEventSlim(); + using var release = new ManualResetEventSlim(); + // The poll thread mid-publish: it holds this source's serialization gate. + var publishing = Task.Run(() => publisher.WithAcquisitionStatusLockForTest(ticket, publisherGate: false, () => + { + held.Set(); + release.Wait(Wait, token); + }), token); + try + { + held.Wait(Wait, token).ShouldBeTrue(); + // The binding retry pass reaches the same, already bound reference. + publisher.EnsureDriverBinding("cluster-a", Driver, "t0000", producer).ShouldBeTrue("it is already bound and current"); + } + finally { release.Set(); await publishing.WaitAsync(Wait, token); } + SourceIngressDiagnostics.Capture()["Invalidate.BindingContention"].ShouldBe(before); + interest!.TryReadChanges(32, out _).ShouldBeTrue("a binding check of a current source is not this stream's reset"); + interest.ResetReason.ShouldBe(InterestResetReason.None); + // Positive control: the source still delivers through the same ticket afterwards. + publisher.TryPublish(ticket, new DataValueSnapshot((ushort)8, OpcUaStatus.Good, DateTime.UtcNow, DateTime.UtcNow)).ShouldBeTrue(); + hub.ProcessPending(); + interest.TryReadChanges(32, out var changes).ShouldBeTrue(); + changes.ShouldContain(change => change.Ticket == ticket); + } + } + + [Fact] + public async Task A_binding_that_is_not_current_still_cannot_be_ensured_through_a_held_gate() + { + // Control: the fast path answers only a CURRENT binding. A replaced producer's reference still needs the gate. + var token = TestContext.Current.CancellationToken; + using var hub = HubTest.Create(partitions: 1, bytes: 1_000_000, ingress: 100, dirty: 100); + var publisher = new SourceSamplePublisher(hub, () => Serving, "cluster-a"); + publisher.RegisterDriverShape(Driver, "t0001", SourceValueShape.FromDriverType("UInt16", false)).ShouldBeTrue(); + var old = publisher.RegisterDriverIncarnation(Driver); + publisher.EnsureDriverBinding("cluster-a", Driver, "t0001", old).ShouldBeTrue(); + publisher.TryCaptureDriver(Driver, "t0001", old, out var oldTicket).ShouldBeTrue(); + var replacement = publisher.RegisterDriverIncarnation(Driver); // retires `old` + using var held = new ManualResetEventSlim(); + using var release = new ManualResetEventSlim(); + var holder = Task.Run(() => publisher.WithAcquisitionStatusLockForTest(oldTicket, publisherGate: false, () => + { + held.Set(); + release.Wait(Wait, token); + }), token); + try + { + held.Wait(Wait, token).ShouldBeTrue(); + publisher.EnsureDriverBinding("cluster-a", Driver, "t0001", replacement).ShouldBeFalse("a rebind needs the gate"); + } + finally { release.Set(); await holder.WaitAsync(Wait, token); } + publisher.EnsureDriverBinding("cluster-a", Driver, "t0001", replacement).ShouldBeTrue(); + publisher.TryCaptureDriver(Driver, "t0001", replacement, out _).ShouldBeTrue(); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcData1026RenewalBatchWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcData1026RenewalBatchWireTests.cs new file mode 100644 index 000000000..752938aea --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcData1026RenewalBatchWireTests.cs @@ -0,0 +1,103 @@ +using Opc.Ua; +using Opc.Ua.Client; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +/// +/// #1026: a cohort renews its items' metadata leases in batches. It used to renew each item with its own capabilities + +/// GetMetadata pair, each holding one unary-budget reservation and one resolver fetch slot taken without waiting; the +/// excess failed and retried only on the NEXT 250 ms renewal tick. With the production defaults (1 MiB unary budget ⇒ four +/// 256 KiB reservations) a cohort renewed ~16 items a second, so a 2048-item cohort's 15 s leases (renewed in their second +/// half) lapsed faster than they renewed: the scale gate saw ~1900 of 2048 items stood down BadUserAccessDenied. +/// +public sealed partial class GrpcDataConfiguredDiscoveryWireTests +{ + [Fact(Timeout = 90000), Trait("Issue", "1026")] + public async Task One_renewal_tick_renews_every_due_item_of_a_cohort_in_one_metadata_call() + { + const int Items = 6; // the composed server admits 8 demands, 4 unary operations and 2 resolver fetch slots + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + using var origin = new LocalDataFixture(additionalRawNodes: Items - 1, servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); + peer = origin; + var connections = new RenewalConnections(origin); + await WithComposedServer(origin, origin.Root, async (session, _, resolver, _, access, _, anchor) => + { + var client = (SessionClient)session; + var children = (await BrowseAll(client, anchor, 10)).Select(r => ExpandedNodeId.ToNodeId(r.NodeId, session.NamespaceUris)).ToArray(); + children.Length.ShouldBe(Items); + var ids = children.Select(child => child.IdentifierAsString).ToArray(); + var subscription = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + for (var i = 0; i < Items; i++) await AddComposedItem(client, subscription, children[i], (uint)(i + 1), 100, ct); + await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct); + var initial = ids.Select(id => resolver.TryResolveProjected(DataRealm.Raw, id, out var proof) ? proof : null).ToArray(); + initial.ShouldAllBe(proof => proof != null); + while (connections.MetadataRequests.Reader.TryRead(out _)) { } + var before = ProjectedStreamDiagnostics.Capture(); + + // Into the renewal window (lease 15 s, renewed in its second half) in ONE step: exactly one renewal tick fires. + await AdvanceAndSettle(origin.Clock, access, TimeSpan.FromSeconds(9), ct, oneStep: true); + // No further tick: everything the cohort renews now, it renews from that one tick. + var renewed = 0; + for (var wait = 0; wait < 400; wait++) + { + renewed = ids.Where((id, i) => resolver.TryResolveProjected(DataRealm.Raw, id, out var proof) && !ReferenceEquals(proof, initial[i])).Count(); + if (renewed == Items) break; + await Task.Delay(25, ct); + } + var after = ProjectedStreamDiagnostics.Capture(); + renewed.ShouldBe(Items, "one renewal tick renews every due item of the cohort; per-item renewals beyond the unary budget " + + $"waited for later ticks (budget refusals {after["RenewalBudget"] - before["RenewalBudget"]}, " + + $"slot refusals {after["RenewalSlots"] - before["RenewalSlots"]})"); + var metadataCalls = 0; + while (connections.MetadataRequests.Reader.TryRead(out _)) metadataCalls++; + metadataCalls.ShouldBe(1, "the cohort's due items renew in one GetMetadata call"); + }, connectionSource: connections); + } + + /// + /// #1026: two demands of ONE node in ONE cohort (two clients' monitored items at the same interval, or a client's + /// abandoned subscription beside its new one) reach the renewal window together. The batch claims the predecessor for the + /// first and the second joins that claim (#969) — so the batch must publish its verdict before it waits for the joiner, + /// or both wait forever and both leases lapse (the scale gate's second run stood ~1000 items down). + /// + [Fact(Timeout = 90000), Trait("Issue", "1026")] + public async Task Two_demands_of_one_node_in_one_cohort_both_renew_from_one_tick() + { + var ct = TestContext.Current.CancellationToken; + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); + peer = origin; subscriptions.SampleClock = origin.Clock; + var published = System.Threading.Channels.Channel.CreateUnbounded(); + var connections = new RenewalConnections(origin); + await WithComposedServer(origin, origin.Raw, async (session, _, _, _, access, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var first = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, first, anchor, 1, 100, ct); + await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(SetupWait, ct); + var original = await NextPublishedRenewal(published.Reader, x => x.IsCompleteSnapshot, ct); + var second = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, second, anchor, 2, 100, ct); + await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(SetupWait, ct); + subscriptions.Opens.ShouldBe(1, "both items share one cohort (same connection, serving and interval)"); + (await PublishComposedValue(client, 2, ct)).StatusCode.ShouldBe(StatusCodes.Good); + while (published.Reader.TryRead(out _)) { } + + await AdvanceAndSettle(origin.Clock, access, TimeSpan.FromSeconds(9), ct, oneStep: true); + // Each registration rebinds onto the successor with its own fresh complete baseline (before the fix neither did: the + // batch waited for the joiner, the joiner for the batch's verdict). Whether the first rebind's witness is still valid + // once the second rebinds is the shared source's business, not this test's. + for (var i = 0; i < 2; i++) + await NextPublishedRenewal(published.Reader, x => x.IsCompleteSnapshot && x.ReceivedTimestamp > original.ReceivedTimestamp, ct); + access.OverlapRenewalsJoinedForTests.ShouldBe(1, "the second demand joined the first one's renewal"); + }, onPublished: update => published.Writer.TryWrite(update), connectionSource: connections); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcData1026ResetReasonTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcData1026ResetReasonTests.cs new file mode 100644 index 000000000..56452bfdf --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcData1026ResetReasonTests.cs @@ -0,0 +1,108 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +/// +/// #1026: an origin stream reset names its cause. Every interest-lease reset used to reach the consumer as +/// "Source change history expired.", whether the history rolled, an own source was invalidated (and for which of ~25 +/// reasons), the lease was released or the partition epoch moved. +/// +[Trait("Feature", "GrpcData")] +[Trait("Category", "Unit")] +public sealed class GrpcData1026ResetReasonTests +{ + [Fact] + public void An_own_source_invalidation_names_its_reason_on_the_lease_and_in_the_counters() + { + using var hub = HubTest.Create(partitions: 1, bytes: 1_000_000, ingress: 100, dirty: 100); + var mine = HubTest.Ticket("driver", "reason-mine"); + HubTest.BindAndPublish(hub, mine, 1, 1); + hub.ProcessPending(); + hub.TryCaptureInterestSnapshot([mine], HubTest.Budget, CancellationToken.None, out var snapshot, out var interest).ShouldBeTrue(); + using (interest!) + { + snapshot!.Dispose(); + var before = SourceIngressDiagnostics.Capture()["Invalidate.SerializationContention"]; + hub.Invalidate(mine, SourceInvalidationReasons.SerializationContention); + SourceIngressDiagnostics.Capture()["Invalidate.SerializationContention"].ShouldBeGreaterThan(before); + interest!.TryReadChanges(32, out _).ShouldBeFalse(); + interest.ResetReason.ShouldBe(InterestResetReason.SourceInvalidated); + interest.ResetSourceReason.ShouldBe(SourceInvalidationReason.SerializationContention); + InterestResetDiagnostics.Describe(interest.ResetReason, interest.ResetSourceReason) + .ShouldBe("Source invalidated (SerializationContention)."); + } + } + + [Fact] + public void A_partition_invalidation_and_a_release_are_named_too() + { + using var hub = HubTest.Create(partitions: 1, bytes: 1_000_000, ingress: 100, dirty: 100); + var a = HubTest.Ticket("driver", "reason-a"); + HubTest.BindAndPublish(hub, a, 1, 1); + hub.ProcessPending(); + hub.TryCaptureInterestSnapshot([a], HubTest.Budget, CancellationToken.None, out var s1, out var partitioned).ShouldBeTrue(); + hub.TryCaptureInterestSnapshot([a], HubTest.Budget, CancellationToken.None, out var s2, out var released).ShouldBeTrue(); + s1!.Dispose(); s2!.Dispose(); + released!.Dispose(); + released.TryReadChanges(32, out _).ShouldBeFalse(); + released.ResetReason.ShouldBe(InterestResetReason.Released); + using (partitioned!) + { + hub.InvalidatePartitionFor(a.Key, "overload"); + partitioned!.TryReadChanges(32, out _).ShouldBeFalse(); + partitioned.ResetReason.ShouldBe(InterestResetReason.PartitionEpoch); + } + } + + [Theory] + [InlineData("Source change history expired.", "ResetHistory")] + [InlineData("Source invalidated (CommitRejected).", "ResetSourceInvalidated")] + [InlineData("Source interest released.", "ResetInterestLost")] + [InlineData("Source partition reset.", "ResetInterestLost")] + [InlineData("Source routing changed.", "ResetInterestLost")] + [InlineData("Source binding replaced.", "ResetInterestLost")] + [InlineData("Source retired.", "ResetInterestLost")] + [InlineData("Snapshot catch-up expired; retry later.", "ResetSnapshot")] + [InlineData("something else", "ResetOther")] + public void The_consumer_counts_each_reset_text_separately(string diagnostic, string expected) => + ProjectedStreamDiagnostics.ClassifyReset(diagnostic).ToString().ShouldBe(expected); + + [Fact] + public void A_retired_or_partition_invalidated_own_source_is_named_as_such_not_as_an_invalidation() + { + InterestResetDiagnostics.Describe(InterestResetReason.SourceInvalidated, SourceInvalidationReason.Retired).ShouldBe("Source retired."); + InterestResetDiagnostics.Describe(InterestResetReason.SourceInvalidated, SourceInvalidationReason.PartitionInvalidated) + .ShouldBe("Source partition reset."); + InterestResetDiagnostics.Describe(InterestResetReason.None, SourceInvalidationReason.Other).ShouldBe("Source change history expired."); + } + + [Fact] + public void Removing_a_source_names_its_streams_reset_retired() + { + using var hub = HubTest.Create(partitions: 1, bytes: 1_000_000, ingress: 100, dirty: 100); + var mine = HubTest.Ticket("driver", "reason-removed"); + HubTest.BindAndPublish(hub, mine, 1, 1); + hub.ProcessPending(); + hub.TryCaptureInterestSnapshot([mine], HubTest.Budget, CancellationToken.None, out var snapshot, out var interest).ShouldBeTrue(); + using (interest!) + { + snapshot!.Dispose(); + hub.TryRemove(mine, 2).ShouldBeTrue(); + interest!.TryReadChanges(32, out _).ShouldBeFalse(); + InterestResetDiagnostics.Describe(interest.ResetReason, interest.ResetSourceReason).ShouldBe("Source retired."); + } + } + + [Fact] + public void Every_named_reason_string_classifies_to_its_own_enum_value() + { + var names = typeof(SourceInvalidationReasons).GetFields() + .Where(field => field.IsLiteral && field.FieldType == typeof(string)).ToArray(); + names.Length.ShouldBeGreaterThan(20); + foreach (var field in names) + SourceInvalidationReasons.Classify((string)field.GetRawConstantValue()!).ToString().ShouldBe(field.Name); + SourceInvalidationReasons.Classify("anything a test passes").ShouldBe(SourceInvalidationReason.Other); + } +}