diff --git a/docs/DataConnections.md b/docs/DataConnections.md index ab7426020..81a4f220e 100644 --- a/docs/DataConnections.md +++ b/docs/DataConnections.md @@ -412,6 +412,15 @@ found two defects that only show at hundreds of items: 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. +- **Consumer: an interrupted renewal no longer strands its item.** The catalog keeps at most one retained predecessor per + projected node, so a renewal fails while an older proof of the node is still pinned. When a stream ended mid-renewal (an + origin restart does that to every batch in flight) the node's source could still hold the predecessor (it had not yet + seen the successor's baseline) while its demand had moved to the successor; once both leases lapsed, every + between-attempt renewal failed (`RenewalFail.Cache.PredecessorChain`) and the item stayed `BadUserAccessDenied` for good — + live, ~1000 of 1888 items after a SOURCE restart. Between attempts a renewal now first retires an idle source whose own + proof lapsed, exactly as `GetSource` retires an invalid source (the next attempt creates a fresh one). The catalog names + the pin holders of a refused chain (`RenewalFail.Chain..`). An idle source's still-pinned overlap + predecessor is deliberately NOT released early: the expired-overlap failover recovery (recovery parking) relies on it. - **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` / 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 fe7deb2d5..1a307f5d6 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedCatalogCache.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedCatalogCache.cs @@ -45,6 +45,8 @@ public interface IFederatedProjectionCatalog bool IsUsableProof(ProjectedNodeProof proof) => proof.Lease.IsValid && TryResolveProjected(proof.Metadata.View.Realm, proof.LocalIdentifier, out var current) && ReferenceEquals(current, proof); bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin); + /// #1026: naming its holder (diagnostics only). + bool TryPinProjected(DataRealm realm, string localId, string holder, out IDisposable? pin) => TryPinProjected(realm, localId, out pin); event Action? Invalidated; } @@ -53,7 +55,23 @@ public sealed class ProjectedCatalogCache { private readonly record struct ParentKey(string Mapping, DataView Parent, string? Filter, string? Cursor, DataCallerIdentity? Caller, ConfiguredProjectionCapability? Capability); private sealed class ParentEntry(ProjectedParentSnapshot snapshot) { internal readonly object Version = new(); internal ProjectedParentSnapshot Snapshot = snapshot; internal LinkedListNode? Sweep; } - private sealed class NodeEntry(ProjectedNodeProof proof) { internal ProjectedNodeProof Proof = proof; internal NodeEntry? Predecessor; internal int Pins; internal bool Retired; internal LinkedListNode<(DataRealm Realm, string Id)>? Sweep; } + private sealed class NodeEntry(ProjectedNodeProof proof) + { + internal ProjectedNodeProof Proof = proof; internal NodeEntry? Predecessor; internal int Pins; internal bool Retired; internal LinkedListNode<(DataRealm Realm, string Id)>? Sweep; + /// #1026: pins by holder kind (under the cache lock), named when a renewal is refused for a pinned predecessor. + internal Dictionary? Holders; + internal void Hold(string holder, int delta) + { + Holders ??= new(StringComparer.Ordinal); + var count = Holders.GetValueOrDefault(holder) + delta; + if (count <= 0) Holders.Remove(holder); else Holders[holder] = count; + } + } + private static void CountChainHolders(string role, NodeEntry? entry) + { + if (entry?.Holders is not { Count: > 0 } holders) { ProjectedStreamDiagnostics.CountRenewalFailure("Chain." + role + "." + (entry is null ? "none" : "unlabeled")); return; } + foreach (var holder in holders.Keys) ProjectedStreamDiagnostics.CountRenewalFailure("Chain." + role + "." + holder); + } private readonly object _sync = new(); private readonly Dictionary _parents = new(); private readonly Dictionary<(DataRealm Realm, string Id), NodeEntry> _nodes = new(); @@ -481,7 +499,14 @@ public sealed class ProjectedCatalogCache // 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) { ProjectedStreamDiagnostics.CountRenewalFailure("Cache.PredecessorChain"); return false; } + if ((long)oldCount + (current is { Pins: > 0 } ? 1 : 0) + 1 > 2) + { + ProjectedStreamDiagnostics.CountRenewalFailure("Cache.PredecessorChain"); + CountChainHolders(overlap ? "OverlapPredecessor" : "ExactPredecessor", current?.Predecessor); + CountChainHolders(overlap ? "OverlapCurrent" : "ExactCurrent", current); + if (_retiredByProof.TryGetValue(previous, out var retiredPrevious)) CountChainHolders("RetiredPrevious", retiredPrevious); + return false; + } _mappingNodeCounts.TryGetValue(mapping, out var count); var physicalMappingLimit = (long)maximumMappingNodes + Math.Min((long)maximumMappingNodes, _maxNodes); if ((long)count + (addsEntry ? 1 : 0) > physicalMappingLimit) { ProjectedStreamDiagnostics.CountRenewalFailure("Cache.MappingNodes"); return false; } @@ -537,12 +562,13 @@ public sealed class ProjectedCatalogCache try { return ValidCore(proof, requireLease: false); } catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or NullReferenceException) { return false; } } - public bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin) + public bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin) => TryPinProjected(realm, localId, "other", out pin); + public bool TryPinProjected(DataRealm realm, string localId, string holder, out IDisposable? pin) { lock (_sync) { if (!_nodes.TryGetValue((realm, localId), out var entry) || entry.Retired || !Valid(entry.Proof)) { pin = null; return false; } - entry.Pins++; pin = new Pin(this, entry); return true; + entry.Pins++; entry.Hold(holder, 1); pin = new Pin(this, entry, holder); return true; } } // Pins an already charged, expired successor solely for an invalid recovery @@ -567,11 +593,12 @@ public sealed class ProjectedCatalogCache else if (retiredCount != 2 || !_retiredByProof.TryGetValue(successor, out current)) return false; if (current.Pins <= 0) return false; checked { current.Pins++; } - pin = new Pin(this, current); + current.Hold("parked", 1); + pin = new Pin(this, current, "parked"); return true; } } - private sealed class Pin(ProjectedCatalogCache owner, NodeEntry entry) : IDisposable + private sealed class Pin(ProjectedCatalogCache owner, NodeEntry entry, string holder) : IDisposable { private int _disposed; public void Dispose() @@ -579,7 +606,7 @@ public sealed class ProjectedCatalogCache if (Interlocked.Exchange(ref _disposed, 1) != 0) return; lock (owner._sync) { - entry.Pins--; + entry.Pins--; entry.Hold(holder, -1); if (entry.Pins == 0 && entry.Retired) { var key = (entry.Proof.Metadata.View.Realm, entry.Proof.LocalIdentifier); 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 309db67d7..a4bf3539f 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs @@ -271,7 +271,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable var op = Operation(operation); if (!_policy.AuthorizeMapped(identity, op, proof.Metadata.View, proof.Lease.Serving, proof.Subject, proof.Resolver, proof.Lease) || !definition.Lifetime.TryPin(out var nodePin) || nodePin is null) { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.AcquireAuthorization); return false; } - if (!_catalog.TryPinProjected(definition.Realm, definition.LocalIdentifier, out var pin) || pin is null) { nodePin.Dispose(); ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.AcquirePin); return false; } + if (!_catalog.TryPinProjected(definition.Realm, definition.LocalIdentifier, "demand", out var pin) || pin is null) { nodePin.Dispose(); ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.AcquirePin); return false; } var candidate = new Demand(this, nodeId, definition, proof, identity, operation, pin, nodePin, connectionId, localRole.Generation, null); lock (_sync) { @@ -413,7 +413,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable proof.Metadata.View.MappingId is not { } mapping || proof.Lease.Serving.ServingGeneration <= 0 || (proof.Subject.AllowedOperations & DataOperations.Subscribe) == 0 || !capability.Matches(mapping, proof.Metadata.View, proof.Resolver.LocalAuthority) || _connectionForMapping(mapping) is not { Length: > 0 } connectionId || !definition.Lifetime.TryPin(out var nodePin) || nodePin is null) return false; - if (!_catalog.TryPinProjected(definition.Realm, definition.LocalIdentifier, out var pin) || pin is null) { nodePin.Dispose(); return false; } + if (!_catalog.TryPinProjected(definition.Realm, definition.LocalIdentifier, "read", out var pin) || pin is null) { nodePin.Dispose(); return false; } var candidate = new Demand(this, nodeId, definition, proof, null, DataOperations.Subscribe, pin, nodePin, connectionId, 1, capability); lock (_sync) { @@ -620,7 +620,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable caller is null || !owner._policy.AuthorizeMapped(caller, OpcUaOperation.CreateMonitoredItems, nextProof.Metadata.View, nextProof.Lease.Serving, nextProof.Subject, nextProof.Resolver, nextProof.Lease)) || !nextDefinition.Lifetime.TryPin(out nextNodePin) || nextNodePin is null) return false; - if (!owner._catalog.TryPinProjected(nextDefinition.Realm, nextDefinition.LocalIdentifier, out nextPin) || nextPin is null) return false; + if (!owner._catalog.TryPinProjected(nextDefinition.Realm, nextDefinition.LocalIdentifier, "binding", out nextPin) || nextPin is null) return false; if (!nextDefinition.AuthorityIsCurrent() || !owner._catalog.TryResolveProjected(nextDefinition.Realm, nextDefinition.LocalIdentifier, out var pinnedProof) || !ReferenceEquals(pinnedProof, nextProof)) return false; replacement = new(nextDefinition, nextProof, nextPin, nextNodePin, nextConnection); @@ -709,6 +709,11 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable { lock (Gate) ReleaseExpiredPredecessorLocked(); } + internal SourceKey Key => _key; + /// #1026: no cohort attempt is running on this source (between attempts). + internal bool IsIdle { get { lock (Gate) return _activeAttempts == 0; } } + /// #1026: the proof this source currently serves under (null once invalidated). + internal ProjectedNodeProof? CurrentProof { get { lock (Gate) return _proof; } } internal bool IsProofValid(ProjectedNodeProof captured) { try { return IsValid && captured.Lease.IsValid && _owner._catalog.IsUsableProof(captured); } @@ -1005,7 +1010,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable } } if (_sources.Count >= _limits.MaxDemands || !demand.Definition.Lifetime.TryPin(out var nodePin) || nodePin is null) return null; - if (!_catalog.TryPinProjected(demand.Realm, demand.LocalIdentifier, out var pin) || pin is null) { nodePin.Dispose(); return null; } + if (!_catalog.TryPinProjected(demand.Realm, demand.LocalIdentifier, "source", out var pin) || pin is null) { nodePin.Dispose(); return null; } var route = new ProjectedValueRoute("grpc-data:" + connection, ProjectedDataIds.DependencyReference(demand.Realm, demand.LocalIdentifier), demand.Realm, demand.LocalIdentifier, demand.ProjectionGeneration, demand.Serving, Guid.NewGuid()); var source = new SourceState(this, key, proof, demand.Definition, pin, nodePin, route) @@ -1622,13 +1627,37 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable 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) + if (resolver is not null && sink is not null && renew.Count > 0) + { + // #1026: the catalog admits at most one retained predecessor per node, so a renewal fails while an older proof of + // the node is still pinned. A renewal interrupted mid-cycle (the stream ended after the demand rebound onto the + // successor but before the successor's baseline reached the node's source — an origin restart does that to + // every batch in flight) leaves the idle source on the predecessor, pinning it; once both leases lapsed every + // renewal of the successor failed and the item stayed lapsed for good. An idle source whose own proof lapsed AND + // is no longer the node's current proof (it fell behind its demands) is retired here, exactly as GetSource + // retires an invalid source (the next attempt creates a fresh one). A source that is on the node's current + // proof keeps its overlap predecessor: expired-overlap recovery parking relies on it. + var sourceOf = new Dictionary(); + foreach (var (sourceDemand, demandSourceState) in sources) sourceOf[sourceDemand] = demandSourceState; + var staleSources = new List(); + foreach (var (demand, old) in renew) + { + if (!sourceOf.TryGetValue(demand, out var candidate) || staleSources.Contains(candidate) || !candidate.IsIdle || + candidate.IsValid || candidate.CurrentProof is not { } sourceProof || + !resolver.TryResolveForRenewal(old.Definition.Realm, old.Definition.LocalIdentifier, out var nodeCurrent) || + nodeCurrent is null || ReferenceEquals(sourceProof, nodeCurrent)) continue; + lock (_owner._sync) + if (_owner._sources.TryGetValue(candidate.Key, out var registered) && ReferenceEquals(registered, candidate) && + _owner.RemoveSourceLocked(candidate.Key, out _)) staleSources.Add(candidate); + } + foreach (var stale in staleSources) stale.Invalidate(); for (var offset = 0; offset < renew.Count; offset += RenewalBatchItems) { if (_stop.IsCancellationRequested) return; await RenewOwnedBatchAsync(renew.GetRange(offset, Math.Min(RenewalBatchItems, renew.Count - offset)), resolver, sink, _stop.Token).ConfigureAwait(false); } + } foreach (var (demand, old) in renew) { if (_stop.IsCancellationRequested) return; 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 6efd3fec3..e515954ef 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/RemoteNamespaceResolver.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/RemoteNamespaceResolver.cs @@ -104,6 +104,7 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp public bool TryResolveProjected(DataRealm realm, string localId, out ProjectedNodeProof? proof) => _cache.TryResolveProjected(realm, localId, out proof); public bool IsUsableProof(ProjectedNodeProof proof) => _cache.IsUsableProof(proof); public bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin) => _cache.TryPinProjected(realm, localId, out pin); + public bool TryPinProjected(DataRealm realm, string localId, string holder, out IDisposable? pin) => _cache.TryPinProjected(realm, localId, holder, out pin); internal bool TryResolveForRenewal(DataRealm realm, string localId, out ProjectedNodeProof? proof) => _cache.TryResolveForRenewal(realm, localId, out proof); internal bool TryPinExpiredRecoveryPair(ProjectedNodeProof previous, ProjectedNodeProof successor, out IDisposable? pin) => 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 index 752938aea..1fa63d29a 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcData1026RenewalBatchWireTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcData1026RenewalBatchWireTests.cs @@ -60,6 +60,47 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests }, connectionSource: connections); } + /// + /// #1026: a renewal interrupted mid-cycle. The catalog committed the successor and the demand rebound onto it, but the + /// stream ended before the successor's baseline arrived, so the node's source still holds the predecessor. Once both + /// leases lapsed, the between-attempt renewal of the successor did not fit the catalog's bound of one retained + /// predecessor (the idle source still pinned it) — the scale gate saw ~1000 of 1888 items never recover after an origin + /// restart (RenewalFail.Cache.PredecessorChain). The idle, lapsed source is retired first, as GetSource would. + /// + [Fact(Timeout = 90000), Trait("Issue", "1026")] + public async Task A_renewal_interrupted_before_the_successor_baseline_still_recovers_after_both_leases_lapse() + { + 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) { HoldFirstRenewalRemoveAck = true }; + await WithComposedServer(origin, origin.Raw, async (session, _, _, _, access, _, anchor) => + { + var client = (SessionClient)session; + await BrowseAll(client, anchor, 1); + var subscription = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId; + await AddComposedItem(client, subscription, anchor, 1, 100, ct); + await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(SetupWait, ct); + var original = await NextPublishedRenewal(published.Reader, x => x.IsCompleteSnapshot, ct); + (await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good); + + // Renew: the catalog commits the successor and the demand rebinds onto it; its rebind is then held (no successor baseline). + await AdvanceAndSettle(origin.Clock, access, TimeSpan.FromSeconds(9), ct, oneStep: true); + await connections.RenewalRemoveAckHeld.Task.WaitAsync(SetupWait, ct); + var chainBefore = ProjectedStreamDiagnostics.Capture().GetValueOrDefault("RenewalFail.Cache.PredecessorChain"); + // Both leases lapse: the cohort's attempt ends (its demand is no longer valid) and it renews between attempts. + for (var i = 0; i < 20; i++) await AdvanceAndSettle(origin.Clock, access, TimeSpan.FromSeconds(1), ct); + var recovered = await NextPublishedRenewal(published.Reader, + x => x.IsCompleteSnapshot && x.ReceivedTimestamp > original.ReceivedTimestamp && x.SourceProof.IsValid, ct); + recovered.SourceProof.IsValid.ShouldBeTrue(); + (ProjectedStreamDiagnostics.Capture().GetValueOrDefault("RenewalFail.Cache.PredecessorChain") - chainBefore) + .ShouldBe(0, "the idle source's lapsed predecessor must not block the renewal"); + }, onPublished: update => published.Writer.TryWrite(update), 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