Merge #956/#957: unknown value-kind decodes to a skip marker (version skew); /raw refuses newly-alarming an export root; data-connection saves validate only introduced errors; ACL-hidden nodes inside a grant answer NotFound

This commit is contained in:
Joseph Doherty
2026-12-01 20:34:45 -05:00
19 changed files with 543 additions and 43 deletions
@@ -274,8 +274,11 @@ public static class DataProtoMapper
if (x.Dimensions.Count > TypedValueCodec.MaxDimensions)
throw new ArgumentException("Too many dimensions.");
Preflight(x, 1, null);
// #956: a value-kind number this build does not define (a newer origin's data type) is NOT a decode failure — it
// decodes to an unknown-kind marker (DataMetadata.HasUnknownKind) that ValidateDecoded accepts and Validate refuses,
// so the resolver skips that one item (#941) instead of the whole browse page / metadata batch failing here.
// Unspecified (0) is still malformed and throws (ValidateDecoded).
var kind = (DataValueKind)x.ValueKind;
DataContractValidation.Required(kind);
var metadata = new DataMetadata(
DecodeView(x.View),
x.BrowseName,
@@ -296,7 +299,7 @@ public static class DataProtoMapper
null,
x.History is { } history ? new DataHistoryInfo(history.Historizing) : null
);
metadata.Validate();
metadata.ValidateDecoded();
return metadata;
}
@@ -1249,6 +1252,12 @@ public static class DataProtoMapper
{
Preflight(item, 1, limits);
var status = (DataItemStatus)item.Status;
if (item.Status != 0 && !System.Enum.IsDefined(status))
// #956 version skew: a per-item status a newer origin added is that item's failure, not the batch's. It grants
// nothing (no value, no lease) and reads as transient (Unavailable), so the consumer retries rather than caching
// a permanent refusal. Unspecified (0) is still malformed and fails the response below.
return new(item.CorrelationId, DataItemStatus.Unavailable, null,
$"Origin item status {item.Status} is not understood by this build.", null);
DataContractValidation.Required(status);
MetadataLease? lease = item.Lease is { } itemLease
? new(itemLease.CatalogEpoch, itemLease.AuthorityEpoch, TimeSpan.FromTicks(itemLease.DurationTicks)) : null;
@@ -46,6 +46,14 @@ public static class DataConnectionValidator
/// <summary>Default of the host option <c>DataConnections:MaxImportedConditionNodes</c> (= 2,500 × 49) per consumer node.</summary>
public const int DefaultMaxImportedConditionNodes = 122_500;
/// <summary>#942: an enabled export rooted at an alarm-bearing RawTag, or at a UnsTagReference to one.</summary>
public const string ExportRootAlarmBearingCode = "DataExportRootAlarmBearing";
/// <summary>The <see cref="ExportRootAlarmBearingCode"/> message; /raw's tag edit (#957) refuses with the same text.</summary>
public const string ExportRootAlarmBearingMessage =
"An export cannot be rooted at an alarm-bearing tag or a reference to one: the tag carries no value and its " +
"alarm is exported as a condition under the tag's folder (Raw) or the referencing equipment (UNS). Root the " +
"export at that folder, device or equipment instead.";
/// <summary>Authoring/deploy-gate validation: an operation bit outside the known set is an error.</summary>
public static IReadOnlyList<ValidationError> Validate(DraftSnapshot draft) => Validate(draft, deployed: false);
@@ -348,10 +356,7 @@ public static class DataConnectionValidator
// export set. Refused at authoring and at the deploy gate only: a node re-validating an already-deployed artifact
// (deployed) keeps its tolerant behaviour.
if (!deployed && AlarmBearingRoot(export.RootKind, export.RootEntityId))
Add("DataExportRootAlarmBearing", id,
"An export cannot be rooted at an alarm-bearing tag or a reference to one: the tag carries no value and its " +
"alarm is exported as a condition under the tag's folder (Raw) or the referencing equipment (UNS). Root the " +
"export at that folder, device or equipment instead.");
Add(ExportRootAlarmBearingCode, id, ExportRootAlarmBearingMessage);
}
return errors;
}
@@ -356,6 +356,37 @@ public sealed record DataMetadata(DataView View, string BrowseName, string NodeK
string? StableSourceId, string? EngineeringUnits, bool IsStale, DataValueKind? ArrayElementKind = null, ServingIdentity? Serving = null,
DataHistoryInfo? History = null)
{
/// <summary>
/// #956 version skew: the value kind (or the array element kind) is a number this build does not define — a data type
/// a newer origin added. Such an item is an <em>unsupported marker</em>: it decodes (so one item never fails a whole
/// browse page or metadata batch), it fails <see cref="Validate"/> (so it can never be re-encoded, materialised or
/// granted), and the consumer's resolver skips it like any other unmaterialisable kind (#941).
/// </summary>
public bool HasUnknownKind => !Enum.IsDefined(ValueKind) || ArrayElementKind is { } element && !Enum.IsDefined(element);
/// <summary>
/// Validation of an item decoded from a peer (#956): <see cref="Validate"/> for every item of a kind this build defines;
/// for a <see cref="HasUnknownKind"/> marker, everything that does not depend on the unknown kind's meaning — the view,
/// a nonzero kind, a positive catalog revision, non-negative dimensions and, for a known <c>Array</c> whose element kind
/// is the unknown one, the array shape. Unspecified (0) is a malformed item, never version skew, and still throws.
/// </summary>
public void ValidateDecoded()
{
if (!HasUnknownKind) { Validate(); return; }
ArgumentNullException.ThrowIfNull(View);
View.Validate();
ArgumentNullException.ThrowIfNull(Dimensions);
if (ValueKind == DataValueKind.Unspecified || ArrayElementKind == DataValueKind.Unspecified)
throw new ArgumentOutOfRangeException(nameof(ValueKind), ValueKind, "A defined nonzero value is required.");
if (CatalogRevision <= 0 || Dimensions.Any(d => d < 0)) throw new ArgumentOutOfRangeException(nameof(CatalogRevision));
if (Enum.IsDefined(ValueKind))
{
// The value kind is known, so the unknown one is the element kind: only an array may carry one, with its shape.
if (ValueKind != DataValueKind.Array) throw new ArgumentException("Only arrays may specify an element kind.", nameof(ArrayElementKind));
if (ValueRank <= 0 || Dimensions.Count != ValueRank) throw new ArgumentException("Array rank and dimensions must agree.", nameof(ValueRank));
}
}
public void Validate()
{
ArgumentNullException.ThrowIfNull(View);
@@ -51,6 +51,7 @@ public sealed class DataConnectionAdminService(IDbContextFactory<OtOpcUaConfigDb
await RequireEditorAsync();
await using var db = await factory.CreateDbContextAsync(ct);
var snapshot = await DraftSnapshotFactory.FromConfigDbAsync(db, ct);
var baseline = DataConnectionValidator.Validate(snapshot);
switch (row)
{
case DataConnection c:
@@ -67,8 +68,7 @@ public sealed class DataConnectionAdminService(IDbContextFactory<OtOpcUaConfigDb
break;
default: throw new ArgumentException("Unsupported draft row.", nameof(row));
}
var errors = DataConnectionValidator.Validate(snapshot);
if (errors.Count != 0) throw new InvalidOperationException(string.Join(" ", errors.Select(e => e.Message)));
ThrowIfRefused(baseline, DataConnectionValidator.Validate(snapshot), RowId(row));
await db.SaveChangesAsync(ct);
}
@@ -77,6 +77,7 @@ public sealed class DataConnectionAdminService(IDbContextFactory<OtOpcUaConfigDb
await RequireEditorAsync();
await using var db = await factory.CreateDbContextAsync(ct);
var snapshot = await DraftSnapshotFactory.FromConfigDbAsync(db, ct);
var baseline = DataConnectionValidator.Validate(snapshot);
switch (row)
{
case DataConnection c:
@@ -90,11 +91,30 @@ public sealed class DataConnectionAdminService(IDbContextFactory<OtOpcUaConfigDb
await DeleteRow(db, snapshot.RemoteNamespaceMappings, m, x => x.RemoteNamespaceMappingRowId, x => x.RemoteNamespaceMappingId, ct); break;
default: throw new ArgumentException("Unsupported draft row.", nameof(row));
}
var errors = DataConnectionValidator.Validate(snapshot);
if (errors.Count != 0) throw new InvalidOperationException(string.Join(" ", errors.Select(e => e.Message)));
ThrowIfRefused(baseline, DataConnectionValidator.Validate(snapshot), RowId(row));
await db.SaveChangesAsync(ct);
}
/// <summary>
/// #957: a mutation is refused for every error it INTRODUCES (absent from the pre-mutation draft) and for every error
/// still attached to the row being saved, but not for a pre-existing error of some other row. Before, the whole draft
/// had to be valid, so one invalid row already in ConfigDb (a /raw edit made an export root alarm-bearing, a node was
/// disabled, a row predating a newer rule) blocked saving or deleting every unrelated data-connection row - and with
/// two such rows neither could be fixed or deleted first. The deploy gate (<c>DraftValidator</c>) still validates the
/// whole draft, so nothing invalid can be deployed; authoring only stops refusing changes that did not cause it.
/// </summary>
internal static void ThrowIfRefused(IReadOnlyList<ValidationError> baseline, IReadOnlyList<ValidationError> after, string rowId)
{
var existing = baseline.ToHashSet();
var refused = after.Where(e => !existing.Contains(e) || string.Equals(e.Context, rowId, StringComparison.OrdinalIgnoreCase)).ToList();
if (refused.Count != 0) throw new InvalidOperationException(string.Join(" ", refused.Select(e => e.Message)));
}
private static string RowId(object row) => row switch
{
DataConnection c => c.DataConnectionId, DataExport e => e.DataExportId, RemoteNamespaceMapping m => m.RemoteNamespaceMappingId,
_ => throw new ArgumentException("Unsupported draft row.", nameof(row))
};
private async Task RequireEditorAsync()
{
var user = (await authentication.GetAuthenticationStateAsync()).User;
@@ -918,6 +918,8 @@ public sealed class RawTreeService(IDbContextFactory<OtOpcUaConfigDbContext> dbF
return new UnsMutationResult(false, configError);
if (TagRowProblem(await ResolveDriverTypeAsync(db, entity.DeviceId, ct), input, tagConfig) is { } rowError)
return new UnsMutationResult(false, rowError);
if (await AlarmOnExportRootProblemAsync(db, tagId, entity.TagConfig, tagConfig, ct) is { } exportError)
return new UnsMutationResult(false, exportError);
db.Entry(entity).Property(e => e.RowVersion).OriginalValue = rowVersion;
entity.Name = input.Name;
@@ -938,6 +940,35 @@ public sealed class RawTreeService(IDbContextFactory<OtOpcUaConfigDbContext> dbF
}
}
/// <summary>
/// #957: adding an alarm to a tag that is already the root of an enabled data export - directly (<c>RawTag</c>) or
/// through a UNS reference to it (<c>UnsTagReference</c>) - is refused here with the deploy gate's own
/// <see cref="DataConnectionValidator.ExportRootAlarmBearingCode"/> text, instead of surfacing only at the next
/// deploy (#942). Only the edit that INTRODUCES the alarm is refused: a tag that was already alarm-bearing (a draft
/// made invalid before this check existed) can still be edited, and the deploy gate keeps reporting the export, so an
/// unrelated edit is never blocked by a pre-existing problem (the same rule as <c>DataConnectionAdminService</c>).
/// A targeted query, not a whole-draft validation, so a tag save stays cheap on a large configuration.
/// </summary>
private static async Task<string?> AlarmOnExportRootProblemAsync(
OtOpcUaConfigDbContext db, string tagId, string? oldConfig, string newConfig, CancellationToken ct)
{
if (TagConfigIntent.Parse(newConfig).Alarm is null || TagConfigIntent.Parse(oldConfig).Alarm is not null) return null;
var references = await db.UnsTagReferences.AsNoTracking().Where(r => r.TagId == tagId)
.Select(r => r.UnsTagReferenceId).ToListAsync(ct);
var exports = (await db.DataExports.AsNoTracking()
.Where(e => e.Enabled && (e.RootKind == "RawTag" || e.RootKind == "UnsTagReference"))
.Select(e => new { e.DataExportId, e.RootKind, e.RootEntityId })
.ToListAsync(ct))
// The validator compares ids case-insensitively; so does this (the provider's collation may not).
.Where(e => e.RootKind == "RawTag"
? string.Equals(e.RootEntityId, tagId, StringComparison.OrdinalIgnoreCase)
: references.Contains(e.RootEntityId, StringComparer.OrdinalIgnoreCase))
.Select(e => e.DataExportId).Order(StringComparer.Ordinal).ToList();
return exports.Count == 0 ? null
: $"This tag is the root of data export {string.Join(", ", exports.Select(x => $"'{x}'"))}, so it cannot become " +
$"alarm-bearing. {DataConnectionValidator.ExportRootAlarmBearingMessage}";
}
/// <inheritdoc />
public async Task<RawTagImportResult> ImportTagsAsync(
string deviceId, IReadOnlyList<RawTagImportRow> rows, CancellationToken ct = default)
@@ -61,11 +61,12 @@ public sealed partial class LocalDataServices
if (catalog is null || !Ready(catalog) || !RoleAllows(target, catalog.Serving)) return DataItemStatus.Unavailable;
if (!string.Equals(catalog.Serving.Role, "Primary", StringComparison.OrdinalIgnoreCase)) return DataItemStatus.Unavailable;
if (context.AuthorityEpoch != catalog.AuthorityEpoch || !_policy.IsCallerUsable(Caller(context))) return DataItemStatus.Denied;
// #943: a root outside the caller's grant is answered exactly like a missing one (no existence oracle).
if (!catalog.DisclosesAddress(context.PrincipalId, view)) return DataItemStatus.NotFound;
if (!catalog.TryResolve(view, out var node)) return DataItemStatus.Denied;
// #943: a root outside the caller's grant is answered exactly like a missing one (no existence oracle); #957: so is
// one inside it that the origin ACL hides.
if (!catalog.DisclosesAddress(context.PrincipalId, view, out var atAddress)) return DataItemStatus.NotFound;
if (!catalog.TryResolve(view, out var node)) return Refusal(context, atAddress);
var root = node.Metadata.View;
if (catalog.ConditionLimitFor(context.PrincipalId, root) is not { } limit) return DataItemStatus.Denied;
if (catalog.ConditionLimitFor(context.PrincipalId, root) is not { } limit) return Refusal(context, node);
var serving = catalog.Serving;
object? listedFrom = null;
ConditionItemScope? cached = null;
@@ -141,6 +141,24 @@ public sealed partial class LocalDataServices : IDataConnectionFactory
return allowed && Ready(catalog);
}
/// <summary>
/// #957: whether the origin ACL lets the caller know <paramref name="node"/> exists — it may Browse it or Read it (the
/// same ACL rule that admits GetMetadata). A node the ACL hides is never listed by Browse, so a refusal of it inside
/// the caller's grant must not say "exists" either.
/// </summary>
private bool VisibleToCaller(DataAuthenticatedContext context, LocalDataNode node) =>
_policy.AuthorizeLocal(Caller(context), OpcUaOperation.Browse, node.Scope)
|| _policy.AuthorizeLocal(Caller(context), OpcUaOperation.Read, node.Scope);
/// <summary>
/// #957: the per-item refusal of a node inside the caller's grant (#943 answers one outside it NotFound): <c>Denied</c>
/// when the caller may know the node exists, <c>NotFound</c> — exactly a missing node's answer — when the origin ACL
/// hides it. Browse omits such a node and HistoryRead / Write answer it like a missing one, so GetMetadata, Read,
/// Subscribe and condition-item admission must not be the oracle that tells it apart.
/// </summary>
private DataItemStatus Refusal(DataAuthenticatedContext context, LocalDataNode node) =>
VisibleToCaller(context, node) ? DataItemStatus.Denied : DataItemStatus.NotFound;
internal DataItemStatus AuthorizeSubscription(DataAuthenticatedContext context, DataTarget target, DataView view,
out SubscriptionAuthorizedView? authorized)
{
@@ -154,10 +172,11 @@ public sealed partial class LocalDataServices : IDataConnectionFactory
target.Mode == DataTargetMode.Node && !string.Equals(target.ExpectedNodeId, catalog.Serving.NodeId, StringComparison.OrdinalIgnoreCase))
return DataItemStatus.Unavailable;
if (!_policy.IsCallerUsable(Caller(context))) return DataItemStatus.Denied;
// #943: an address outside the caller's grant is answered exactly like a missing one (no existence oracle).
if (!catalog.DisclosesAddress(context.PrincipalId, view)) return DataItemStatus.NotFound;
if (!catalog.TryResolve(view, out var node)) return DataItemStatus.Denied;
if (!Allowed(catalog, context, node, DataOperations.Subscribe)) return DataItemStatus.Denied;
// #943: an address outside the caller's grant is answered exactly like a missing one (no existence oracle); #957: so
// is one inside it that the origin ACL hides.
if (!catalog.DisclosesAddress(context.PrincipalId, view, out var atAddress)) return DataItemStatus.NotFound;
if (!catalog.TryResolve(view, out var node)) return Refusal(context, atAddress);
if (!Allowed(catalog, context, node, DataOperations.Subscribe)) return Refusal(context, node);
var source = node.Source;
if (!node.Supported || source is null) return DataItemStatus.Unsupported;
if (!node.SourceEnabled) return DataItemStatus.Unavailable;
@@ -265,15 +284,16 @@ public sealed partial class LocalDataServices : IDataConnectionFactory
var view = request.Views[i]; view.Validate();
var status = !Ready(catalog) || Expired(start, request.Budget) ? DataItemStatus.Unavailable
: !_policy.IsCallerUsable(Caller(context)) ? DataItemStatus.Denied
// #943: an address outside the caller's grant is answered exactly like a missing one (no existence oracle).
: !catalog.DisclosesAddress(context.PrincipalId, view) ? DataItemStatus.NotFound
: !catalog.TryResolveAddress(view, out _) ? DataItemStatus.Denied
// #943: an address outside the caller's grant is answered exactly like a missing one (no existence oracle); #957:
// so is one inside it that the origin ACL hides.
: !catalog.DisclosesAddress(context.PrincipalId, view, out var atAddress) ? DataItemStatus.NotFound
: !catalog.TryResolveAddress(view, out _) ? Refusal(context, atAddress)
: DataItemStatus.Good;
DataMetadata? metadata = null;
MetadataLease? itemLease = null;
if (status == DataItemStatus.Good && catalog.TryResolveAddress(view, out var node))
{
if (!Allowed(catalog, context, node, DataOperations.Metadata)) status = DataItemStatus.Denied;
if (!Allowed(catalog, context, node, DataOperations.Metadata)) status = Refusal(context, node);
else if (!node.Supported) status = DataItemStatus.Unsupported;
else
{
@@ -327,10 +347,11 @@ public sealed partial class LocalDataServices : IDataConnectionFactory
new(item.CorrelationId, status, readiness, null, null, null);
if (!Ready(catalog) || Expired(start, request.Budget)) { results.Add(Empty(DataItemStatus.Unavailable)); continue; }
if (!_policy.IsCallerUsable(Caller(context))) { results.Add(Empty(DataItemStatus.Denied)); continue; }
// #943: an address outside the caller's grant is answered exactly like a missing one (no existence oracle).
if (!catalog.DisclosesAddress(context.PrincipalId, item.View)) { results.Add(Empty(DataItemStatus.NotFound)); continue; }
if (!catalog.TryResolve(item.View, out var node)) { results.Add(Empty(DataItemStatus.Denied)); continue; }
if (!Allowed(catalog, context, node, DataOperations.Read)) { results.Add(Empty(DataItemStatus.Denied)); continue; }
// #943: an address outside the caller's grant is answered exactly like a missing one (no existence oracle); #957:
// so is one inside it that the origin ACL hides.
if (!catalog.DisclosesAddress(context.PrincipalId, item.View, out var atAddress)) { results.Add(Empty(DataItemStatus.NotFound)); continue; }
if (!catalog.TryResolve(item.View, out var node)) { results.Add(Empty(Refusal(context, atAddress))); continue; }
if (!Allowed(catalog, context, node, DataOperations.Read)) { results.Add(Empty(Refusal(context, node))); continue; }
if (!node.Supported) { results.Add(Empty(DataItemStatus.Unsupported)); continue; }
if (!node.SourceEnabled) { results.Add(Empty(DataItemStatus.Unavailable)); continue; }
if (node.Source is not { } key) { results.Add(Empty(DataItemStatus.Unsupported)); continue; }
@@ -354,9 +375,12 @@ public sealed partial class LocalDataServices : IDataConnectionFactory
// and original timestamps remain unchanged, including provisional boot acquisitions.
var exposed = sample with { Value = sample.Value.Retain(), Serving = catalog.Serving };
exposed.Validate();
if (!Allowed(catalog, context, node, DataOperations.Read)
|| !_hub.TryGetCurrentTicket(key, out current) || current != ticket)
{ exposed.Dispose(); read.Dispose(); results.Add(Empty(DataItemStatus.Denied)); continue; }
var stillAllowed = Allowed(catalog, context, node, DataOperations.Read);
if (!stillAllowed || !_hub.TryGetCurrentTicket(key, out current) || current != ticket)
{
exposed.Dispose(); read.Dispose();
results.Add(Empty(stillAllowed ? DataItemStatus.Denied : Refusal(context, node))); continue;
}
var publication = new PublicationReadLease(read, () => CanPublish(context, exposed.Serving, target)
&& !Expired(start, request.Budget));
results.Add(new(item.CorrelationId, item.MaximumAge is { } max && age > max ? DataItemStatus.Stale : DataItemStatus.Good,
@@ -154,9 +154,15 @@ public sealed partial class LocalExportCatalog
/// When this is false the address must be answered exactly like a missing one, so a peer granted one subtree cannot
/// probe guessed addresses elsewhere and learn which exist (the existence oracle).
/// </summary>
internal bool DisclosesAddress(string principal, DataView view)
internal bool DisclosesAddress(string principal, DataView view) => DisclosesAddress(principal, view, out _);
/// <summary>
/// <see cref="DisclosesAddress(string, DataView)"/>, also returning the node at the view's address (whatever the view's
/// other fields claim) so a refusal inside the grant can be judged against the origin ACL (#957).
/// </summary>
internal bool DisclosesAddress(string principal, DataView view, out LocalDataNode node)
{
if (!_nodes.TryGetValue((LocalAddress(view.Address), view.Realm), out var node)) return false;
if (!_nodes.TryGetValue((LocalAddress(view.Address), view.Realm), out node!)) return false;
var target = node.Metadata.View;
foreach (var rule in _exports)
{
@@ -139,9 +139,11 @@ public sealed class ProjectedCatalogCache
/// that is not materialisable (an <c>UnsupportedVariable</c> from a pre-#917 origin, a node kind a newer origin adds, a
/// value type the consumer cannot represent) is SKIPPED by the resolver; it used to fail the whole page, making the
/// folder <c>BadNoCommunication</c>. A malformed item of a supported kind (rank / dimensions / element kind that do
/// not agree) still fails the page closed — that is a protocol violation, not an unknown kind.
/// not agree) still fails the page closed — that is a protocol violation, not an unknown kind. #956: an item whose value
/// or element kind is a number this build does not define (<see cref="DataMetadata.HasUnknownKind"/>, decoded as a
/// marker rather than failing the response) is never materialisable, whatever its node kind.
/// </summary>
internal static bool IsMaterialisable(DataMetadata metadata) => metadata.NodeKind switch
internal static bool IsMaterialisable(DataMetadata metadata) => !metadata.HasUnknownKind && metadata.NodeKind switch
{
"Folder" => true,
"Variable" or "Tag" => HasBuiltInType(metadata.ValueKind == DataValueKind.Array ? metadata.ArrayElementKind : metadata.ValueKind),
@@ -207,7 +207,7 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
{
var originView = new DataView(request.Parent.Address, request.Parent.Realm, null, 0, binding.Mapping.RemoteRootEntityId);
var metadata = await connection.Connection.GetMetadataAsync(new([originView], request.Budget with { Timeout = remaining }), route.Token).ConfigureAwait(false);
if (metadata.Count != 1 || metadata[0].Status != DataItemStatus.Good || metadata[0].Value is not { } root || root.View.Address != originView.Address || root.View.MappingId is not null || root.Serving is null)
if (metadata.Count != 1 || metadata[0].Status != DataItemStatus.Good || metadata[0].Value is not { } root || root.HasUnknownKind || root.View.Address != originView.Address || root.View.MappingId is not null || root.Serving is null)
return PreparedPage.Failed(ProjectionPageStatus.Unavailable);
originParent = root;
}
@@ -395,9 +395,11 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
elapsed = Clock.GetElapsedTime(started, Clock.GetTimestamp());
if (elapsed < TimeSpan.Zero || elapsed >= budget.Timeout || linked.IsCancellationRequested) return Failed;
// #939: the origin's own verdict on this item — Denied, or a Good answer that no longer grants the operation — is a
// definitive refusal (the consumer answers BadUserAccessDenied), not a lapse to retry.
// definitive refusal (the consumer answers BadUserAccessDenied), not a lapse to retry. #957: so is NotFound — an
// origin answers a node its ACL now hides from this peer (or one outside its grant, #943) exactly like a missing
// one, so for a node this consumer already projected it is the same verdict, not a lapse.
if (results.Count == 1 && results[0].CorrelationId == "0" &&
(results[0].Status == DataItemStatus.Denied ||
(results[0].Status is DataItemStatus.Denied or DataItemStatus.NotFound ||
results[0].Status == DataItemStatus.Good && results[0].Value is { } granted && granted.View == previous.OriginMetadata.View &&
(binding.Mapping.AllowedOperations & required) == required &&
((granted.AllowedOperations & required) == 0 || required == DataOperations.Write && !granted.Writable)))