diff --git a/docs/DataConnections.md b/docs/DataConnections.md
index 92be059e6..ce8704d57 100644
--- a/docs/DataConnections.md
+++ b/docs/DataConnections.md
@@ -94,19 +94,29 @@ unavailable until valid authority can be established.
`MetadataLeaseMilliseconds` keeps its retained proof; the lease is only *lapsed* when its time ran
out or its route was replaced while the local catalog authority, mapping binding and cache
generation are all still current and nothing revoked it. On a refused value Read / attribute Read /
-HistoryRead of such a node, the consumer first authorizes the caller against the lapsed subject
-(local grant + mapping bit, everything but the lease). A caller without the grant is still
+HistoryRead / Write / CreateMonitoredItems (the last two since #940) of such a node, the consumer first
+authorizes the caller against the lapsed subject (local grant + mapping bit, everything but the lease;
+a write also needs this node's local write role). A caller without the grant is still
`BadUserAccessDenied` and nothing is sent to the origin. A granted caller gets the same exact
-`GetMetadata` renewal as above, for the operation it is performing (Read / HistoryRead bit, not
-Subscribe), one per node and operation at a time, with a 250 ms back-off after a failure. On-demand
+`GetMetadata` renewal as above, for the operation it is performing (its Read / HistoryRead / Write /
+Subscribe bit), one per node and operation at a time, with a 250 ms back-off after a failure. On-demand
renewals never touch the unary budget (cold reads, writes) or the browse/subscription-renewal fetch
slots: they queue (at most 64) for their own pool of `max(1, maxConcurrentFetches / 2)` origin calls,
reserve 256 KiB each, and have 3 s end to end, so a batch of N lapsed nodes renews all N:
-- **Value Read** answers `BadWaitingForInitialData` (as a cold read does) while the renewal runs off
- the request thread; once it commits, a read is scheduled so the client's retry is served from the
- fresh sample. `BadResourceUnavailable` while a renewal cannot be started (capacity, back-off).
+- **Value Read** awaits the renewal within the request (#938; the async Read, no `Lock`, at most
+ 5 s together with the origin read that follows) and is then served from an origin read. A renewal
+ still running at the deadline answers `BadWaitingForInitialData` (as a cold read does);
+ `BadResourceUnavailable` while a renewal cannot be started (capacity, back-off) or failed.
A non-Value attribute of a lapsed node answers `BadResourceUnavailable` while it renews.
+- **Write** (#940) awaits the renewal (at most 4 s, and at most half the request's timeout hint)
+ and is then dispatched. A renewal that cannot complete or start answers `BadResourceUnavailable`
+ with nothing sent to the origin.
+- **CreateMonitoredItems** (#940) awaits the renewal of its lapsed Value items once per request (at
+ most 4 s, async, no `Lock`) and then creates them. An item still not acquirable is answered PER
+ ITEM — `BadResourceUnavailable` for a lapse the caller is granted, `BadUserAccessDenied` for a real
+ refusal. (Before, a refused projected item was thrown from the item manager and faulted the whole
+ CreateMonitoredItems request.)
- **HistoryRead** renews within the request and is then served. The wait (one per batch, at most 4 s
and never past `HistoryReadDeadline`, no node-manager `Lock` held, the request's cancellation
honoured) takes one of the non-local history batch slots first. A batch that finds none free does
@@ -116,13 +126,17 @@ reserve 256 KiB each, and have 3 s end to end, so a batch of N lapsed nodes rene
- **Browse:** a cached page past half its lease is served as is *and* refreshed in the background
(one refresh per page key), so a re-browse renews the leases of the nodes it lists.
-An origin that stopped granting the operation fails the renewal; the consumer then keeps answering
-the retryable status (it cannot tell that from an unreachable origin).
+**An origin refusal is an access denial (#939).** The renewal reports why it did not commit. A
+definitive refusal BY THE ORIGIN — the call answered `PERMISSION_DENIED`, the item answered `Denied`,
+the principal no longer holds Metadata, or the returned metadata no longer grants the operation (for a
+write: or is no longer writable) — is answered `BadUserAccessDenied` and held for 5 s
+(`ProjectedDataAccess.LapseRefusalHold`) per node and operation, during which the node is refused
+without another origin call; after it the next request asks the origin again. Everything else (an
+unreachable, unready or non-primary origin, an `Unauthenticated` call, capacity, a timeout, a changed
+shape) stays retryable with the 250 ms back-off. HistoryRead follows the same rule.
-Not covered yet: a **Write** or **CreateMonitoredItems** on a lapsed node is still refused
-`BadUserAccessDenied` (neither starts a renewal; a re-browse, a Read or a HistoryRead of the node
-renews it, after which they succeed). A lease that was revoked (`Invalidate`), a removed mapping and a
-retired node are refusals, not lapses, and are never renewed.
+A lease that was revoked (`Invalidate`), a removed mapping and a retired node are refusals, not
+lapses, and are never renewed.
An authorized logical monitored-item request can survive a physical stream expiry and seek a new
pinned binding with bounded retries. The old binding and any queued sample evidence remain tied to
diff --git a/docs/ReadWriteOperations.md b/docs/ReadWriteOperations.md
index 5950237da..e476e2063 100644
--- a/docs/ReadWriteOperations.md
+++ b/docs/ReadWriteOperations.md
@@ -35,14 +35,24 @@ continuations must still match current authority, catalog and serving generation
A projected Value Read first acquires a current scoped demand. A cached sample can be returned
only when its proof, serving identity, projection generation and age satisfy the request.
-`maxAge=0`, a missing sample or an unsuitable sample schedules an asynchronous bounded remote
-read and returns `BadWaitingForInitialData`; it does not block the SDK callback on the network.
-The response refreshes the local cache for a later Read. The origin's own local Read remains a
-cached read rather than a device poll.
+**Since #938** a `maxAge` the cache cannot satisfy — `maxAge=0` always (Part 4: read the source),
+a missing sample or an unsuitable one — is served from a bounded origin read **in the same
+request**: the node manager's async Read (`IReadAsyncNodeManager`, no node-manager `Lock` held, no
+request thread blocked) reads the origin, serves what it read and publishes it to the cache. The
+wait is at most 5 s per request (`OtOpcUaNodeManager.ProjectedOriginReadWait`), less the request
+deadline's margin; the reads are admitted against the same unary budget as before (the default
+1 MiB `MaxPendingBytes` admits one 1 MiB read at a time) and a batch is pumped through it as reads
+complete. A read that is not answered in time, or answers nothing servable (unreachable, not
+ready, older than the mapping's stale timeout), returns `BadWaitingForInitialData` as before; a
+read never admitted by the deadline is scheduled as before. A lapsed lease is renewed first, in the
+same request (see [Data connections](DataConnections.md#subscription-freshness-and-exact-item-renewal)).
+Before #938 `maxAge=0` was never served from the cache and never awaited, so it answered
+`BadWaitingForInitialData` on every read — which is what ScadaBridge's DCL
+(`RealOpcUaClient.ReadValuesAsync`, `session.ReadAsync(null, 0, …)`) and the Client CLI default send.
+The origin's own local Read remains a cached read rather than a device poll.
-For explicit cached reads, the CLI accepts `read --max-age 5000` (milliseconds).
-Its default remains zero. A cold projection can still return pending; retry after
-the bounded refresh completes. This matches the [OPC UA Read age parameter](https://reference.opcfoundation.org/specs/OPC-10000-4/5.11.2);
+For explicit cached reads, the CLI accepts `read --max-age 5000` (milliseconds); its default is
+zero. This matches the [OPC UA Read age parameter](https://reference.opcfoundation.org/specs/OPC-10000-4/5.11.2);
it does not extend a mapping's authority lease or allowed origin-sample age.
Projected data-change monitored items acquire live demands and share compatible upstream
diff --git a/docs/plans/evidence/grpc-data-ext/938-939-940-948.md b/docs/plans/evidence/grpc-data-ext/938-939-940-948.md
new file mode 100644
index 000000000..94f448f2f
--- /dev/null
+++ b/docs/plans/evidence/grpc-data-ext/938-939-940-948.md
@@ -0,0 +1,75 @@
+# #938 / #939 / #940 / #948 — projected Read age, origin refusals, lapsed Write/Subscribe, consumed candidates
+
+2026-12-01. Follow-ups of #920 and #922 (`920.md`, `fu922.md`). Consumer side of gRPC data connections.
+
+## #938 — `maxAge = 0` never returned Good
+
+**Root cause.** The projected Value Read (`OtOpcUaNodeManager.Read` pre-loop) served the cache only when `maxAge > 0`, and every
+other case scheduled a fire-and-forget origin read and answered `BadWaitingForInitialData` (the sync SDK callback could not wait).
+With `maxAge = 0` the cache is never eligible, so every read was `BadWaitingForInitialData`, forever.
+
+**Who sends 0.** The Client CLI default (`read --max-age 0`) and **ScadaBridge's DCL**:
+`RealOpcUaClient.ReadValuesAsync` (`src/ZB.MOM.WW.ScadaBridge.DataConnectionLayer/Adapters/RealOpcUaClient.cs:1546`) calls
+`session.ReadAsync(null, 0, …)` for every Value read (`ReadValueAsync` delegates to it). Its other `ReadAsync` calls (lines 1687,
+1992) read DataType/ValueRank/AccessLevel, not Value.
+
+**Fix.** `OtOpcUaNodeManager` implements `IReadAsyncNodeManager` (forwarded by the SDK's `AsyncNodeManagerAdapter`): before the
+unchanged sync `Read`, it serves every projected Value read the cache cannot satisfy from an awaited origin read
+(`IProjectedDataAccess.ReadNowAsync` — the same admission, authenticated/freshness-checked read and cache publication as
+`ScheduleRead`). A lapsed lease is renewed first (#922 classification) and read in the same request. Bounded by 5 s
+(`ProjectedOriginReadWait`) and the request deadline − 250 ms; reads are pumped through the unary budget (the default 1 MiB budget
+admits one read at a time). Unanswered / unservable ⇒ `BadWaitingForInitialData` as before; the caller's demand is re-checked at
+serve time. The renewal no longer schedules a separate warming read.
+
+## #939 — an origin refusal read as retryable
+
+**Root cause.** `RemoteNamespaceResolver.RenewExactAsync` returned `bool`, so an origin that stopped granting the operation looked
+exactly like an unreachable one (`BadResourceUnavailable`, 250 ms back-off, retried forever).
+
+**Fix.** `RenewExactOutcomeAsync` → `ProjectedRenewalResult {Renewed, Refused, Failed}`. `Refused` only for the origin's own verdict:
+the call answered `PERMISSION_DENIED` (as the cause of the connection's "no ready endpoint" failure), the item answered `Denied`, the
+principal no longer holds Metadata, or the metadata no longer grants the operation (a write: or is not writable). It is answered
+`BadUserAccessDenied` (Read, HistoryRead, Write, CreateMonitoredItems) and held 5 s (`LapseRefusalHold`) per node and operation,
+unsent. `Unauthenticated`, unreachable, unready, capacity and timeouts stay `Failed` (retryable).
+
+## #940 — Write / CreateMonitoredItems on a lapsed node
+
+**Root cause.** Neither classified a refused acquire; both answered `BadUserAccessDenied`. CreateMonitoredItems threw it from the item
+manager, which runs under the SDK's `Lock` and faults the WHOLE request.
+
+**Fix.** `RenewLapsed` accepts Write (also gated on the local write role) and Subscribe. `OtOpcUaSdkServer.WriteAsync` awaits the
+renewal (≤ 4 s, ≤ half the timeout hint) and dispatches; `BadResourceUnavailable` (unsent) when it cannot renew. CreateMonitoredItems:
+`ICreateMonitoredItemsAsyncNodeManager` awaits the renewals once per request (≤ 4 s), then the sync override classifies each projected
+Value item outside `Lock` (probe acquire; lapse ⇒ `BadResourceUnavailable`, refusal ⇒ `BadUserAccessDenied`) PER ITEM.
+
+## #948 — orphan proof candidate for a consumed acquisition
+
+**Decision: not intended.** A candidate exists to prove one SDK notification; a re-delivered acquisition the item already delivered
+produces none (same value/status/timestamps ⇒ the SDK filter drops it), so the candidate and its shared budget charge lingered.
+`ProjectedMonitoredItem` now remembers the last consumed acquisition (key only, no value). A complete snapshot of it, with nothing
+queued since (no candidate, no queued loss, no rebind / client mode change / unmatched notification), renews health evidence and adds
+no candidate. Any queue reset clears the memory, so a wrong skip can only cost an unproven notification + baseline request.
+
+## Red / green (Runtime harness, real consumer SDK session + projection stack)
+
+| Test (`Trait Issue`) | pre-fix | fix |
+|---|---|---|
+| 938 `A_max_age_zero_read_is_served_from_the_origin_in_the_same_request_every_time` | **FAIL** | pass |
+| 938 `A_max_age_zero_batch_larger_than_the_unary_budget_is_pumped_and_fully_served` | **FAIL** | pass |
+| 938 `A_max_age_zero_read_of_a_lapsed_node_renews_and_is_served_in_one_request` | **FAIL** | pass |
+| 938 `A_max_age_zero_read_without_the_read_grant_is_denied_and_never_reaches_the_origin` (control) | pass | pass |
+| 939 `An_origin_refusing_the_renewal…` × {ItemDenied, OperationNotGranted, PermissionDeniedCall} | **FAIL** ×3 | pass |
+| 939 `An_unreachable_origin_for_a_lapsed_node_stays_retryable_not_denied` | **FAIL** (final read) | pass |
+| 939 `An_origin_that_stops_granting_history_answers_a_lapsed_history_read_access_denied_unsent` | added after (pre-fix: `BadResourceUnavailable` by #922 design) | pass |
+| 940 `A_write_to_a_lapsed_node_renews_on_demand_and_is_dispatched` | **FAIL** | pass |
+| 940 `A_write_to_a_lapsed_node_whose_origin_is_unreachable_is_retryable_and_unsent` | **FAIL** | pass |
+| 940 `A_write_to_a_lapsed_node_without_the_write_grant…` (control) | pass | pass |
+| 940 `Creating_a_monitored_item_on_a_lapsed_node_renews_on_demand_instead_of_denying` | **FAIL** | pass |
+| 940 `Creating_a_monitored_item_on_a_lapsed_node_whose_origin_is_unreachable_is_retryable` | **FAIL** | pass |
+| 940 `Creating_a_monitored_item…without_the_subscribe_grant…` (control) | **FAIL** (request fault, not per item) | pass |
+| 948 `A_redelivered_already_consumed_acquisition_leaves_no_orphan_candidate` | **FAIL** (1 orphan) | pass |
+
+Updated (behaviour changed by #938, first read now Good): `Sdk_mapped_read_preserves…`, `Cold_sdk_read_publishes…`,
+`New_primary_renews_same_monitored_item_after_a_prior_mapped_read(warmByRead)`, the #922 value-read test's second idle gap.
+
+Not live-gated (no rig run in this change).
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedDataAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedDataAccess.cs
index 6714f4446..eee7312e2 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedDataAccess.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedDataAccess.cs
@@ -32,6 +32,39 @@ public enum ProjectedLapseOutcome
Unavailable,
}
+/// #939: how an on-demand renewal of a lapsed projected lease ended.
+public enum ProjectedRenewalResult
+{
+ /// The lease was renewed and committed: retry the operation.
+ Renewed,
+ ///
+ /// The ORIGIN definitively refused it (the call answered PERMISSION_DENIED, the item Denied, or the metadata
+ /// no longer grants the operation): answer BadUserAccessDenied. Remembered briefly so a polling client does not
+ /// turn every request into an origin call.
+ ///
+ Refused,
+ /// Anything else (unreachable / unready origin, capacity, timeout, a changed shape or local fence): retryable.
+ Failed,
+}
+
+/// #938: how an immediate origin read of a projected node ended.
+public enum ProjectedOriginReadStatus
+{
+ /// The origin answered a fresh, authenticated sample: serve .
+ Served,
+ /// No unary capacity right now (nothing was sent): the caller may retry once another read completes.
+ NotAdmitted,
+ /// Sent (or started), but nothing servable came back in time: unreachable, not ready, stale, cancelled or refused.
+ NoValue,
+}
+
+/// #938: the outcome of .
+public readonly record struct ProjectedOriginRead(ProjectedOriginReadStatus Status, ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataValueSnapshot? Value)
+{
+ public static ProjectedOriginRead NotAdmitted => new(ProjectedOriginReadStatus.NotAdmitted, null);
+ public static ProjectedOriginRead NoValue => new(ProjectedOriginReadStatus.NoValue, null);
+}
+
/// Nonblocking local admission and bounded scheduling for projected data.
public interface IProjectedDataAccess
{
@@ -39,18 +72,30 @@ public interface IProjectedDataAccess
bool TryAcquire(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation, out IProjectedDemandLease? demand);
/// On success owns the demand through physical completion; otherwise the caller retains it.
bool ScheduleRead(IProjectedDemandLease demand, DataBudget budget, long requestStartedTimestamp);
+ ///
+ /// #938: reads the value from the origin NOW (a Part 4 maxAge the cache cannot satisfy, e.g. 0), within
+ /// counted from , admitted against the same unary
+ /// budget as ; the value is also published to the projection cache. Admission is decided
+ /// synchronously: a answer comes back as an already-completed task,
+ /// so a caller can retry it once another read finishes. The caller keeps ownership of .
+ ///
+ Task ReadNowAsync(IProjectedDemandLease demand, DataBudget budget, long requestStartedTimestamp,
+ CancellationToken cancellationToken) => Task.FromResult(ProjectedOriginRead.NotAdmitted);
Task WriteAsync(IProjectedDemandLease demand, object? value, DataBudget budget,
long requestStartedTimestamp, CancellationToken cancellationToken);
bool StartSubscription(IProjectedDemandLease demand, TimeSpan publishingInterval);
/// Requests a coalesced fresh authenticated snapshot without changing caller ownership.
bool RequestFreshSnapshot(IProjectedDemandLease demand) => false;
///
- /// #922: classifies a refused acquire of for (Read or HistoryRead) and,
- /// when the only reason is a lapsed lease the caller would otherwise be granted, starts (or joins) ONE bounded asynchronous
- /// exact renewal. Nonblocking and lock-free with respect to the caller: never call it, or wait on the task, under the
- /// node-manager Lock — the renewal commits through the SDK sink, which takes it.
+ /// #922: classifies a refused acquire of for (Read, HistoryRead and,
+ /// since #940, Write and Subscribe) and, when the only reason is a lapsed lease the caller would otherwise be granted,
+ /// starts (or joins) ONE bounded asynchronous exact renewal. A recent definitive origin refusal (#939) is
+ /// without another origin call. Nonblocking and lock-free with respect to the
+ /// caller: never call it, or wait on the task, under the node-manager Lock — the renewal commits through the SDK
+ /// sink, which takes it.
///
- ProjectedLapseOutcome RenewLapsed(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation, out Task? renewal)
+ ProjectedLapseOutcome RenewLapsed(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation,
+ out Task? renewal)
{
renewal = null;
return ProjectedLapseOutcome.Denied;
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.ProjectedOriginAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.ProjectedOriginAccess.cs
new file mode 100644
index 000000000..daaced182
--- /dev/null
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.ProjectedOriginAccess.cs
@@ -0,0 +1,334 @@
+using System.Diagnostics;
+using Opc.Ua;
+using Opc.Ua.Server;
+using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
+using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
+using DataValue = Opc.Ua.DataValue;
+using DataValueSnapshot = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataValueSnapshot;
+
+namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
+
+///
+/// #938 / #940: the projected (gRPC data connection) Read and CreateMonitoredItems seams that must AWAIT the origin — an
+/// immediate origin read for a maxAge the cache cannot satisfy, and the on-demand renewal of a lapsed metadata lease.
+/// Both run in the SDK's async dispatch ( / ,
+/// forwarded by AsyncNodeManagerAdapter) with NO node-manager Lock held and no request thread blocked, then hand
+/// the batch to the unchanged synchronous path, which skips what was served here and classifies the rest.
+///
+public sealed partial class OtOpcUaNodeManager : IReadAsyncNodeManager, ICreateMonitoredItemsAsyncNodeManager
+{
+ ///
+ /// #938: the longest one Read request waits for its projected origin work (lapse renewals, then the reads themselves),
+ /// further capped by the request's own deadline. Longer than a renewal's budget (3 s), so a renewal that completes is
+ /// followed by its read.
+ ///
+ internal static readonly TimeSpan ProjectedOriginReadWait = TimeSpan.FromSeconds(5);
+
+ /// #940: the longest a CreateMonitoredItems request waits for the renewal of lapsed projected items.
+ internal static readonly TimeSpan ProjectedSubscribeRenewalWait = TimeSpan.FromSeconds(4);
+
+ /// Kept back from the request deadline so the answer still reaches the client in time.
+ private static readonly TimeSpan ProjectedDeadlineMargin = TimeSpan.FromMilliseconds(250);
+
+ ///
+ async ValueTask IReadAsyncNodeManager.ReadAsync(OperationContext context, double maxAge, ArrayOf nodesToRead,
+ IList values, IList errors, CancellationToken cancellationToken)
+ {
+ if (SecurityFilteringActive && ProjectedDataAccess is { } access && IdentityOf(context) is { } identity)
+ {
+ try { await ReadProjectedFromOriginAsync(context, maxAge, nodesToRead, values, errors, access, identity, cancellationToken).ConfigureAwait(false); }
+ catch (Exception ex) when (ex is not OutOfMemoryException)
+ {
+ // Never fail the batch here: whatever was not served is answered by the synchronous path below.
+ }
+ }
+ Read(context, maxAge, nodesToRead, values, errors);
+ }
+
+ ///
+ /// Serves every projected Value read the cache cannot satisfy at (Part 4: 0 = read the
+ /// source) from a bounded, awaited origin read. A lapsed lease is renewed first (#922 classification, unchanged), so an idle
+ /// node is served in the same request. Reads are admitted against the unary budget and pumped as capacity frees up; what
+ /// is not served by the deadline is left to (or answered like) the synchronous path: BadWaitingForInitialData.
+ ///
+ private async Task ReadProjectedFromOriginAsync(OperationContext context, double maxAge, ArrayOf nodesToRead,
+ IList values, IList errors, IProjectedDataAccess access, RoleCarryingUserIdentity identity,
+ CancellationToken cancellationToken)
+ {
+ var wait = Bound(context, ProjectedOriginReadWait);
+ if (wait <= TimeSpan.Zero) return;
+ var deadline = Stopwatch.GetTimestamp() + (long)(wait.TotalSeconds * Stopwatch.Frequency);
+ using var stop = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, context.CancellationToken);
+ var pending = new Queue<(int Index, IProjectedDemandLease Demand)>();
+ var running = new List<(int Index, IProjectedDemandLease Demand, Task Read)>();
+ List<(int Index, Task Renewal)>? lapsed = null;
+ try
+ {
+ for (var ii = 0; ii < nodesToRead.Count; ii++)
+ {
+ var item = nodesToRead[ii];
+ if (item is null || item.Processed || item.AttributeId != Attributes.Value || !IsProjectedDescendant(item.NodeId)) continue;
+ if (TryAcquireProjectedRead(access, item.NodeId, identity, out var demand))
+ {
+ if (TryServeProjectedFromCache(item.NodeId, demand!, maxAge, out var cached))
+ {
+ demand!.Dispose();
+ values[ii] = cached; errors[ii] = null!; item.Processed = true;
+ continue;
+ }
+ pending.Enqueue((ii, demand!));
+ continue;
+ }
+ // #922 classification: only a lapse the caller would be granted starts a renewal; Denied / Unavailable are left to
+ // the synchronous path, which answers them exactly as before.
+ Task? renewal = null;
+ ProjectedLapseOutcome lapse;
+ try { lapse = access.RenewLapsed(item.NodeId, identity, DataOperations.Read, out renewal); }
+ catch (Exception) { lapse = ProjectedLapseOutcome.Denied; }
+ if (lapse == ProjectedLapseOutcome.Renewing && renewal is not null) (lapsed ??= []).Add((ii, renewal));
+ }
+ if (lapsed is not null)
+ {
+ await WhenAllUntil(lapsed.Select(x => (Task)x.Renewal), deadline, stop.Token).ConfigureAwait(false);
+ foreach (var (index, renewal) in lapsed)
+ {
+ // Still renewing, failed or refused: the synchronous path joins / reads the outcome (BadWaitingForInitialData /
+ // BadResourceUnavailable / BadUserAccessDenied). Renewed: read it now, in this request.
+ if (renewal is not { IsCompletedSuccessfully: true, Result: ProjectedRenewalResult.Renewed }) continue;
+ if (TryAcquireProjectedRead(access, nodesToRead[index].NodeId, identity, out var demand)) pending.Enqueue((index, demand!));
+ }
+ }
+ if (pending.Count == 0) return;
+ while (pending.Count > 0 || running.Count > 0)
+ {
+ // Admit as many as the unary budget takes now; NotAdmitted is decided synchronously (a completed task).
+ while (pending.Count > 0 && !stop.IsCancellationRequested)
+ {
+ var remaining = Remaining(deadline);
+ if (remaining <= TimeSpan.Zero) break;
+ var (index, demand) = pending.Peek();
+ var read = access.ReadNowAsync(demand, new DataBudget(remaining, 1, ProjectedOriginReadBytes), access.Clock.GetTimestamp(), stop.Token);
+ if (read.IsCompletedSuccessfully && read.Result.Status == ProjectedOriginReadStatus.NotAdmitted) break;
+ pending.Dequeue();
+ running.Add((index, demand, read));
+ }
+ if (Remaining(deadline) <= TimeSpan.Zero || stop.IsCancellationRequested) break;
+ if (running.Count == 0)
+ {
+ // Capacity is held by other requests: poll it briefly, within the deadline.
+ await Task.Delay(TimeSpan.FromMilliseconds(10), stop.Token).ConfigureAwait(false);
+ continue;
+ }
+ var tasks = running.Select(x => (Task)x.Read).ToList();
+ var any = Task.WhenAny(tasks);
+ if (await Task.WhenAny(any, Task.Delay(Remaining(deadline), stop.Token)).ConfigureAwait(false) != any) break;
+ for (var k = running.Count - 1; k >= 0; k--)
+ {
+ var (index, demand, read) = running[k];
+ if (!read.IsCompleted) continue;
+ running.RemoveAt(k);
+ Settle(index, demand, read);
+ }
+ }
+ }
+ catch (OperationCanceledException) { }
+ finally
+ {
+ // Out of time: an admitted read that has not answered is answered "waiting" (it was sent; scheduling another would only
+ // duplicate it); a read never admitted is left to the synchronous path, which answers it from cache or schedules it.
+ foreach (var (index, demand, read) in running)
+ {
+ if (read.IsCompleted) { Settle(index, demand, read); continue; }
+ demand.Dispose(); // cancels the read
+ values[index] = new DataValue(Variant.Null, StatusCodes.BadWaitingForInitialData);
+ nodesToRead[index].Processed = true;
+ }
+ foreach (var (_, demand) in pending) demand.Dispose();
+ }
+
+ void Settle(int index, IProjectedDemandLease demand, Task read)
+ {
+ try
+ {
+ // The caller's authority is re-checked at serve time: a grant revoked (or a node retired) while the read was in
+ // flight serves nothing here and is classified by the synchronous path instead.
+ if (!demand.IsValid) return;
+ values[index] = read is { IsCompletedSuccessfully: true, Result: { Status: ProjectedOriginReadStatus.Served, Value: { } snapshot } }
+ ? ProjectedDataValue(nodesToRead[index].NodeId, snapshot)
+ : new DataValue(Variant.Null, StatusCodes.BadWaitingForInitialData);
+ errors[index] = null!;
+ nodesToRead[index].Processed = true;
+ }
+ catch (Exception ex) when (ex is ArgumentException or InvalidCastException or OverflowException or InvalidOperationException)
+ {
+ values[index] = new DataValue(Variant.Null, StatusCodes.BadWaitingForInitialData);
+ errors[index] = null!;
+ nodesToRead[index].Processed = true;
+ }
+ finally { demand.Dispose(); }
+ }
+ }
+
+ /// The per-read byte reservation of an awaited origin read (as a scheduled read; narrowed to the adapter's limit).
+ private const long ProjectedOriginReadBytes = 4 * 1024 * 1024;
+
+ private static bool TryAcquireProjectedRead(IProjectedDataAccess access, NodeId nodeId, RoleCarryingUserIdentity identity,
+ out IProjectedDemandLease? demand)
+ {
+ demand = null;
+ try
+ {
+ if (access.TryAcquire(nodeId, identity, DataOperations.Read, out demand) && demand is { IsValid: true }) return true;
+ }
+ catch (Exception ex) when (ex is not OutOfMemoryException) { }
+ demand?.Dispose(); demand = null;
+ return false;
+ }
+
+ ///
+ /// The cached projected value of when it is bound to 's serving identity and
+ /// generation, still proven, and no older than ms (Part 4: maxAge = 0 is never served from cache).
+ ///
+ private bool TryServeProjectedFromCache(NodeId nodeId, IProjectedDemandLease demand, double maxAge, out DataValue value)
+ {
+ value = default;
+ if (!(maxAge > 0)) return false;
+ // Total: a cached value that cannot be served (shape conversion, a clock fault) is simply "not served from cache", so a
+ // caller holding a demand always keeps ownership of it.
+ try { return TryServeProjectedFromCacheCore(nodeId, demand, maxAge, out value); }
+ catch (Exception ex) when (ex is ArgumentException or InvalidCastException or OverflowException or InvalidOperationException)
+ {
+ value = default;
+ return false;
+ }
+ }
+
+ private bool TryServeProjectedFromCacheCore(NodeId nodeId, IProjectedDemandLease demand, double maxAge, out DataValue value)
+ {
+ value = default;
+ ProjectedValueWrite? cached;
+ var byteArray = false;
+ lock (Lock)
+ {
+ _projectedSamples.TryGetValue(nodeId, out cached);
+ if (_projectedVariables.TryGetValue(nodeId, out var mapped))
+ byteArray = mapped.Metadata.ValueKind == DataValueKind.Array && mapped.Metadata.ArrayElementKind == DataValueKind.UInt8;
+ }
+ if (cached is null || !cached.Proof.IsValid || !demand.IsValid || cached.Serving != demand.Serving ||
+ cached.ProjectionGeneration != demand.ProjectionGeneration ||
+ !cached.OriginAgeBounds.Advance(cached.Proof.Clock.GetElapsedTime(cached.ReceivedTimestamp, cached.Proof.Clock.GetTimestamp()))
+ .IsFresh(TimeSpan.FromMilliseconds(Math.Min(maxAge, TimeSpan.MaxValue.TotalMilliseconds)))) return false;
+ var candidate = new DataValue(SdkValueBoundary.FromClr(cached.Snapshot.Value, byteArray), cached.Snapshot.StatusCode,
+ (DateTimeUtc)(cached.Snapshot.SourceTimestampUtc ?? DateTime.MinValue),
+ (DateTimeUtc)(cached.Snapshot.ServerTimestampUtc ?? DateTime.MinValue));
+ if (!cached.Proof.IsValid || !demand.IsValid) return false;
+ value = candidate;
+ return true;
+ }
+
+ /// An origin sample read for this request, as the SDK DataValue the projected node would carry.
+ private DataValue ProjectedDataValue(NodeId nodeId, DataValueSnapshot snapshot)
+ {
+ var byteArray = false;
+ lock (Lock)
+ if (_projectedVariables.TryGetValue(nodeId, out var mapped))
+ byteArray = mapped.Metadata.ValueKind == DataValueKind.Array && mapped.Metadata.ArrayElementKind == DataValueKind.UInt8;
+ return new DataValue(SdkValueBoundary.FromClr(snapshot.Value, byteArray), snapshot.StatusCode,
+ (DateTimeUtc)(snapshot.SourceTimestampUtc ?? DateTime.MinValue), (DateTimeUtc)(snapshot.ServerTimestampUtc ?? DateTime.MinValue));
+ }
+
+ ///
+ async ValueTask ICreateMonitoredItemsAsyncNodeManager.CreateMonitoredItemsAsync(OperationContext context, uint subscriptionId,
+ double publishingInterval, TimestampsToReturn timestampsToReturn, ArrayOf itemsToCreate,
+ IList errors, IList filterErrors, IList monitoredItems, bool createDurable,
+ MonitoredItemIdFactory monitoredItemIdFactory, CancellationToken cancellationToken)
+ {
+ if (SecurityFilteringActive && ProjectedDataAccess is { } access && IdentityOf(context) is { } identity)
+ {
+ try { await RenewLapsedProjectedItemsAsync(context, itemsToCreate, access, identity, cancellationToken).ConfigureAwait(false); }
+ catch (Exception ex) when (ex is not OutOfMemoryException)
+ {
+ // Never fail the batch here: the synchronous create classifies every projected item itself.
+ }
+ }
+ CreateMonitoredItems(context, subscriptionId, publishingInterval, timestampsToReturn, itemsToCreate, errors, filterErrors,
+ monitoredItems, createDurable, monitoredItemIdFactory);
+ }
+
+ ///
+ /// #940: starts (or joins) the on-demand renewal of every projected Value item whose lease lapsed and that the caller would be
+ /// granted Subscribe on, and waits for them (once per request, bounded, no Lock held), so the synchronous create that
+ /// follows acquires them. Anything not renewed by then is classified per item by .
+ ///
+ private async Task RenewLapsedProjectedItemsAsync(OperationContext context, ArrayOf itemsToCreate,
+ IProjectedDataAccess access, RoleCarryingUserIdentity identity, CancellationToken cancellationToken)
+ {
+ List>? renewing = null;
+ for (var ii = 0; ii < itemsToCreate.Count; ii++)
+ {
+ var item = itemsToCreate[ii];
+ if (item is null || item.Processed || item.ItemToMonitor?.AttributeId != Attributes.Value ||
+ !IsProjectedDescendant(item.ItemToMonitor.NodeId)) continue;
+ Task? renewal = null;
+ ProjectedLapseOutcome lapse;
+ try { lapse = access.RenewLapsed(item.ItemToMonitor.NodeId, identity, DataOperations.Subscribe, out renewal); }
+ catch (Exception) { lapse = ProjectedLapseOutcome.Denied; }
+ if (lapse == ProjectedLapseOutcome.Renewing && renewal is not null) (renewing ??= []).Add(renewal);
+ }
+ if (renewing is null) return;
+ var wait = Bound(context, ProjectedSubscribeRenewalWait);
+ if (wait <= TimeSpan.Zero) return;
+ using var stop = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, context.CancellationToken);
+ try
+ {
+ await WhenAllUntil(renewing, Stopwatch.GetTimestamp() + (long)(wait.TotalSeconds * Stopwatch.Frequency), stop.Token)
+ .ConfigureAwait(false);
+ }
+ catch (OperationCanceledException) { }
+ }
+
+ ///
+ /// #940: why a projected Value monitored item cannot be created right now, or null when it can be acquired. A lapse the caller
+ /// is granted (renewing, back-off, capacity) is BadResourceUnavailable — retryable, as for Read; a real ACL denial,
+ /// a revoked/removed node and a held origin refusal (#939) are BadUserAccessDenied. Never call under Lock.
+ ///
+ private static StatusCode? ProjectedSubscribeRefusal(IProjectedDataAccess access, NodeId nodeId, RoleCarryingUserIdentity identity)
+ {
+ IProjectedDemandLease? probe = null;
+ try
+ {
+ if (access.TryAcquire(nodeId, identity, DataOperations.Subscribe, out probe) && probe is { IsValid: true }) return null;
+ }
+ catch (Exception ex) when (ex is not OutOfMemoryException) { }
+ finally { probe?.Dispose(); }
+ ProjectedLapseOutcome lapse;
+ try { lapse = access.RenewLapsed(nodeId, identity, DataOperations.Subscribe, out _); }
+ catch (Exception) { lapse = ProjectedLapseOutcome.Denied; }
+ return lapse == ProjectedLapseOutcome.Denied ? StatusCodes.BadUserAccessDenied : StatusCodes.BadResourceUnavailable;
+ }
+
+
+ private static TimeSpan Bound(OperationContext context, TimeSpan cap)
+ {
+ var deadline = context.OperationDeadline;
+ if (deadline == DateTime.MaxValue || deadline <= DateTime.MinValue) return cap;
+ var left = deadline - DateTime.UtcNow - ProjectedDeadlineMargin;
+ return left < cap ? left : cap;
+ }
+
+ private static TimeSpan Remaining(long deadline)
+ {
+ var ticks = deadline - Stopwatch.GetTimestamp();
+ return ticks <= 0 ? TimeSpan.Zero : TimeSpan.FromSeconds((double)ticks / Stopwatch.Frequency);
+ }
+
+ private static async Task WhenAllUntil(IEnumerable tasks, long deadline, CancellationToken cancellationToken)
+ {
+ var all = Task.WhenAll(tasks);
+ var remaining = Remaining(deadline);
+ if (remaining <= TimeSpan.Zero) return;
+ try { await all.WaitAsync(remaining, cancellationToken).ConfigureAwait(false); }
+ catch (TimeoutException) { }
+ catch (Exception ex) when (ex is not OperationCanceledException and not OutOfMemoryException) { }
+ }
+}
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs
index a3dac66b4..d38fe328d 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs
@@ -6351,24 +6351,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
? StatusCodes.BadWaitingForInitialData : StatusCodes.BadResourceUnavailable);
continue;
}
- ProjectedValueWrite? cached;
- var byteArray = false;
- lock (Lock)
- {
- _projectedSamples.TryGetValue(projected.NodeId, out cached);
- if (_projectedVariables.TryGetValue(projected.NodeId, out var mapped))
- byteArray = mapped.Metadata.ValueKind == DataValueKind.Array && mapped.Metadata.ArrayElementKind == DataValueKind.UInt8;
- }
- if (cached is not null && cached.Proof.IsValid && demand.IsValid && cached.Serving == demand.Serving &&
- cached.ProjectionGeneration == demand.ProjectionGeneration && maxAge > 0 &&
- cached.OriginAgeBounds.Advance(cached.Proof.Clock.GetElapsedTime(cached.ReceivedTimestamp,
- cached.Proof.Clock.GetTimestamp())).IsFresh(TimeSpan.FromMilliseconds(Math.Min(maxAge, TimeSpan.MaxValue.TotalMilliseconds))))
- {
- var value = new DataValue(SdkValueBoundary.FromClr(cached.Snapshot.Value, byteArray), cached.Snapshot.StatusCode,
- (DateTimeUtc)(cached.Snapshot.SourceTimestampUtc ?? DateTime.MinValue),
- (DateTimeUtc)(cached.Snapshot.ServerTimestampUtc ?? DateTime.MinValue));
- if (cached.Proof.IsValid && demand.IsValid) { values[ii] = value; continue; }
- }
+ if (TryServeProjectedFromCache(projected.NodeId, demand, maxAge, out var cachedValue)) { values[ii] = cachedValue; continue; }
var started = access.Clock.GetTimestamp();
var budget = new DataBudget(TimeSpan.FromSeconds(5), 1, 4 * 1024 * 1024);
if (access.ScheduleRead(demand, budget, started)) demand = null; // ownership transfers only on admission
@@ -6585,8 +6568,20 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
var item = itemsToCreate[ii];
var target = item.ItemToMonitor?.NodeId;
if (item.Processed || !OwnsNamespace(target)) continue;
- if (target is { } projected && IsProjectedDescendant(projected) && identity is not null && ProjectedDataAccess is not null &&
- item.ItemToMonitor?.AttributeId == Attributes.Value) continue;
+ if (target is { } projected && IsProjectedDescendant(projected) && identity is not null && ProjectedDataAccess is { } access &&
+ item.ItemToMonitor?.AttributeId == Attributes.Value)
+ {
+ // #940: a refused projected item is answered PER ITEM here (outside Lock), classified like Read: a lapse the
+ // caller is granted is retryable (its renewal was awaited by CreateMonitoredItemsAsync, or starts now), only a
+ // real refusal is BadUserAccessDenied. Thrown from the item manager instead, it faulted the whole request.
+ if (ProjectedSubscribeRefusal(access, projected, identity) is { } refusal)
+ {
+ item.Processed = true;
+ errors[ii] = refusal;
+ if (refusal.Code == StatusCodes.BadUserAccessDenied.Code) denied++;
+ }
+ continue;
+ }
if (Permits(identity, OpcUaOperation.CreateMonitoredItems, target!.Value)) continue;
item.Processed = true;
@@ -8988,8 +8983,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
var vetoes = new ServiceResult?[nodesToProcess.Count];
var lapses = new ProjectedLapseOutcome?[nodesToProcess.Count];
- var renewalTasks = new Task?[nodesToProcess.Count];
- List>? renewals = null;
+ var renewalTasks = new Task?[nodesToProcess.Count];
+ List>? renewals = null;
var access = ProjectedDataAccess;
for (var i = 0; i < nodesToProcess.Count; i++)
{
@@ -8998,7 +8993,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
// #922: a projected node refused only because its metadata lease lapsed is renewed within this request — never
// answered access-denied for the lapse. A caller without the grant is classified Denied and never reaches the origin.
if (vetoes[i] is null || identity is null || access is null || !IsProjectedDescendant(handle.NodeId)) continue;
- Task? renewal = null;
+ Task? renewal = null;
try { lapses[i] = access.RenewLapsed(handle.NodeId, identity, DataOperations.HistoryRead, out renewal); }
catch (Exception) { lapses[i] = ProjectedLapseOutcome.Denied; renewal = null; }
renewalTasks[i] = renewal;
@@ -9041,7 +9036,9 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
// #922 review: the lapse classification and the veto are two authorities (DataOperationPolicy / DataPlaneAuthorizer).
// A renewal that SUCCEEDED and is still vetoed is a real refusal, never a retryable one.
- if (lapses[i] is ProjectedLapseOutcome.Renewing && renewalTasks[i] is { IsCompletedSuccessfully: true, Result: true })
+ // #939: so is a renewal the ORIGIN refused (its operation is no longer granted) — BadUserAccessDenied, not retryable.
+ if (lapses[i] is ProjectedLapseOutcome.Renewing && renewalTasks[i] is
+ { IsCompletedSuccessfully: true, Result: ProjectedRenewalResult.Renewed or ProjectedRenewalResult.Refused })
lapses[i] = ProjectedLapseOutcome.Denied;
if (lapses[i] is ProjectedLapseOutcome.Renewing or ProjectedLapseOutcome.Unavailable)
{
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaSdkServer.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaSdkServer.cs
index e7a72a311..1490b440a 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaSdkServer.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaSdkServer.cs
@@ -411,11 +411,22 @@ public sealed class OtOpcUaSdkServer : StandardServer
{
if (caller is null || access is null || !access.TryAcquire(item.NodeId, caller, DataOperations.Write, out demand) ||
demand is null || !demand.IsValid)
- { result[i] = StatusCodes.BadUserAccessDenied; continue; }
+ {
+ demand?.Dispose(); demand = null;
+ // #940: a lapsed metadata lease is not an access denial — the same classification + on-demand renewal as
+ // Read (#922). A caller granted the write waits (bounded) for the renewal and is then dispatched; a real
+ // ACL denial, a revoked node and an origin refusal (#939) stay BadUserAccessDenied.
+ var (acquired, refusal) = caller is null || access is null
+ ? (null, StatusCodes.BadUserAccessDenied)
+ : await AcquireLapsedProjectedWriteAsync(access, item.NodeId, caller, requestHeader, requestLifetime.CancellationToken)
+ .ConfigureAwait(false);
+ if (acquired is null) { result[i] = refusal; continue; }
+ demand = acquired;
+ }
if (!manager.CanDispatchProjectedWrite()) { result[i] = StatusCodes.BadInvalidState; continue; }
var milliseconds = requestHeader is { TimeoutHint: > 0 } ? Math.Min(requestHeader.TimeoutHint, 30000u) : 30000u;
var budget = new DataBudget(TimeSpan.FromMilliseconds(milliseconds), 1, 4 * 1024 * 1024);
- var outcome = await access.WriteAsync(demand, SdkValueBoundary.ToClr(item.Value.WrappedValue), budget, started,
+ var outcome = await access!.WriteAsync(demand, SdkValueBoundary.ToClr(item.Value.WrappedValue), budget, started,
requestLifetime.CancellationToken).ConfigureAwait(false);
result[i] = outcome.State switch
{
@@ -438,7 +449,44 @@ public sealed class OtOpcUaSdkServer : StandardServer
finally { OnRequestComplete(context); }
}
- private static readonly byte[] ProjectedCursorPrefix = [0x4f, 0x54, 0x50, 0x43, 0x55, 0x41, 0x50, 0x31];
+ /// #940: the longest a projected Write waits for the on-demand renewal of a lapsed lease (also capped by its timeout hint).
+ internal static readonly TimeSpan ProjectedWriteRenewalWait = TimeSpan.FromSeconds(4);
+
+ ///
+ /// #940: classifies a refused projected write acquire. Denied ⇒ BadUserAccessDenied; a lapse the caller is granted
+ /// renews (bounded by and the request's timeout hint, no lock held) and is then
+ /// re-acquired; a renewal that cannot complete or start ⇒ BadResourceUnavailable (retryable, nothing dispatched);
+ /// an origin refusal or a renewed node that is still refused ⇒ BadUserAccessDenied.
+ ///
+ private static async Task<(IProjectedDemandLease? Demand, StatusCode Refusal)> AcquireLapsedProjectedWriteAsync(IProjectedDataAccess access,
+ NodeId nodeId, RoleCarryingUserIdentity caller, RequestHeader? requestHeader, CancellationToken cancellationToken)
+ {
+ ProjectedLapseOutcome lapse;
+ Task? renewal = null;
+ try { lapse = access.RenewLapsed(nodeId, caller, DataOperations.Write, out renewal); }
+ catch (Exception) { lapse = ProjectedLapseOutcome.Denied; }
+ if (lapse == ProjectedLapseOutcome.Denied) return (null, StatusCodes.BadUserAccessDenied);
+ if (lapse != ProjectedLapseOutcome.Renewing || renewal is null) return (null, StatusCodes.BadResourceUnavailable);
+ var wait = ProjectedWriteRenewalWait;
+ if (requestHeader is { TimeoutHint: > 0 } && TimeSpan.FromMilliseconds(requestHeader.TimeoutHint) / 2 < wait)
+ wait = TimeSpan.FromMilliseconds(requestHeader.TimeoutHint) / 2; // leave the write itself the other half
+ try { await renewal.WaitAsync(wait, cancellationToken).ConfigureAwait(false); }
+ catch (Exception ex) when (ex is TimeoutException or OperationCanceledException) { return (null, StatusCodes.BadResourceUnavailable); }
+ if (!renewal.IsCompletedSuccessfully) return (null, StatusCodes.BadResourceUnavailable);
+ if (renewal.Result == ProjectedRenewalResult.Failed) return (null, StatusCodes.BadResourceUnavailable);
+ if (renewal.Result == ProjectedRenewalResult.Refused) return (null, StatusCodes.BadUserAccessDenied);
+ IProjectedDemandLease? demand = null;
+ try
+ {
+ if (access.TryAcquire(nodeId, caller, DataOperations.Write, out demand) && demand is { IsValid: true }) return (demand, StatusCodes.Good);
+ }
+ catch (Exception ex) when (ex is not OutOfMemoryException) { }
+ demand?.Dispose();
+ // Renewed and still refused: the two authorities disagree only on a real refusal (#922 review rule).
+ return (null, StatusCodes.BadUserAccessDenied);
+ }
+
+ private static readonly byte[] ProjectedCursorPrefix =[0x4f, 0x54, 0x50, 0x43, 0x55, 0x41, 0x50, 0x31];
private readonly object _projectedBrowseLock = new();
private readonly Dictionary _projectedBrowseCursors = new();
private int _maxProjectedBrowseCursors = 256;
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/WarmStandby.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/WarmStandby.cs
index c0fc1f500..c6af7743b 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/WarmStandby.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/WarmStandby.cs
@@ -348,6 +348,8 @@ internal sealed class OrdinaryTagItemManager(IAsyncNodeManager nodeManager, ISer
ProjectedValueWrite? initialSample = null;
ProjectedVariableDefinition? definition = null;
if (projected && !owner.TryAcquireProjectedItem(context, handle.NodeId, publishingInterval, out demand, out initialSample, out definition))
+ // #940: refusals known before the create are answered per item by OtOpcUaNodeManager.CreateMonitoredItems (lapse ⇒
+ // retryable); this is the race-only remainder (the authority changed in between).
throw new ServiceResultException(StatusCodes.BadUserAccessDenied);
uint? reservedId = null;
@@ -472,6 +474,27 @@ internal sealed class ProjectedMonitoredItem : MonitoredItem
private LossControl? _queuedLoss;
internal Action? AfterLossDequeueForTests;
private long _candidateBytes;
+ // #948: the acquisition whose candidate an SDK notification last consumed, while that is still the value the SDK item last
+ // queued (no other candidate, loss or queue reset since). Kept without the sample (no value retained): a false match only
+ // costs an unproven notification + a baseline request, never a borrowed proof.
+ private ConsumedAcquisition? _lastConsumed;
+ private sealed record ConsumedAcquisition(SourceBinding Binding, object SourceIdentity, TimeProvider Clock, long SourceVersion,
+ DataRealm Realm, string LocalIdentifier, long ProjectionGeneration, ServingIdentity Serving, uint StatusCode,
+ DateTime? SourceTimestampUtc, DateTime? ServerTimestampUtc)
+ {
+ internal static ConsumedAcquisition? Of(SourceBinding binding, ProjectedValueWrite sample) =>
+ sample.SourceVersion is > 0 and var version
+ ? new(binding, sample.Proof.SourceIdentity, sample.Proof.Clock, version, sample.Realm, sample.LocalIdentifier,
+ sample.ProjectionGeneration, sample.Serving, sample.Snapshot.StatusCode, sample.Snapshot.SourceTimestampUtc,
+ sample.Snapshot.ServerTimestampUtc)
+ : null;
+ internal bool Matches(SourceBinding? binding, ProjectedValueWrite sample) =>
+ ReferenceEquals(Binding, binding) && sample.SourceVersion == SourceVersion &&
+ ReferenceEquals(sample.Proof.SourceIdentity, SourceIdentity) && ReferenceEquals(sample.Proof.Clock, Clock) &&
+ sample.Realm == Realm && sample.LocalIdentifier == LocalIdentifier && sample.ProjectionGeneration == ProjectionGeneration &&
+ sample.Serving == Serving && sample.Snapshot.StatusCode == StatusCode &&
+ sample.Snapshot.SourceTimestampUtc == SourceTimestampUtc && sample.Snapshot.ServerTimestampUtc == ServerTimestampUtc;
+ }
private bool _needsSnapshot;
private int _snapshotRequested;
private SourceBinding? _binding;
@@ -527,6 +550,17 @@ internal sealed class ProjectedMonitoredItem : MonitoredItem
if (!FreshForDemand(sample)) return true;
_needsSnapshot = true;
}
+ else if (_candidates.Count == 0 && _queuedLoss is null && _lastConsumed is { } consumed && consumed.Matches(original, sample))
+ {
+ // #948: this item already DELIVERED this acquisition and nothing has been queued since, so the SDK item's last
+ // value is this one: re-applying it raises no notification, and a candidate for it would never be consumed
+ // (it would hold its shared budget charge until the binding changed). Renew health evidence only.
+ if (!FreshForDemand(sample)) return true;
+ var successor = new SampleEvidence(original!, sample.Proof, sample.OriginAgeBounds, sample.ReceivedTimestamp);
+ _latestEvidence?.Clear();
+ _latestEvidence = successor; _reportedLoss = null;
+ return false;
+ }
}
if (!sameSource || (_needsSnapshot && sample.IsCompleteSnapshot))
{
@@ -606,7 +640,7 @@ internal sealed class ProjectedMonitoredItem : MonitoredItem
{
if (MonitoringMode == MonitoringMode.Disabled || _queuedLoss is not null || ReferenceEquals(_reportedLoss, loss.Evidence) || _retired != 0 || !ReferenceEquals(_latestEvidence, loss.Evidence) ||
!ReferenceEquals(_binding, loss.Evidence.Binding)) return;
- _queuedLoss = loss;
+ _queuedLoss = loss; _lastConsumed = null;
try { QueueValue(new DataValue(Variant.Null, StatusCodes.BadNoCommunication, DateTimeUtc.MinValue, DateTimeUtc.MinValue),
new ServiceResult(StatusCodes.BadNoCommunication), ignoreFilters: true); }
catch (Exception) { _queuedLoss = null; }
@@ -670,7 +704,7 @@ internal sealed class ProjectedMonitoredItem : MonitoredItem
private void ClearCandidates()
{
foreach (var candidate in _candidates) candidate.Charge.Dispose();
- _candidates.Clear(); _candidateBytes = 0;
+ _candidates.Clear(); _candidateBytes = 0; _lastConsumed = null;
}
internal void RequestBaseline()
{
@@ -704,7 +738,8 @@ internal sealed class ProjectedMonitoredItem : MonitoredItem
_definition is { } definition && _owner.IsProjectedDefinitionCurrent(_nodeId, definition);
internal void ResetHealthMonitoringMode()
{
- lock (_bindingSync) { _queuedLoss = null; _reportedLoss = null; }
+ // A client mode change can reset the SDK item's last value: a later re-delivery may notify again, so it needs a candidate.
+ lock (_bindingSync) { _queuedLoss = null; _reportedLoss = null; _lastConsumed = null; }
}
internal void Retire()
{
@@ -785,10 +820,11 @@ internal sealed class ProjectedMonitoredItem : MonitoredItem
{
ProjectedDeliveryDiagnostics.Count(ProjectedDeliveryDiagnostics.Event.CandidateUnique);
var matched = matching[0]; _candidates.Remove(matched); _candidateBytes -= matched.Bytes;
+ _lastConsumed = ConsumedAcquisition.Of(matched.Binding, matched.Sample);
evidence = matched.Binding.Capture(matched.Sample.Proof, matched.Sample.OriginAgeBounds, matched.Sample.ReceivedTimestamp);
matched.Charge.Dispose();
}
- else { ProjectedDeliveryDiagnostics.Count(matching.Length == 0 ? ProjectedDeliveryDiagnostics.Event.CandidateMissing : ProjectedDeliveryDiagnostics.Event.CandidateAmbiguous); _needsSnapshot = true; }
+ else { ProjectedDeliveryDiagnostics.Count(matching.Length == 0 ? ProjectedDeliveryDiagnostics.Event.CandidateMissing : ProjectedDeliveryDiagnostics.Event.CandidateAmbiguous); _needsSnapshot = true; _lastConsumed = null; }
}
if (evidence is null) RequestBaseline();
var originalSample = evidence;
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 0ecc07b47..2a0d5556d 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs
@@ -208,11 +208,15 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
// a metadata call. Renewals never use the unary budget (that would starve cold reads, writes and subscription renewals):
// they queue — at most MaxQueuedLapseRenewals — for the resolver's own on-demand pool, so a batch of N lapsed nodes renews
// them all, a few at a time.
- private readonly Dictionary<(DataRealm Realm, string LocalIdentifier, DataOperations Operation), Task> _lapseRenewals = new();
- private readonly Dictionary<(DataRealm Realm, string LocalIdentifier, DataOperations Operation), long> _lapseRenewalBackoff = new();
+ private readonly Dictionary<(DataRealm Realm, string LocalIdentifier, DataOperations Operation), Task> _lapseRenewals = new();
+ // #939: a failed renewal backs off briefly (Refused = false ⇒ retryable); a definitive ORIGIN refusal is held longer and
+ // answered Denied (BadUserAccessDenied) without another origin call until it expires.
+ private readonly Dictionary<(DataRealm Realm, string LocalIdentifier, DataOperations Operation), (long Until, bool Refused)> _lapseRenewalBackoff = new();
private const int MaxLapseRenewalBackoffEntries = 4096;
internal const int MaxQueuedLapseRenewals = 64;
internal static readonly TimeSpan LapseRenewalBackoff = TimeSpan.FromMilliseconds(250);
+ /// #939: how long a definitive origin refusal of a lapsed node's renewal is answered BadUserAccessDenied unsent.
+ internal static readonly TimeSpan LapseRefusalHold = TimeSpan.FromSeconds(5);
/// The whole on-demand renewal, pool wait included; clearly shorter than the longest a HistoryRead waits for it.
internal static readonly TimeSpan LapseRenewalTimeout = TimeSpan.FromSeconds(3);
/// One metadata item and its capability probe: never a multi-MiB unary reservation.
@@ -221,11 +225,12 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
private int _lapseRenewalsStarted;
///
- public ProjectedLapseOutcome RenewLapsed(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation, out Task? renewal)
+ public ProjectedLapseOutcome RenewLapsed(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation,
+ out Task? renewal)
{
renewal = null;
- if (caller is null || operation is not (DataOperations.Read or DataOperations.HistoryRead) || _renewalSink is not { } sink ||
- _catalog is not RemoteNamespaceResolver resolver) return ProjectedLapseOutcome.Denied;
+ if (caller is null || operation is not (DataOperations.Read or DataOperations.HistoryRead or DataOperations.Write or DataOperations.Subscribe) ||
+ _renewalSink is not { } sink || _catalog is not RemoteNamespaceResolver resolver) return ProjectedLapseOutcome.Denied;
try
{
// The SDK node must still be live, and either it or its catalog proof must have lapsed — a refusal of a node whose
@@ -235,9 +240,13 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
definition.AuthorityIsCurrent() && _catalog.IsUsableProof(proof) ||
proof.Generation != definition.ProjectionGeneration || !MetadataMatches(proof.Metadata, definition.Metadata) ||
proof.Metadata.View.MappingId is not { } mapping || _connectionForMapping(mapping) is not { Length: > 0 } ||
- (operation == DataOperations.Read && proof.MaximumSampleAge <= TimeSpan.Zero) ||
+ (operation is DataOperations.Read or DataOperations.Subscribe && proof.MaximumSampleAge <= TimeSpan.Zero) ||
(operation == DataOperations.HistoryRead && (!definition.Historizing || !ProjectedHistoryAccess.Advertises(proof))))
return ProjectedLapseOutcome.Denied;
+ // #940: a write is also gated on this node's local write role — a node that may not write refuses whatever the lease
+ // says, exactly as TryAcquire does.
+ if (operation == DataOperations.Write && _localWriteRole() is not { Allowed: true, Generation: > 0 })
+ return ProjectedLapseOutcome.Denied;
var identity = new DataCallerIdentity(caller.Principal, caller.ApiKeyId, caller.CredentialVersion, caller.CredentialExpiresUtc);
// The same grant the served operation needs, judged on everything but the lapsed lease: a caller without it is
// refused exactly as before, and never causes an origin call.
@@ -245,24 +254,25 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
return ProjectedLapseOutcome.Denied;
var key = (definition.Realm, definition.LocalIdentifier, operation);
var budget = new DataBudget(LapseRenewalTimeout, 1, Math.Min(LapseRenewalBytes, _limits.MaxUnaryBytes));
- TaskCompletionSource started;
+ TaskCompletionSource started;
lock (_sync)
{
if (_disposed) return ProjectedLapseOutcome.Unavailable;
if (_lapseRenewals.TryGetValue(key, out var running)) { renewal = running; return ProjectedLapseOutcome.Renewing; }
var now = Clock.GetTimestamp();
- if (_lapseRenewalBackoff.TryGetValue(key, out var until))
+ if (_lapseRenewalBackoff.TryGetValue(key, out var held))
{
- if (now < until) return ProjectedLapseOutcome.Unavailable;
+ // #939: a recent definitive origin refusal is an access denial, answered without another origin call.
+ if (now < held.Until) return held.Refused ? ProjectedLapseOutcome.Denied : ProjectedLapseOutcome.Unavailable;
_lapseRenewalBackoff.Remove(key);
}
if (_lapseRenewals.Count >= MaxQueuedLapseRenewals) return ProjectedLapseOutcome.Unavailable;
- started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
_lapseRenewals.Add(key, started.Task);
}
Interlocked.Increment(ref _lapseRenewalsStarted);
// Never on the caller's thread: the renewal awaits the origin and commits through the SDK sink (node-manager Lock).
- _ = Task.Run(() => RunLapseRenewalAsync(resolver, sink, key, proof, definition, nodeId, caller, identity, operation, budget, started));
+ _ = Task.Run(() => RunLapseRenewalAsync(resolver, sink, key, proof, definition, nodeId, identity, operation, budget, started));
renewal = started.Task;
return ProjectedLapseOutcome.Renewing;
}
@@ -271,52 +281,42 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
private async Task RunLapseRenewalAsync(RemoteNamespaceResolver resolver, IProjectedNamespacePageSink sink,
(DataRealm Realm, string LocalIdentifier, DataOperations Operation) key, ProjectedNodeProof proof, ProjectedVariableDefinition definition, NodeId nodeId,
- RoleCarryingUserIdentity caller, DataCallerIdentity identity, DataOperations operation, DataBudget budget, TaskCompletionSource completion)
+ DataCallerIdentity identity, DataOperations operation, DataBudget budget, TaskCompletionSource completion)
{
- var renewed = false;
+ var result = ProjectedRenewalResult.Failed;
try
{
- renewed = await resolver.RenewExactAsync(proof, definition, nodeId, identity, null, sink, budget,
+ result = await resolver.RenewExactOutcomeAsync(proof, definition, nodeId, identity, null, sink, budget,
() => { lock (_sync) return !_disposed; }, CancellationToken.None, overlap: false,
authorizeAs: Operation(operation), required: operation, onDemand: true).ConfigureAwait(false);
}
- catch (Exception ex) when (ex is not OutOfMemoryException) { renewed = false; }
+ catch (Exception ex) when (ex is not OutOfMemoryException) { result = ProjectedRenewalResult.Failed; }
finally
{
lock (_sync)
{
_lapseRenewals.Remove(key);
- if (!renewed && !_disposed)
+ if (result != ProjectedRenewalResult.Renewed && !_disposed)
{
if (_lapseRenewalBackoff.Count >= MaxLapseRenewalBackoffEntries) EvictLapseBackoffLocked();
- var delay = (long)(LapseRenewalBackoff.TotalSeconds * Clock.TimestampFrequency);
- _lapseRenewalBackoff[key] = Clock.GetTimestamp() + Math.Max(1, delay);
+ var refused = result == ProjectedRenewalResult.Refused;
+ var delay = (long)((refused ? LapseRefusalHold : LapseRenewalBackoff).TotalSeconds * Clock.TimestampFrequency);
+ _lapseRenewalBackoff[key] = (Clock.GetTimestamp() + Math.Max(1, delay), refused);
}
}
}
- // A Read answered retryable while the lease renewed: fetch the value now, through the ordinary authorized path, so the
- // client's retry is served from the fresh sample instead of starting another cold read.
- if (renewed && operation == DataOperations.Read)
- {
- IProjectedDemandLease? demand = null;
- try
- {
- if (TryAcquire(nodeId, caller, DataOperations.Read, out demand) && demand is not null &&
- ScheduleRead(demand, new DataBudget(LapseRenewalTimeout, 1, ProjectedReadBytes), Clock.GetTimestamp())) demand = null;
- }
- catch (Exception ex) when (ex is not OutOfMemoryException) { }
- finally { demand?.Dispose(); }
- }
- completion.TrySetResult(renewed);
+ // #938: the Read that started this renewal reads the origin itself, within its own request, once it commits — so the
+ // renewal no longer schedules a separate cache-warming read.
+ completion.TrySetResult(result);
}
// Full map (rare): drop the expired entries; if none expired, the one that expires first — never the whole map, which would
// let every node's back-off lapse at once.
private void EvictLapseBackoffLocked()
{
var now = Clock.GetTimestamp();
- var expired = _lapseRenewalBackoff.Where(entry => entry.Value <= now).Select(entry => entry.Key).ToArray();
+ var expired = _lapseRenewalBackoff.Where(entry => entry.Value.Until <= now).Select(entry => entry.Key).ToArray();
foreach (var key in expired) _lapseRenewalBackoff.Remove(key);
- if (expired.Length == 0) _lapseRenewalBackoff.Remove(_lapseRenewalBackoff.MinBy(entry => entry.Value).Key);
+ if (expired.Length == 0) _lapseRenewalBackoff.Remove(_lapseRenewalBackoff.MinBy(entry => entry.Value.Until).Key);
}
/// The per-read byte budget the SDK Read path schedules a cold projected read with.
internal const long ProjectedReadBytes = 4 * 1024 * 1024;
@@ -860,21 +860,46 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
}
public bool ScheduleRead(IProjectedDemandLease demand, DataBudget budget, long requestStartedTimestamp)
{
- if (demand is not Demand item || item.RequestedOperation != DataOperations.Read || !item.IsValid || budget is null) return false;
+ if (!TryAdmitRead(demand, budget, requestStartedTimestamp, out var item, out var boundedBudget)) return false;
+ _ = Task.Run(() => ReadCoreAsync(item!, boundedBudget!, requestStartedTimestamp, CancellationToken.None, ownsDemand: true)); return true;
+ }
+ ///
+ public Task ReadNowAsync(IProjectedDemandLease demand, DataBudget budget, long requestStartedTimestamp,
+ CancellationToken cancellationToken)
+ {
+ // #938: the same admission (unary count + bytes) and the same authenticated, freshness-checked, cache-publishing read as
+ // ScheduleRead — but the caller awaits it and is served what it read. The caller keeps the demand. Admission is decided
+ // here, synchronously, so NotAdmitted is an already-completed task.
+ if (cancellationToken.IsCancellationRequested) return Task.FromResult(ProjectedOriginRead.NoValue);
+ if (!TryAdmitRead(demand, budget, requestStartedTimestamp, out var item, out var boundedBudget))
+ return Task.FromResult(demand is Demand { IsValid: true } ? ProjectedOriginRead.NotAdmitted : ProjectedOriginRead.NoValue);
+ return Task.Run(async () =>
+ {
+ var value = await ReadCoreAsync(item!, boundedBudget!, requestStartedTimestamp, cancellationToken, ownsDemand: false).ConfigureAwait(false);
+ return value is null ? ProjectedOriginRead.NoValue : new ProjectedOriginRead(ProjectedOriginReadStatus.Served, value);
+ }, CancellationToken.None);
+ }
+ private bool TryAdmitRead(IProjectedDemandLease demand, DataBudget budget, long requestStartedTimestamp, out Demand? item, out DataBudget? boundedBudget)
+ {
+ item = null; boundedBudget = null;
+ if (demand is not Demand candidate || candidate.RequestedOperation != DataOperations.Read || !candidate.IsValid || budget is null) return false;
try { budget.Validate(); } catch (ArgumentException) { return false; }
var elapsed = Clock.GetElapsedTime(requestStartedTimestamp, Clock.GetTimestamp());
if (elapsed < TimeSpan.Zero || elapsed >= budget.Timeout) return false;
// The request's byte budget is an upper bound. Narrow it to this adapter's
// configured physical limit before admission and before remote dispatch.
- var boundedBudget = budget with { MaxBytes = Math.Min(budget.MaxBytes, _limits.MaxUnaryBytes) };
+ var bounded = budget with { MaxBytes = Math.Min(budget.MaxBytes, _limits.MaxUnaryBytes) };
lock (_sync)
{
- if (_disposed || _unaryCount >= _limits.MaxUnaryOperations || boundedBudget.MaxBytes > _limits.MaxUnaryBytes - _unaryBytes || !item.TryHold()) return false;
- _unaryCount++; _unaryBytes += boundedBudget.MaxBytes;
+ if (_disposed || _unaryCount >= _limits.MaxUnaryOperations || bounded.MaxBytes > _limits.MaxUnaryBytes - _unaryBytes || !candidate.TryHold()) return false;
+ _unaryCount++; _unaryBytes += bounded.MaxBytes;
}
- _ = Task.Run(() => ReadCoreAsync(item, boundedBudget, requestStartedTimestamp)); return true;
+ item = candidate; boundedBudget = bounded;
+ return true;
}
- private async Task ReadCoreAsync(Demand demand, DataBudget budget, long started)
+ // Returns the read sample when it is servable to the demand's caller: authenticated by the demand's current binding, fresh
+ // within the mapping's stale timeout, and published to (or already superseded in) the projection cache. Null otherwise.
+ private async Task ReadCoreAsync(Demand demand, DataBudget budget, long started, CancellationToken callerStop, bool ownsDemand)
{
IGrpcDataAdapterConnectionLease? connection = null;
try
@@ -882,14 +907,14 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
var original = demand.CurrentBinding;
var originalProof = original.Proof;
var remaining = budget.Timeout - Clock.GetElapsedTime(started, Clock.GetTimestamp());
- if (remaining <= TimeSpan.Zero || !demand.IsValid || !ReferenceEquals(demand.CurrentBinding, original)) return;
+ if (remaining <= TimeSpan.Zero || !demand.IsValid || !ReferenceEquals(demand.CurrentBinding, original)) return null;
var connectionId = _connectionForMapping(originalProof.Metadata.View.MappingId!);
- if (string.IsNullOrWhiteSpace(connectionId)) return;
+ if (string.IsNullOrWhiteSpace(connectionId)) return null;
using var timeout = new CancellationTokenSource(remaining, Clock);
- using var linked = CancellationTokenSource.CreateLinkedTokenSource(timeout.Token, demand.CancellationToken);
+ using var linked = CancellationTokenSource.CreateLinkedTokenSource(timeout.Token, demand.CancellationToken, callerStop);
connection = await _connections.AcquireAsync(connectionId, linked.Token).ConfigureAwait(false);
if (connection is null || !ReferenceEquals(connection.Connection.Clock, Clock) || connection.CancellationToken.IsCancellationRequested ||
- !demand.IsValid || !ReferenceEquals(demand.CurrentBinding, original)) return;
+ !demand.IsValid || !ReferenceEquals(demand.CurrentBinding, original)) return null;
using var route = CancellationTokenSource.CreateLinkedTokenSource(linked.Token, connection.CancellationToken);
var readStarted = Clock.GetTimestamp();
var result = await connection.Connection.ReadAsync(new DataReadRequest([new ReadItem("0", originalProof.OriginMetadata.View, null)], budget with { Timeout = remaining }), route.Token).ConfigureAwait(false);
@@ -897,32 +922,36 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
{
if (result.Count != 1 || result[0].CorrelationId != "0" || result[0].Status != DataItemStatus.Good || result[0].Readiness != DataReadiness.Ready ||
result[0].Sample is not { } sample || sample.Serving != originalProof.Lease.Serving || sample.Version <= 0 || !demand.IsValid ||
- !ReferenceEquals(demand.CurrentBinding, original) || route.IsCancellationRequested) return;
+ !ReferenceEquals(demand.CurrentBinding, original) || route.IsCancellationRequested) return null;
result[0].AgeBounds.Validate();
// An unstamped implementation is conservatively anchored before the read call.
var received = result[0].FreshnessObservedTimestamp ?? readStarted;
- if (!result[0].AgeBounds.Advance(Clock.GetElapsedTime(received, Clock.GetTimestamp())).IsFresh(originalProof.MaximumSampleAge)) return;
- if (sample.Value.EstimatedRetainedBytes > budget.MaxBytes) return;
+ if (!result[0].AgeBounds.Advance(Clock.GetElapsedTime(received, Clock.GetTimestamp())).IsFresh(originalProof.MaximumSampleAge)) return null;
+ if (sample.Value.EstimatedRetainedBytes > budget.MaxBytes) return null;
var payload = DecodeValue(sample.Value, originalProof.OriginMetadata);
var snapshot = new DataValueSnapshot(payload, sample.StatusCode, sample.SourceTimestampUtc?.UtcDateTime, sample.ServerTimestampUtc?.UtcDateTime);
var source = GetSource(demand, connectionId);
- if (source is null) return;
+ if (source is null) return null;
lock (source.Gate)
{
- if (!demand.IsValid || !ReferenceEquals(demand.CurrentBinding, original) || !source.IsValid || sample.Version <= source.LastVersion || route.IsCancellationRequested ||
- !result[0].AgeBounds.Advance(Clock.GetElapsedTime(received, Clock.GetTimestamp())).IsFresh(originalProof.MaximumSampleAge)) return;
+ if (!demand.IsValid || !ReferenceEquals(demand.CurrentBinding, original) || !source.IsValid || route.IsCancellationRequested ||
+ !result[0].AgeBounds.Advance(Clock.GetElapsedTime(received, Clock.GetTimestamp())).IsFresh(originalProof.MaximumSampleAge)) return null;
+ // The cache already holds this acquisition or a newer one: nothing to publish, but what was read is still an
+ // authenticated, fresh origin sample of this request (#938 serves it).
+ if (sample.Version <= source.LastVersion) return snapshot;
var update = new ProjectedValueUpdate(source.Route, snapshot, result[0].AgeBounds, received, source.CaptureReadProof(originalProof), true, originalProof.MaximumSampleAge, sample.Version);
- if (_publisher.TryPublish([update])) { source.LastVersion = sample.Version; source.CacheLocked(update, sample.Version); }
- else if (!ProjectedEvidenceRetirement.CanDrop(update.SourceProof)) source.Invalidate();
+ if (_publisher.TryPublish([update])) { source.LastVersion = sample.Version; source.CacheLocked(update, sample.Version); return snapshot; }
+ if (!ProjectedEvidenceRetirement.CanDrop(update.SourceProof)) source.Invalidate();
+ return null;
}
}
finally { foreach (var item in result) item.Dispose(); }
}
- catch (Exception) { }
+ catch (Exception) { return null; }
finally
{
try { if (connection is not null) await connection.DisposeAsync().ConfigureAwait(false); }
- finally { demand.Dispose(); demand.ReleaseHold(); lock (_sync) { _unaryCount--; _unaryBytes -= budget.MaxBytes; } }
+ finally { if (ownsDemand) demand.Dispose(); demand.ReleaseHold(); lock (_sync) { _unaryCount--; _unaryBytes -= budget.MaxBytes; } }
}
}
public async Task WriteAsync(IProjectedDemandLease demand, object? value, DataBudget budget,
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 6d2a0e1b9..6e5858437 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/RemoteNamespaceResolver.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/RemoteNamespaceResolver.cs
@@ -312,21 +312,39 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
// Refresh exactly one already-owned projected item. This deliberately creates no Browse
// page, cursor or sibling visibility and does not create a physical subscription.
internal async Task RenewExactAsync(ProjectedNodeProof previous, ProjectedVariableDefinition definition,
+ 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 RenewExactOutcomeAsync(previous, definition, nodeId, caller, configured, sink, budget, demandActive, cancellationToken,
+ overlap, authorizeAs, required, onDemand).ConfigureAwait(false) == ProjectedRenewalResult.Renewed;
+
+ ///
+ /// with the reason a renewal did not commit (#939):
+ /// ONLY for a definitive refusal BY THE ORIGIN — the call answered PERMISSION_DENIED, the item was answered
+ /// Denied, the principal no longer holds Metadata, or the metadata no longer grants .
+ /// Everything else (unreachable / unready / non-primary origin, capacity, timeout, a changed shape, a local fence) is
+ /// , i.e. retryable.
+ ///
+ internal async Task RenewExactOutcomeAsync(ProjectedNodeProof previous, ProjectedVariableDefinition definition,
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)
{
+ const ProjectedRenewalResult Failed = ProjectedRenewalResult.Failed;
+ const ProjectedRenewalResult Refused = ProjectedRenewalResult.Refused;
// #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) and requires exactly that bit at the origin.
- if (authorizeAs is not (OpcUaOperation.CreateMonitoredItems or OpcUaOperation.Read or OpcUaOperation.HistoryRead) ||
- required is not (DataOperations.Subscribe or DataOperations.Read or DataOperations.HistoryRead)) return false;
+ // 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 false;
+ if (mapping is null || previous.Subject.Scope.Segments.Count == 0) return Failed;
ProjectedMappingBinding binding;
lock (_sync)
{
- if (_disposed || !_mappings.TryGetValue(mapping, out binding!)) return false;
+ if (_disposed || !_mappings.TryGetValue(mapping, out binding!)) return Failed;
}
bool CallerAllowed() => demandActive() && (configured is not null
? configured.Matches(mapping, previous.Metadata.View, binding.LocalAuthority)
@@ -339,16 +357,16 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
!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 false;
+ !previous.Subject.LocalAncestry.SequenceEqual(binding.LocalAncestry, StringComparer.OrdinalIgnoreCase)) return Failed;
// 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 false;
+ if (!await slots.WaitAsync(onDemand ? budget.Timeout : TimeSpan.Zero, cancellationToken).ConfigureAwait(false)) return Failed;
if (onDemand)
{
var left = budget.Timeout - System.Diagnostics.Stopwatch.GetElapsedTime(queued);
- if (left <= TimeSpan.Zero) { slots.Release(); return false; }
+ if (left <= TimeSpan.Zero) { slots.Release(); return Failed; }
budget = budget with { Timeout = left };
}
IGrpcDataAdapterConnectionLease? connection = null;
@@ -359,22 +377,31 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
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 false;
+ !string.Equals(connection.Connection.Target.ExpectedClusterId, previous.OriginMetadata.View.Address.OriginClusterId, StringComparison.OrdinalIgnoreCase)) return Failed;
using var route = CancellationTokenSource.CreateLinkedTokenSource(linked.Token, connection.CancellationToken);
var capabilities = await connection.Connection.GetCapabilitiesAsync(budget, route.Token).ConfigureAwait(false);
capabilities.Validate();
var serving = capabilities.Serving;
var target = connection.Connection.Target;
- if (!capabilities.MetadataItemLeases || capabilities.Readiness != DataReadiness.Ready ||
- (capabilities.Operations & DataOperations.Metadata) == 0 || serving.ServingGeneration <= 0 ||
+ 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 false;
+ target.Mode == DataTargetMode.Node && target.Consistency == DataConsistency.ReadyReplica && string.Equals(serving.Role, "Secondary", StringComparison.OrdinalIgnoreCase))) return Failed;
+ // #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 false;
+ 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 false;
+ 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.
+ if (results.Count == 1 && results[0].CorrelationId == "0" &&
+ (results[0].Status == DataItemStatus.Denied ||
+ 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 ||
@@ -385,14 +412,14 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
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 false;
+ !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)
{
var remaining = expiry - Clock.GetUtcNow();
- if (remaining <= TimeSpan.Zero) return false;
+ if (remaining <= TimeSpan.Zero) return Failed;
if (remaining < maximumLease) maximumLease = remaining;
}
var lease = new BoundProjectionLease(new MetadataAuthorityLease(serving, remoteLease, started, maximumLease, TimeSpan.Zero, Clock),
@@ -406,10 +433,10 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
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 false;
+ 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) };
- return sink.TryRenewExact(nodeId, definition, newDefinition, () =>
+ var committedRenewal = sink.TryRenewExact(nodeId, definition, newDefinition, () =>
{
var duration = Clock.GetElapsedTime(started, Clock.GetTimestamp());
if (linked.IsCancellationRequested || cancellationToken.IsCancellationRequested || connection.CancellationToken.IsCancellationRequested ||
@@ -422,8 +449,11 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
guard.Adopt(actual);
return guard.IsCurrent();
});
+ return committedRenewal ? ProjectedRenewalResult.Renewed : Failed;
}
- catch (Exception ex) when (ex is not OutOfMemoryException) { return false; }
+ // #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; }
finally
{
try { if (connection is not null) await connection.DisposeAsync().ConfigureAwait(false); }
@@ -431,6 +461,12 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
finally { slots.Release(); }
}
}
+ internal static bool IsOriginPermissionDenied(Exception? ex)
+ {
+ for (var depth = 0; ex is not null && depth < 8; ex = ex.InnerException, depth++)
+ if (ex is Grpc.Core.RpcException { StatusCode: Grpc.Core.StatusCode.PermissionDenied }) return true;
+ return false;
+ }
public void Dispose()
{
ProjectedMappingBinding[] old;
diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataComposedBrowseWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataComposedBrowseWireTests.cs
index c56b311b3..ddf4cc17d 100644
--- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataComposedBrowseWireTests.cs
+++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataComposedBrowseWireTests.cs
@@ -154,7 +154,9 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
var client = (SessionClient)session;
var first = await client.ReadAsync(new RequestHeader(), 5000, TimestampsToReturn.Both,
[new ReadValueId { NodeId = anchor, AttributeId = Attributes.Value }], ct);
- first.Results[0].StatusCode.ShouldBe(StatusCodes.BadWaitingForInitialData);
+ // #938: the cold read is served from the origin read it triggers (same request), which also publishes the value.
+ StatusCode.IsGood(first.Results[0].StatusCode).ShouldBeTrue(first.Results[0].StatusCode.ToString());
+ first.Results[0].WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(42);
var update = await published.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
update.Snapshot.Value.ShouldBe(42);
var result = await client.ReadAsync(new RequestHeader(), 5000, TimestampsToReturn.Both,
diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataExpiredOverlapFailoverWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataExpiredOverlapFailoverWireTests.cs
index 39dd4f55b..03f2fb55e 100644
--- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataExpiredOverlapFailoverWireTests.cs
+++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataExpiredOverlapFailoverWireTests.cs
@@ -238,7 +238,8 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
{
var pending = await client.ReadAsync(new RequestHeader(), 5000, TimestampsToReturn.Both,
[new ReadValueId { NodeId = anchor, AttributeId = Attributes.Value }], ct);
- pending.Results[0].StatusCode.ShouldBe(StatusCodes.BadWaitingForInitialData);
+ // #938: served by the origin read it triggers, which also publishes (and read-owns) the source.
+ StatusCode.IsGood(pending.Results[0].StatusCode).ShouldBeTrue(pending.Results[0].StatusCode.ToString());
mappedRead = await NextPublished(published.Reader, x => Equals(x.Snapshot.Value, 42), ct);
mappedRead.Route.Serving.ShouldBe(originA.Serving);
var cached = await client.ReadAsync(new RequestHeader(), 5000, TimestampsToReturn.Both,
diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLeaseLapseWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLeaseLapseWireTests.cs
index 777b0aaf9..0822f030c 100644
--- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLeaseLapseWireTests.cs
+++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLeaseLapseWireTests.cs
@@ -58,10 +58,12 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
connections.BrowseCalls.ShouldBe(browses, "the renewal is an exact metadata refresh, not a re-browse");
connections.MetadataCalls.ShouldBeGreaterThan(metadata, "renewed by an exact metadata call");
- // And again: every idle gap longer than the lease renews the same way.
+ // And again: every idle gap longer than the lease renews the same way — since #938 within the same request (the
+ // read awaits the renewal, then reads the origin), so the first read after the gap is already served.
origin.Clock.Advance(TimeSpan.FromSeconds(16));
- (await ReadValue(client, anchor, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadWaitingForInitialData.Code);
- (await ReadUntilGood(client, anchor, ct)).ShouldBe(42);
+ var again = await ReadValue(client, anchor, ct);
+ StatusCode.IsGood(again.StatusCode).ShouldBeTrue(again.StatusCode.ToString());
+ again.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(42);
}, connectionSource: connections, staleTimeoutMilliseconds: LongStale);
}
diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedOriginAccessWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedOriginAccessWireTests.cs
new file mode 100644
index 000000000..e362e18cf
--- /dev/null
+++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedOriginAccessWireTests.cs
@@ -0,0 +1,421 @@
+using RpcException = Grpc.Core.RpcException;
+using RpcStatus = Grpc.Core.Status;
+using RpcStatusCode = Grpc.Core.StatusCode;
+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;
+using DataBrowseRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.BrowseRequest;
+using DataReadRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest;
+using DataReadResult = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadResult;
+
+namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
+
+///
+/// #938 / #939 / #940 over the wire (real consumer SDK session + projection stack):
+///
+/// #938 — a projected Read whose maxAge the cache cannot satisfy (Part 4: 0 = read the source; the
+/// Client CLI default and what ScadaBridge's DCL sends) is served from a bounded origin read in the SAME request.
+/// #939 — a lapsed node whose renewal the ORIGIN refuses answers BadUserAccessDenied (held, unsent), while an
+/// unreachable origin stays retryable.
+/// #940 — Write and CreateMonitoredItems on a lapsed node renew it on demand instead of BadUserAccessDenied; a
+/// real ACL denial stays BadUserAccessDenied and never reaches the origin.
+///
+///
+public sealed partial class GrpcDataConfiguredDiscoveryWireTests
+{
+ private const int NoSubscribeGrant = 3; // Browse | Read
+ private const int NoWriteGrant = 7; // Browse | Read | Subscribe
+
+ private static async Task ReadAt(SessionClient client, NodeId node, double maxAge, CancellationToken ct) =>
+ (await client.ReadAsync(new RequestHeader(), maxAge, TimestampsToReturn.Both,
+ [new ReadValueId { NodeId = node, AttributeId = Attributes.Value }], ct)).Results[0];
+
+ // ---------------------------------------------------------------- #938
+
+ [Fact(Timeout = 90000), Trait("Issue", "938")]
+ public async Task A_max_age_zero_read_is_served_from_the_origin_in_the_same_request_every_time()
+ {
+ var ct = TestContext.Current.CancellationToken;
+ using var origin = new LocalDataFixture(servingGeneration: 1);
+ origin.Publish(42);
+ var connections = new CountingConnections(origin);
+ await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
+ {
+ var client = (SessionClient)session;
+ await BrowseAll(client, anchor, 1);
+ var first = await ReadAt(client, anchor, 0, ct);
+ StatusCode.IsGood(first.StatusCode).ShouldBeTrue($"maxAge=0 must read the source, not answer {first.StatusCode}");
+ first.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(42);
+ connections.ReadCalls.ShouldBe(1);
+
+ // maxAge = 0 is never served from the cache: every such read goes to the origin.
+ var second = await ReadAt(client, anchor, 0, ct);
+ StatusCode.IsGood(second.StatusCode).ShouldBeTrue(second.StatusCode.ToString());
+ second.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(42);
+ connections.ReadCalls.ShouldBe(2);
+
+ // A maxAge the cache satisfies is served from it, with no origin call (the reads above warmed it).
+ // (The publication into the node's cache is asynchronous, so allow it to land.)
+ var fromCache = false;
+ for (var i = 0; i < 200 && !fromCache; i++)
+ {
+ var reads = connections.ReadCalls;
+ var cached = await ReadAt(client, anchor, LongMaxAge, ct);
+ cached.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(42);
+ fromCache = connections.ReadCalls == reads;
+ if (!fromCache) await Task.Delay(10, ct);
+ }
+ fromCache.ShouldBeTrue("a maxAge the cache satisfies is served without an origin read");
+ }, connectionSource: connections);
+ }
+
+ [Fact(Timeout = 90000), Trait("Issue", "938")]
+ public async Task A_max_age_zero_batch_larger_than_the_unary_budget_is_pumped_and_fully_served()
+ {
+ var ct = TestContext.Current.CancellationToken;
+ using var origin = new LocalDataFixture(additionalRawNodes: 3, servingGeneration: 1);
+ origin.Publish(42);
+ var connections = new CountingConnections(origin);
+ // 1 MiB unary budget = ONE read in flight at a time (each reserves it all), as in production by default.
+ await WithComposedServer(origin, origin.Root, async (session, _, _, _, _, _, anchor) =>
+ {
+ var client = (SessionClient)session;
+ var children = (await BrowseAll(client, anchor, 10)).Select(r => ExpandedNodeId.ToNodeId(r.NodeId, session.NamespaceUris)).ToArray();
+ children.Length.ShouldBe(4);
+ var read = await client.ReadAsync(new RequestHeader(), 0, TimestampsToReturn.Both,
+ children.Select(c => new ReadValueId { NodeId = c, AttributeId = Attributes.Value }).ToArray(), ct);
+ var results = read.Results.ToArray()!;
+ results.ShouldAllBe(r => StatusCode.IsGood(r.StatusCode), string.Join(", ", results.Select(r => r.StatusCode.ToString())));
+ connections.ReadCalls.ShouldBe(4);
+ }, connectionSource: connections, maxUnaryBytes: 1024 * 1024);
+ }
+
+ [Fact(Timeout = 90000), Trait("Issue", "938")]
+ public async Task A_max_age_zero_read_without_the_read_grant_is_denied_and_never_reaches_the_origin()
+ {
+ var ct = TestContext.Current.CancellationToken;
+ using var origin = new LocalDataFixture(servingGeneration: 1);
+ origin.Publish(42);
+ var connections = new CountingConnections(origin);
+ await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
+ {
+ var client = (SessionClient)session;
+ await BrowseAll(client, anchor, 1);
+ (await ReadAt(client, anchor, 0, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code);
+ connections.ReadCalls.ShouldBe(0);
+ }, connectionSource: connections, localPermissions: BrowseOnlyGrant);
+ }
+
+ [Fact(Timeout = 90000), Trait("Issue", "938")]
+ public async Task A_max_age_zero_read_of_a_lapsed_node_renews_and_is_served_in_one_request()
+ {
+ var ct = TestContext.Current.CancellationToken;
+ using var origin = new LocalDataFixture(servingGeneration: 1);
+ origin.Publish(42);
+ var connections = new CountingConnections(origin);
+ await WithComposedServer(origin, origin.Raw, async (session, _, resolver, _, _, _, anchor) =>
+ {
+ var client = (SessionClient)session;
+ await BrowseAll(client, anchor, 1);
+ origin.Clock.Advance(TimeSpan.FromSeconds(16));
+ resolver.TryResolveProjected(DataRealm.Raw, anchor.IdentifierAsString, out _).ShouldBeFalse("precondition: the lease has lapsed");
+ var value = await ReadAt(client, anchor, 0, ct);
+ StatusCode.IsGood(value.StatusCode).ShouldBeTrue(value.StatusCode.ToString());
+ value.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(42);
+ connections.BrowseCalls.ShouldBe(1, "renewed by an exact metadata call, not a re-browse");
+ }, connectionSource: connections, staleTimeoutMilliseconds: LongStale);
+ }
+
+ // ---------------------------------------------------------------- #939
+
+ public enum OriginRefusal { ItemDenied, OperationNotGranted, PermissionDeniedCall }
+
+ [Theory(Timeout = 90000), Trait("Issue", "939")]
+ [InlineData(OriginRefusal.ItemDenied)]
+ [InlineData(OriginRefusal.OperationNotGranted)]
+ [InlineData(OriginRefusal.PermissionDeniedCall)]
+ public async Task An_origin_refusing_the_renewal_of_a_lapsed_node_answers_access_denied_held_and_unsent(OriginRefusal refusal)
+ {
+ var ct = TestContext.Current.CancellationToken;
+ using var origin = new LocalDataFixture(servingGeneration: 1);
+ origin.Publish(42);
+ var connections = new RefusingConnections(origin);
+ await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
+ {
+ var client = (SessionClient)session;
+ await BrowseAll(client, anchor, 1);
+ StatusCode.IsGood((await ReadAt(client, anchor, LongMaxAge, ct)).StatusCode).ShouldBeTrue("precondition: readable");
+ origin.Clock.Advance(TimeSpan.FromSeconds(16));
+ connections.Refusal = refusal;
+ connections.Strip = DataOperations.Read;
+
+ (await ReadAt(client, anchor, LongMaxAge, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code,
+ "the origin's definitive refusal is an access denial, not a lapse to retry");
+ var metadata = connections.MetadataCalls;
+ for (var i = 0; i < 3; i++)
+ (await ReadAt(client, anchor, LongMaxAge, ct)).StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code);
+ connections.MetadataCalls.ShouldBe(metadata, "a held refusal is answered without another origin call");
+
+ // The origin grants it again: once the hold expires the next read renews and is served.
+ connections.Refusal = null;
+ origin.Clock.Advance(ProjectedDataAccess.LapseRefusalHold + TimeSpan.FromMilliseconds(1));
+ var restored = await ReadAt(client, anchor, LongMaxAge, ct);
+ StatusCode.IsGood(restored.StatusCode).ShouldBeTrue(restored.StatusCode.ToString());
+ }, connectionSource: connections, staleTimeoutMilliseconds: LongStale);
+ }
+
+ [Fact(Timeout = 90000), Trait("Issue", "939")]
+ public async Task An_unreachable_origin_for_a_lapsed_node_stays_retryable_not_denied()
+ {
+ var ct = TestContext.Current.CancellationToken;
+ using var origin = new LocalDataFixture(servingGeneration: 1);
+ origin.Publish(42);
+ var connections = new RefusingConnections(origin);
+ await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
+ {
+ var client = (SessionClient)session;
+ await BrowseAll(client, anchor, 1);
+ origin.Clock.Advance(TimeSpan.FromSeconds(16));
+ connections.Unreachable = true; // a transport failure, not a verdict
+ for (var i = 0; i < 3; i++)
+ {
+ var value = await ReadAt(client, anchor, LongMaxAge, ct);
+ value.StatusCode.Code.ShouldNotBe(StatusCodes.BadUserAccessDenied.Code);
+ StatusCode.IsGood(value.StatusCode).ShouldBeFalse();
+ origin.Clock.Advance(ProjectedDataAccess.LapseRenewalBackoff + TimeSpan.FromMilliseconds(1));
+ }
+ connections.Unreachable = false;
+ StatusCode.IsGood((await ReadAt(client, anchor, LongMaxAge, ct)).StatusCode).ShouldBeTrue();
+ }, connectionSource: connections, staleTimeoutMilliseconds: LongStale);
+ }
+
+ [Fact(Timeout = 90000), Trait("Issue", "939")]
+ public async Task An_origin_that_stops_granting_history_answers_a_lapsed_history_read_access_denied_unsent()
+ {
+ await using var originServer = await HistoryOrigin.StartAsync(7);
+ using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
+ var connections = new RefusingConnections(origin);
+ await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
+ {
+ var client = (SessionClient)session;
+ await BrowseAll(client, anchor, 1);
+ StatusCode.IsGood((await RawHistory(client, anchor, 3, default)).StatusCode).ShouldBeTrue("precondition: history is served");
+ var calls = originServer.Source.Calls;
+ origin.Clock.Advance(TimeSpan.FromSeconds(16));
+ connections.Refusal = OriginRefusal.OperationNotGranted;
+ connections.Strip = DataOperations.HistoryRead;
+ var refused = await RawHistory(client, anchor, 3, default);
+ refused.StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code, "the origin no longer grants HistoryRead");
+ originServer.Source.Calls.ShouldBe(calls, "nothing is read after the origin's refusal");
+ }, localPermissions: 15, allowHistory: true, connectionSource: connections);
+ }
+
+ // ---------------------------------------------------------------- #940
+
+ [Fact(Timeout = 90000), Trait("Issue", "940")]
+ public async Task A_write_to_a_lapsed_node_renews_on_demand_and_is_dispatched()
+ {
+ var ct = TestContext.Current.CancellationToken;
+ var writes = new RecordingOriginWrites(DataWriteState.DriverConfirmedSuccess);
+ using var origin = new LocalDataFixture(servingGeneration: 1, writes: _ => writes);
+ origin.Publish(42);
+ var connections = new RefusingConnections(origin);
+ await WithComposedServer(origin, origin.Raw, async (session, _, resolver, _, _, _, anchor) =>
+ {
+ var client = (SessionClient)session;
+ await BrowseAll(client, anchor, 1);
+ origin.Clock.Advance(TimeSpan.FromSeconds(16));
+ resolver.TryResolveProjected(DataRealm.Raw, anchor.IdentifierAsString, out _).ShouldBeFalse("precondition: the lease has lapsed");
+ (await Write(client, anchor, 77, ct)).ShouldBe(StatusCodes.Good, "a lease lapse is not an access denial");
+ writes.Calls.ShouldBe(1);
+ writes.Value.ShouldBe(77);
+ }, maxUnaryBytes: 1024 * 1024, allowWrite: true, connectionSource: connections, staleTimeoutMilliseconds: LongStale);
+ }
+
+ [Fact(Timeout = 90000), Trait("Issue", "940")]
+ public async Task A_write_to_a_lapsed_node_without_the_write_grant_is_denied_and_never_reaches_the_origin()
+ {
+ var ct = TestContext.Current.CancellationToken;
+ var writes = new RecordingOriginWrites(DataWriteState.DriverConfirmedSuccess);
+ using var origin = new LocalDataFixture(servingGeneration: 1, writes: _ => writes);
+ var connections = new RefusingConnections(origin);
+ await WithComposedServer(origin, origin.Raw, async (session, _, _, _, access, _, anchor) =>
+ {
+ var client = (SessionClient)session;
+ await BrowseAll(client, anchor, 1);
+ (await Write(client, anchor, 77, ct)).ShouldBe(StatusCodes.BadUserAccessDenied, "positive control: denied before the lapse too");
+ origin.Clock.Advance(TimeSpan.FromSeconds(16));
+ var metadata = connections.MetadataCalls;
+ (await Write(client, anchor, 77, ct)).ShouldBe(StatusCodes.BadUserAccessDenied);
+ writes.Calls.ShouldBe(0);
+ connections.MetadataCalls.ShouldBe(metadata, "an unauthorized writer never triggers a renewal");
+ access.LapseRenewalsStartedForTests.ShouldBe(0);
+ }, maxUnaryBytes: 1024 * 1024, allowWrite: true, connectionSource: connections, localPermissions: NoWriteGrant);
+ }
+
+ [Fact(Timeout = 90000), Trait("Issue", "940")]
+ public async Task A_write_to_a_lapsed_node_whose_origin_is_unreachable_is_retryable_and_unsent()
+ {
+ var ct = TestContext.Current.CancellationToken;
+ var writes = new RecordingOriginWrites(DataWriteState.DriverConfirmedSuccess);
+ using var origin = new LocalDataFixture(servingGeneration: 1, writes: _ => writes);
+ var connections = new RefusingConnections(origin);
+ await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
+ {
+ var client = (SessionClient)session;
+ await BrowseAll(client, anchor, 1);
+ origin.Clock.Advance(TimeSpan.FromSeconds(16));
+ connections.Unreachable = true;
+ (await Write(client, anchor, 77, ct)).ShouldBe(StatusCodes.BadResourceUnavailable);
+ writes.Calls.ShouldBe(0);
+ connections.Unreachable = false;
+ origin.Clock.Advance(ProjectedDataAccess.LapseRenewalBackoff + TimeSpan.FromMilliseconds(1));
+ (await Write(client, anchor, 78, ct)).ShouldBe(StatusCodes.Good);
+ writes.Calls.ShouldBe(1);
+ }, maxUnaryBytes: 1024 * 1024, allowWrite: true, connectionSource: connections, staleTimeoutMilliseconds: LongStale);
+ }
+
+ [Fact(Timeout = 90000), Trait("Issue", "940")]
+ public async Task Creating_a_monitored_item_on_a_lapsed_node_renews_on_demand_instead_of_denying()
+ {
+ 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 connections = new RefusingConnections(origin);
+ await WithComposedServer(origin, origin.Raw, async (session, _, resolver, _, _, _, anchor) =>
+ {
+ var client = (SessionClient)session;
+ await BrowseAll(client, anchor, 1);
+ origin.Clock.Advance(TimeSpan.FromSeconds(16));
+ resolver.TryResolveProjected(DataRealm.Raw, anchor.IdentifierAsString, out _).ShouldBeFalse("precondition: the lease has lapsed");
+ var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
+ (await CreateItem(client, sub, anchor, 1, ct)).ShouldBe(StatusCodes.Good, "a lease lapse is not an access denial");
+ resolver.TryResolveProjected(DataRealm.Raw, anchor.IdentifierAsString, out _).ShouldBeTrue("renewed on demand");
+ await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
+ }, connectionSource: connections, staleTimeoutMilliseconds: LongStale);
+ }
+
+ [Fact(Timeout = 90000), Trait("Issue", "940")]
+ public async Task Creating_a_monitored_item_on_a_lapsed_node_without_the_subscribe_grant_is_denied_and_unsent()
+ {
+ 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 connections = new RefusingConnections(origin);
+ await WithComposedServer(origin, origin.Raw, async (session, _, _, _, access, _, anchor) =>
+ {
+ var client = (SessionClient)session;
+ await BrowseAll(client, anchor, 1);
+ var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
+ (await CreateItem(client, sub, anchor, 1, ct)).ShouldBe(StatusCodes.BadUserAccessDenied, "positive control: denied before the lapse");
+ origin.Clock.Advance(TimeSpan.FromSeconds(16));
+ var metadata = connections.MetadataCalls;
+ (await CreateItem(client, sub, anchor, 2, ct)).ShouldBe(StatusCodes.BadUserAccessDenied);
+ connections.MetadataCalls.ShouldBe(metadata);
+ access.LapseRenewalsStartedForTests.ShouldBe(0);
+ }, connectionSource: connections, localPermissions: NoSubscribeGrant);
+ }
+
+ [Fact(Timeout = 90000), Trait("Issue", "940")]
+ public async Task Creating_a_monitored_item_on_a_lapsed_node_whose_origin_is_unreachable_is_retryable()
+ {
+ 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 connections = new RefusingConnections(origin);
+ await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
+ {
+ var client = (SessionClient)session;
+ await BrowseAll(client, anchor, 1);
+ origin.Clock.Advance(TimeSpan.FromSeconds(16));
+ connections.Unreachable = true;
+ var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
+ (await CreateItem(client, sub, anchor, 1, ct)).ShouldBe(StatusCodes.BadResourceUnavailable);
+ }, connectionSource: connections, staleTimeoutMilliseconds: LongStale);
+ }
+
+ private static async Task Write(SessionClient client, NodeId node, int value, CancellationToken ct) =>
+ (await client.WriteAsync(new RequestHeader(),
+ [new WriteValue { NodeId = node, AttributeId = Attributes.Value, Value = new Opc.Ua.DataValue(new Variant(value), StatusCodes.Good) }], ct))
+ .Results.ToArray()!.ShouldHaveSingleItem();
+
+ private static async Task CreateItem(SessionClient client, uint subscription, NodeId node, uint handle, CancellationToken ct) =>
+ (await client.CreateMonitoredItemsAsync(new RequestHeader(), subscription, TimestampsToReturn.Both,
+ [new MonitoredItemCreateRequest { ItemToMonitor = new ReadValueId { NodeId = node, AttributeId = Attributes.Value },
+ MonitoringMode = MonitoringMode.Reporting, RequestedParameters = new MonitoringParameters
+ { ClientHandle = handle, SamplingInterval = 100, QueueSize = 1, DiscardOldest = true } }], ct)).Results[0].StatusCode;
+
+ ///
+ /// One persistent origin connection whose metadata answers can be turned into an origin refusal (#939) or whose
+ /// acquisition can fail as an unreachable origin would; counts metadata and read calls.
+ ///
+ private sealed class RefusingConnections(LocalDataFixture peer) : IGrpcDataAdapterConnectionSource
+ {
+ private IDataConnection? _inner;
+ private readonly object _gate = new();
+ private readonly object _route = new();
+ private int _metadata, _read;
+ public int MetadataCalls => Volatile.Read(ref _metadata);
+ public int ReadCalls => Volatile.Read(ref _read);
+ public volatile bool Unreachable;
+ private volatile object? _refusal;
+ public OriginRefusal? Refusal { get => (OriginRefusal?)_refusal; set => _refusal = value; }
+ public DataOperations Strip = DataOperations.Read;
+ public ValueTask AcquireAsync(string connectionId, CancellationToken cancellationToken)
+ {
+ if (connectionId != "link" || Unreachable) return ValueTask.FromResult(null);
+ lock (_gate) _inner ??= peer.Connection();
+ return ValueTask.FromResult(new Borrowed(new Refusing(_inner, this), _route));
+ }
+ private sealed class Borrowed(IDataConnection connection, object route) : IGrpcDataAdapterConnectionLease
+ {
+ public IDataConnection Connection => connection;
+ public CancellationToken CancellationToken => CancellationToken.None;
+ public object? RouteIdentity => route;
+ public ValueTask DisposeAsync() => ValueTask.CompletedTask;
+ }
+ private sealed class Refusing(IDataConnection inner, RefusingConnections owner) : IDataConnection, IDataHistoryService
+ {
+ public DataTarget Target => inner.Target;
+ public TimeProvider Clock => inner.Clock;
+ public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => inner.GetCapabilitiesAsync(budget, cancellationToken);
+ public Task BrowseAsync(DataBrowseRequest request, CancellationToken cancellationToken) => inner.BrowseAsync(request, cancellationToken);
+ public async Task>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken)
+ {
+ Interlocked.Increment(ref owner._metadata);
+ switch (owner.Refusal)
+ {
+ case OriginRefusal.PermissionDeniedCall:
+ // As GrpcDataConnection reports a call the origin answered PERMISSION_DENIED on every endpoint.
+ throw new InvalidOperationException("No ready authenticated data endpoint.",
+ new RpcException(new RpcStatus(RpcStatusCode.PermissionDenied, "Data operation denied.")));
+ case OriginRefusal.ItemDenied:
+ return request.Views.Select((_, i) => new DataItemResult(
+ i.ToString(System.Globalization.CultureInfo.InvariantCulture), DataItemStatus.Denied, null, null)).ToArray();
+ }
+ var results = await inner.GetMetadataAsync(request, cancellationToken);
+ return owner.Refusal == OriginRefusal.OperationNotGranted
+ ? results.Select(x => x.Value is null ? x : x with { Value = x.Value with { AllowedOperations = x.Value.AllowedOperations & ~owner.Strip } }).ToArray()
+ : results;
+ }
+ public Task> ReadAsync(DataReadRequest request, CancellationToken cancellationToken)
+ { Interlocked.Increment(ref owner._read); return inner.ReadAsync(request, cancellationToken); }
+ public Task> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => inner.WriteAsync(request, cancellationToken);
+ public Task SubscribeAsync(CancellationToken cancellationToken) => inner.SubscribeAsync(cancellationToken);
+ public Task> ReadAsync(DataHistoryReadRequest request, CancellationToken cancellationToken) =>
+ ((IDataHistoryService)inner).ReadAsync(request, cancellationToken);
+ public Task ReleaseAsync(IReadOnlyList continuations, CancellationToken cancellationToken) =>
+ ((IDataHistoryService)inner).ReleaseAsync(continuations, cancellationToken);
+ public ValueTask DisposeAsync() => ValueTask.CompletedTask;
+ }
+ }
+}
diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSdkSampleFidelityWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSdkSampleFidelityWireTests.cs
index 5f02575f3..b370d1533 100644
--- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSdkSampleFidelityWireTests.cs
+++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSdkSampleFidelityWireTests.cs
@@ -43,8 +43,12 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
[new ReadValueId { NodeId = node, AttributeId = Attributes.Value }], ct);
return result.Results[0];
}
+ // #938: the cold read is served from the origin read it triggers, in the same request — with the same fidelity.
var first = await ReadAsync();
- first.StatusCode.ShouldBe(StatusCodes.BadWaitingForInitialData);
+ first.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(42);
+ first.StatusCode.Code.ShouldBe(quality);
+ first.SourceTimestamp.ShouldBe((DateTimeUtc)sourceTime.UtcDateTime);
+ first.ServerTimestamp.ShouldBe((DateTimeUtc)serverTime.UtcDateTime);
var admitted = await published.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
admitted.SourceVersion.ShouldBe(version);
admitted.Snapshot.StatusCode.ShouldBe(quality);
diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSdkSourceLossTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSdkSourceLossTests.cs
index fac1beb35..4d9953ace 100644
--- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSdkSourceLossTests.cs
+++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSdkSourceLossTests.cs
@@ -180,6 +180,58 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
}, onPublished: update => published.Writer.TryWrite(update));
}
+ ///
+ /// #948: an acquisition an item already DELIVERED (its proof candidate consumed by an SDK notification) that reaches the
+ /// item again as a complete snapshot — a recovery re-publish, a duplicate baseline, a stricter demand's snapshot — must
+ /// not leave a new candidate behind: the node's value does not change, so no SDK notification will ever consume it, and
+ /// it would hold its shared budget charge until the item's binding changed. A NEW acquisition still gets one (control).
+ ///
+ [Fact(Timeout = 90000), Trait("Issue", "948")]
+ public async Task A_redelivered_already_consumed_acquisition_leaves_no_orphan_candidate()
+ {
+ 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;
+ await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, _, _, anchor) =>
+ {
+ var client = (SessionClient)session;
+ await BrowseAll(client, anchor, 1);
+ var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
+ await AddComposedItem(client, sub, anchor, 1, 100, ct);
+ await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
+ (await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good);
+ var flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic;
+ var manager = sink.GetType().GetField("_nodeManager", flags)!.GetValue(sink)!;
+ var samples = (System.Collections.IDictionary)manager.GetType().GetField("_projectedSamples", flags)!.GetValue(manager)!;
+ var live = manager.GetType().GetField("_liveItems", flags)!.GetValue(manager)!;
+ var keys = (System.Collections.IEnumerable)live.GetType().GetProperty("Keys")!.GetValue(live)!;
+ var existing = keys.Cast