fix(perf): #996 Wave 4 — blob-free health probes, narrow data-connections load, off-thread coordinator acks + AdminOps audit, events page cap, capped reservations page

C-6: DeploymentQueries projects Deployment without ArtifactBlob (DbHealthProbe, readiness, ClusterOverview, DriverHost boot).
C-11/A-5: DraftSnapshotFactory.FromConfigDbForDataConnectionsAsync + one-parse-per-artifact LoadAppliedAsync + capped pickers.
H-6: ConfigPublishCoordinator persists acks off the actor thread (AckPersisted); deadline backlog kicked in parallel.
H-3: Restart/Reconnect reply = dispatch; ConfigEdit audit written off-mailbox, failure logged not surfaced.
U-6: ServerHistorian:MaxEventsPerRead (default 10000) pages HistoryReadEvents; advertised as MaxReturnEventValues.
A-8: /reservations active-only by default, projected, capped at 200.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Joseph Doherty
2026-12-03 10:58:50 -05:00
parent b9955f6946
commit ea976ffa81
31 changed files with 1184 additions and 104 deletions
@@ -114,7 +114,7 @@ else
<label class="form-label" for="export-id">Export ID</label><input id="export-id" class="form-control mb-2" @bind="e.DataExportId" disabled="@(e.DataExportRowId != Guid.Empty)" />
<label class="form-label" for="principal">Peer principal</label><input id="principal" class="form-control mb-2" @bind="e.PrincipalId" />
<label class="form-label" for="export-realm">Realm</label><select id="export-realm" class="form-select mb-2" @bind="e.Realm"><option value="@DataRealm.Raw">Raw</option><option value="@DataRealm.Uns">UNS</option></select>
<label class="form-label" for="export-root">Local export root</label><select id="export-root" class="form-select mb-2" value="@(e.RootKind + "|" + e.RootEntityId)" @onchange="args => SetExportRoot(e, args.Value?.ToString())"><option value="">Choose a root</option>@foreach (var p in ExportRoots(e.Realm)) { <option value="@p.Value">@p.Label</option> }</select>
<label class="form-label" for="export-root">Local export root</label><select id="export-root" class="form-select mb-2" value="@(e.RootKind + "|" + e.RootEntityId)" @onchange="args => SetExportRoot(e, args.Value?.ToString())"><option value="">Choose a root</option>@foreach (var p in ExportRoots(e.Realm)) { <option value="@p.Value">@p.Label</option> }</select><div class="form-text">Tag-level choices are limited to the first @MaxPickerTags; for others type the root below as <span class="mono">Kind|EntityId</span> (e.g. <span class="mono">RawTag|tag-id</span>).</div><label class="form-label" for="export-root-id">Export root (Kind|EntityId)</label><input id="export-root-id" class="form-control mb-2" value="@(e.RootKind + "|" + e.RootEntityId)" @onchange="args => SetExportRoot(e, args.Value?.ToString())" />
@Operations(e.AllowedOperations, v => e.AllowedOperations = v)
<label class="form-label" for="export-history-reads">Concurrent history reads per peer</label><input id="export-history-reads" type="number" min="1" max="@DataConnectionValidator.MaxConcurrentHistoryReadsLimit" class="form-control mb-2" @bind="e.MaxConcurrentHistoryReads" />
<label class="form-label" for="export-history-page">History values per page</label><input id="export-history-page" type="number" min="1" max="@DataConnectionValidator.MaxHistoryValuesPerPageLimit" class="form-control mb-2" @bind="e.MaxHistoryValuesPerPage" />
@@ -152,6 +152,8 @@ else
@code {
[Parameter] public string ClusterId { get; set; } = "";
/// <summary>Per-list cap on tag-level picker options (lmxopcua#996 / A-5): a 50k-tag cluster used to push 50k option elements per render. Larger sets use the typed-id fields.</summary>
private const int MaxPickerTags = 500;
private DraftSnapshot? _snapshot;
private DataConnectionEditorModel? _connection;
private DataExport? _export;
@@ -226,15 +228,15 @@ else
{
var drivers = _snapshot!.DriverInstances.Where(x => Same(x.ClusterId, ClusterId)).Select(x => x.DriverInstanceId).ToHashSet(StringComparer.OrdinalIgnoreCase);
var devices = _snapshot.Devices.Where(x => drivers.Contains(x.DriverInstanceId)).Select(x => x.DeviceId).ToHashSet(StringComparer.OrdinalIgnoreCase);
foreach (var tag in _snapshot.Tags.Where(x => devices.Contains(x.DeviceId))) yield return ($"RawTag|{tag.TagId}", $"Tag: {tag.Name} ({tag.TagId})");
foreach (var tag in _snapshot.Tags.Where(x => devices.Contains(x.DeviceId)).Take(MaxPickerTags)) yield return ($"RawTag|{tag.TagId}", $"Tag: {tag.Name} ({tag.TagId})");
}
else if (realm == DataRealm.Uns)
{
var areas = _snapshot!.UnsAreas.Where(x => Same(x.ClusterId, ClusterId)).Select(x => x.UnsAreaId).ToHashSet(StringComparer.OrdinalIgnoreCase);
var lines = _snapshot.UnsLines.Where(x => areas.Contains(x.UnsAreaId)).Select(x => x.UnsLineId).ToHashSet(StringComparer.OrdinalIgnoreCase);
var equipment = _snapshot.Equipment.Where(x => lines.Contains(x.UnsLineId)).Select(x => x.EquipmentId).ToHashSet(StringComparer.OrdinalIgnoreCase);
foreach (var tag in _snapshot.VirtualTags.Where(x => equipment.Contains(x.EquipmentId))) yield return ($"VirtualTag|{tag.VirtualTagId}", $"Virtual tag: {tag.Name} ({tag.VirtualTagId})");
foreach (var tag in _snapshot.UnsTagReferences.Where(x => equipment.Contains(x.EquipmentId))) yield return ($"UnsTagReference|{tag.UnsTagReferenceId}", $"Tag reference: {tag.UnsTagReferenceId}");
foreach (var tag in _snapshot.VirtualTags.Where(x => equipment.Contains(x.EquipmentId)).Take(MaxPickerTags)) yield return ($"VirtualTag|{tag.VirtualTagId}", $"Virtual tag: {tag.Name} ({tag.VirtualTagId})");
foreach (var tag in _snapshot.UnsTagReferences.Where(x => equipment.Contains(x.EquipmentId)).Take(MaxPickerTags)) yield return ($"UnsTagReference|{tag.UnsTagReferenceId}", $"Tag reference: {tag.UnsTagReferenceId}");
}
}
private IEnumerable<(string Id, string Label)> RemoteRoots(RemoteNamespaceMapping mapping)
@@ -252,7 +254,7 @@ else
foreach (var x in devices) yield return (x.DeviceId, $"Device: {x.Name} ({x.DeviceId})");
var deviceIds = devices.Select(x => x.DeviceId).ToHashSet(StringComparer.OrdinalIgnoreCase);
foreach (var x in _snapshot.TagGroups.Where(x => deviceIds.Contains(x.DeviceId))) yield return (x.TagGroupId, $"Tag group: {x.Name} ({x.TagGroupId})");
foreach (var x in _snapshot.Tags.Where(x => deviceIds.Contains(x.DeviceId))) yield return (x.TagId, $"Tag: {x.Name} ({x.TagId})");
foreach (var x in _snapshot.Tags.Where(x => deviceIds.Contains(x.DeviceId)).Take(MaxPickerTags)) yield return (x.TagId, $"Tag: {x.Name} ({x.TagId})");
}
else
{
@@ -4,6 +4,7 @@
@using Microsoft.EntityFrameworkCore
@using ZB.MOM.WW.OtOpcUa.Configuration
@using ZB.MOM.WW.OtOpcUa.Configuration.Entities
@using ZB.MOM.WW.OtOpcUa.Configuration.Queries
@inject IDbContextFactory<OtOpcUaConfigDbContext> DbFactory
@inject NavigationManager Nav
@@ -131,7 +132,7 @@ else
private bool _loaded;
private ServerCluster? _cluster;
private List<ClusterNode>? _nodes;
private Deployment? _lastDeployment;
private DeploymentSummary? _lastDeployment;
protected override async Task OnInitializedAsync()
{
@@ -144,9 +145,7 @@ else
.Where(n => n.ClusterId == ClusterId)
.OrderBy(n => n.NodeId)
.ToListAsync();
_lastDeployment = await db.Deployments.AsNoTracking()
.OrderByDescending(d => d.CreatedAtUtc)
.FirstOrDefaultAsync();
_lastDeployment = await DeploymentQueries.LatestSummary(db).FirstOrDefaultAsync();
}
_loaded = true;
}
@@ -3,7 +3,7 @@
@rendermode RenderMode.InteractiveServer
@using Microsoft.EntityFrameworkCore
@using ZB.MOM.WW.OtOpcUa.Configuration
@using ZB.MOM.WW.OtOpcUa.Configuration.Entities
@using ZB.MOM.WW.OtOpcUa.Configuration.Queries
@inject IDbContextFactory<OtOpcUaConfigDbContext> DbFactory
<PageErrorBoundary>
@@ -11,6 +11,7 @@
<div class="page-head">
<h1>External ID reservations</h1>
<span class="spacer"></span>
<label class="form-check-label"><input type="checkbox" class="form-check-input" checked="@_includeReleased" @onchange="ToggleReleased" /> Show released</label>
</div>
@if (_rows is null)
@@ -20,7 +21,7 @@
else
{
<section class="panel rise mt-3" style="animation-delay:.08s">
<h2 class="panel-head">@_rows.Count reservation@(_rows.Count == 1 ? "" : "s")</h2>
<h2 class="panel-head">@(_total > _rows.Count ? $"Showing {_rows.Count} of {_total}" : _total.ToString()) @(_includeReleased ? "" : "active ")reservation@(_total == 1 ? "" : "s")</h2>
@if (_rows.Count == 0)
{
<div style="padding:1rem" class="text-muted">No reservations yet.</div>
@@ -35,6 +36,7 @@ else
<th scope="col">Value</th>
<th scope="col">Equipment UUID</th>
<th scope="col">Cluster</th>
@if (_includeReleased) { <th scope="col">Released</th> }
</tr>
</thead>
<tbody>
@@ -45,6 +47,7 @@ else
<td><span class="mono">@r.Value</span></td>
<td><span class="mono small">@r.EquipmentUuid</span></td>
<td><span class="mono small">@r.ClusterId</span></td>
@if (_includeReleased) { <td><span class="mono small">@(r.ReleasedAt?.ToString("u") ?? "active")</span></td> }
</tr>
}
</tbody>
@@ -56,13 +59,24 @@ else
</PageErrorBoundary>
@code {
private List<ExternalIdReservation>? _rows;
private IReadOnlyList<ReservationRow>? _rows;
private int _total;
private bool _includeReleased;
protected override async Task OnInitializedAsync()
protected override async Task OnInitializedAsync() => await LoadAsync();
private async Task ToggleReleased(ChangeEventArgs e)
{
_includeReleased = e.Value is true;
await LoadAsync();
}
private async Task LoadAsync()
{
// Active rows only by default, projected to the shown columns and capped (#996 / A-8).
await using var db = await DbFactory.CreateDbContextAsync();
_rows = await db.ExternalIdReservations.AsNoTracking()
.OrderBy(r => r.Kind).ThenBy(r => r.Value)
.ToListAsync();
var page = await ReservationListQuery.LoadAsync(db, _includeReleased);
_rows = page.Rows;
_total = page.Total;
}
}
@@ -17,7 +17,7 @@ public sealed class DataConnectionAdminService(IDbContextFactory<OtOpcUaConfigDb
public async Task<DraftSnapshot> LoadAsync(CancellationToken ct = default)
{
await using var db = await factory.CreateDbContextAsync(ct);
return await DraftSnapshotFactory.FromConfigDbAsync(db, ct);
return await DraftSnapshotFactory.FromConfigDbForDataConnectionsAsync(db, ct);
}
/// <summary>Returns the last successfully applied artifact's connection revision per node, when available.</summary>
@@ -25,18 +25,27 @@ public sealed class DataConnectionAdminService(IDbContextFactory<OtOpcUaConfigDb
{
await using var db = await factory.CreateDbContextAsync(ct);
var nodes = await db.ClusterNodes.AsNoTracking().Where(n => n.ClusterId == clusterId).Select(n => n.NodeId).ToListAsync(ct);
var result = new List<AppliedConnection>();
// lmxopcua#996 (A-5): resolve each node's applied deployment id first, then fetch + inflate + parse each DISTINCT
// artifact once. Two nodes on the same deployment used to download and inflate the same blob twice, on every
// page open and after every save.
var nodeDeployment = new List<(string Node, Guid Deployment)>();
foreach (var node in nodes)
{
var deployment = await db.NodeDeploymentStates.AsNoTracking().Where(s => s.NodeId == node && s.Status == NodeDeploymentStatus.Applied)
.OrderByDescending(s => s.StartedAtUtc).Select(s => (Guid?)s.DeploymentId).FirstOrDefaultAsync(ct);
if (deployment is null) continue;
var blob = await db.Deployments.AsNoTracking().Where(d => d.DeploymentId == deployment).Select(d => d.ArtifactBlob).FirstOrDefaultAsync(ct);
if (deployment is not null) nodeDeployment.Add((node, deployment.Value));
}
var result = new List<AppliedConnection>();
foreach (var group in nodeDeployment.GroupBy(x => x.Deployment))
{
var deploymentId = group.Key;
var blob = await db.Deployments.AsNoTracking().Where(d => d.DeploymentId == deploymentId).Select(d => d.ArtifactBlob).FirstOrDefaultAsync(ct);
if (blob is not { Length: > 0 }) continue;
try
{
result.AddRange(DeploymentArtifact.ParseDataConnections(blob, node)
.Select(c => new AppliedConnection(node, c.DataConnectionId, c.Revision, c.Enabled)));
var perNode = DeploymentArtifact.ParseDataConnections(blob, group.Select(x => x.Node));
foreach (var (node, _) in group)
result.AddRange(perNode[node].Select(c => new AppliedConnection(node, c.DataConnectionId, c.Revision, c.Enabled)));
}
catch (Exception ex) when (ex is InvalidDataException or InvalidOperationException or System.Text.Json.JsonException)
{
@@ -50,7 +59,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 snapshot = await DraftSnapshotFactory.FromConfigDbForDataConnectionsAsync(db, ct);
var baseline = DataConnectionValidator.Validate(snapshot);
switch (row)
{
@@ -76,7 +85,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 snapshot = await DraftSnapshotFactory.FromConfigDbForDataConnectionsAsync(db, ct);
var baseline = DataConnectionValidator.Validate(snapshot);
switch (row)
{
@@ -104,8 +104,9 @@ public sealed class AdminOperationsActor : ReceiveActor
Receive<DeployComposed>(HandleDeployComposed);
Receive<DeployComposeFailed>(HandleDeployComposeFailed);
Receive<TestDriverConnect>(HandleTestDriverConnect);
ReceiveAsync<RestartDriver>(HandleRestartDriverAsync);
ReceiveAsync<ReconnectDriver>(HandleReconnectDriverAsync);
Receive<RestartDriver>(HandleRestartDriver);
Receive<ReconnectDriver>(HandleReconnectDriver);
Receive<DriverOperationAuditFailed>(HandleDriverOperationAuditFailed);
Receive<AcknowledgeAlarmCommand>(HandleAcknowledgeAlarm);
Receive<ShelveAlarmCommand>(HandleShelveAlarm);
}
@@ -773,64 +774,71 @@ public sealed class AdminOperationsActor : ReceiveActor
}
}
private async Task HandleRestartDriverAsync(RestartDriver msg)
/// <summary>
/// #996 (review H-3): a Restart/Reconnect REPORTS THE DISPATCH, which is what it does. It used to dispatch, then
/// write the <c>ConfigEdit</c> audit row inside the same <c>try</c> — so a ConfigDb failure answered "failed" for a
/// command that was already on its way to every node (the operator retried ⇒ a second restart, a second data gap),
/// and, as a <c>ReceiveAsync</c>, the audit write suspended the whole mailbox (one connect timeout per click
/// against an unreachable server; alarm acks and deploys queued behind it). Now both are synchronous receives:
/// dispatch, reply, and write the audit row off-thread; an audit failure is logged (with the full record) and
/// never changes the operator-visible result.
/// </summary>
private void HandleRestartDriver(RestartDriver msg) =>
DispatchDriverOperation(msg, "restart", msg.DriverInstanceId, msg.ActorByUserName, msg.CorrelationId,
new RestartDriverResult(true, null, msg.CorrelationId),
_ => new RestartDriverResult(false, ServerFault("RestartDriver", msg.CorrelationId), msg.CorrelationId));
private void HandleReconnectDriver(ReconnectDriver msg) =>
DispatchDriverOperation(msg, "reconnect", msg.DriverInstanceId, msg.ActorByUserName, msg.CorrelationId,
new ReconnectDriverResult(true, null, msg.CorrelationId),
_ => new ReconnectDriverResult(false, ServerFault("ReconnectDriver", msg.CorrelationId), msg.CorrelationId));
private void DispatchDriverOperation(
object command, string op, string driverInstanceId, string actor, object correlationId,
object success, Func<Exception, object> failure)
{
var replyTo = Sender;
try
{
// Broadcast to every DriverHostActor on every node via the driver-control DPS topic.
// Only the host that owns the instance will act; others ignore it (id not found in _children).
Dispatch(DriverControlTopic.Name, msg);
await using var db = await _dbFactory.CreateDbContextAsync();
db.ConfigEdits.Add(new ConfigEdit
{
EntityType = "DriverInstance",
EntityId = Guid.TryParse(msg.DriverInstanceId, out var guid) ? guid : Guid.Empty,
FieldsJson = $"{{\"op\":\"restart\",\"driverInstanceId\":{System.Text.Json.JsonSerializer.Serialize(msg.DriverInstanceId)}}}",
EditedBy = msg.ActorByUserName,
SourceNode = Akka.Cluster.Cluster.Get(Context.System).SelfAddress.Host ?? "unknown",
});
await db.SaveChangesAsync();
_log.Info("AdminOps: RestartDriver dispatched for {DriverInstanceId} by {User}",
msg.DriverInstanceId, msg.ActorByUserName);
replyTo.Tell(new RestartDriverResult(true, null, msg.CorrelationId));
// Broadcast to every DriverHostActor on every node via the driver-control topic. Only the host that owns the
// instance acts; others ignore it (id not found in _children).
Dispatch(DriverControlTopic.Name, command);
}
catch (Exception ex)
{
_log.Error(ex, "AdminOps: RestartDriver failed for {DriverInstanceId} (correlation {CorrelationId})", msg.DriverInstanceId, msg.CorrelationId);
replyTo.Tell(new RestartDriverResult(false, ServerFault("RestartDriver", msg.CorrelationId), msg.CorrelationId));
// The ONLY genuine failure: nothing was dispatched.
_log.Error(ex, "AdminOps: {Op} dispatch failed for {DriverInstanceId} (correlation {CorrelationId})", op, driverInstanceId, correlationId);
replyTo.Tell(failure(ex));
return;
}
}
private async Task HandleReconnectDriverAsync(ReconnectDriver msg)
{
var replyTo = Sender;
try
_log.Info("AdminOps: {Op} dispatched for {DriverInstanceId} by {User}", op, driverInstanceId, actor);
replyTo.Tell(success);
// Audit off the mailbox. Cluster state is read HERE (actor thread); the DB work is a pool-thread task.
var sourceNode = Akka.Cluster.Cluster.Get(Context.System).SelfAddress.Host ?? "unknown";
var factory = _dbFactory;
Task.Run(async () =>
{
// Broadcast to every DriverHostActor; only the one owning the instance reacts.
Dispatch(DriverControlTopic.Name, msg);
await using var db = await _dbFactory.CreateDbContextAsync();
await using var db = await factory.CreateDbContextAsync().ConfigureAwait(false);
db.ConfigEdits.Add(new ConfigEdit
{
EntityType = "DriverInstance",
EntityId = Guid.TryParse(msg.DriverInstanceId, out var guid) ? guid : Guid.Empty,
FieldsJson = $"{{\"op\":\"reconnect\",\"driverInstanceId\":{System.Text.Json.JsonSerializer.Serialize(msg.DriverInstanceId)}}}",
EditedBy = msg.ActorByUserName,
SourceNode = Akka.Cluster.Cluster.Get(Context.System).SelfAddress.Host ?? "unknown",
EntityId = Guid.TryParse(driverInstanceId, out var guid) ? guid : Guid.Empty,
FieldsJson = $"{{\"op\":\"{op}\",\"driverInstanceId\":{System.Text.Json.JsonSerializer.Serialize(driverInstanceId)}}}",
EditedBy = actor,
SourceNode = sourceNode,
});
await db.SaveChangesAsync();
_log.Info("AdminOps: ReconnectDriver dispatched for {DriverInstanceId} by {User}",
msg.DriverInstanceId, msg.ActorByUserName);
replyTo.Tell(new ReconnectDriverResult(true, null, msg.CorrelationId));
}
catch (Exception ex)
{
_log.Error(ex, "AdminOps: ReconnectDriver failed for {DriverInstanceId} (correlation {CorrelationId})", msg.DriverInstanceId, msg.CorrelationId);
replyTo.Tell(new ReconnectDriverResult(false, ServerFault("ReconnectDriver", msg.CorrelationId), msg.CorrelationId));
}
await db.SaveChangesAsync().ConfigureAwait(false);
}).PipeTo(Self, failure: ex => new DriverOperationAuditFailed(op, driverInstanceId, actor, correlationId, ex));
}
private void HandleDriverOperationAuditFailed(DriverOperationAuditFailed m) =>
_log.Warning(m.Error,
"AdminOps: the audit row for {Op} of {DriverInstanceId} by {User} could NOT be written (correlation {CorrelationId}); " +
"the command WAS dispatched and the operator was told so",
m.Op, m.DriverInstanceId, m.Actor, m.CorrelationId);
/// <summary>The off-thread ConfigEdit audit write for a dispatched driver operation failed (#996 / H-3).</summary>
private sealed record DriverOperationAuditFailed(string Op, string DriverInstanceId, string Actor, object CorrelationId, Exception Error);
}
@@ -109,6 +109,12 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
private readonly Dictionary<NodeId, PendingPersist> _unpersisted = new(NodeIdComparer);
private string? _lastPersistError;
/// <summary>Acks whose ConfigDb write is in flight on a pool thread (#996 / H-6), one per node.</summary>
private readonly Dictionary<NodeId, ApplyAck> _persisting = new(NodeIdComparer);
/// <summary>A newer ack for a node that already has a write in flight; started when that write returns (newest wins).</summary>
private readonly Dictionary<NodeId, ApplyAck> _pendingBehind = new(NodeIdComparer);
/// <summary>
/// Acks counted without a persisted row (a rejected write, or the deferral cap) — re-sent across a restart, since
/// no row records them (fourth review M1). Dropped once a later persist of that node succeeds.
@@ -250,6 +256,7 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
{
Receive<DispatchDeployment>(HandleDispatch);
Receive<ApplyAck>(HandleAck);
Receive<AckPersisted>(HandleAckPersisted);
Receive<RetryAckPersist>(HandleRetryAckPersist);
Receive<DeadlineElapsed>(HandleDeadline);
Receive<SubscribeAck>(_ => { /* DPS subscribe confirmation */ });
@@ -278,6 +285,9 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
// Timers die with this incarnation; the mailbox survives. Re-send every ack that is still unpersisted so the
// next incarnation (which stashes while Loading) persists and counts it — its node will not resend (M2).
foreach (var pending in _unpersisted.Values) Self.Tell(pending.Ack);
// ...and acks whose write was in flight: its outcome is unknown to the next incarnation (#996).
foreach (var inflight in _persisting.Values) Self.Tell(inflight);
foreach (var behind in _pendingBehind.Values) Self.Tell(behind);
// Fourth review M1: so are acks counted only FROM MEMORY (rejected writes, the deferral cap) — the outcome they
// fed has not been written yet, and without this the next incarnation would wait on their nodes forever.
foreach (var ack in _memoryOnlyAcks.Values) Self.Tell(ack);
@@ -623,28 +633,81 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
// Persist FIRST: the row is the system of record (driver-only nodes never write their own, and nodes do not
// resend). A throw here used to restart the actor and drop the ack; it is re-queued instead.
if (!TryPersistAck(msg)) return;
if (_acks.Count < _expectedAcks.Count) return;
CompleteFromAcks();
StartAckPersist(msg);
}
/// <summary>
/// Persists an ack and, only on success, counts it (and drops any older unpersisted ack of that node, with its
/// retry timer — review L3). On failure the ack is held in <see cref="_unpersisted"/> and retried on a backoff.
/// lmxopcua#996 (review H-6): the ack write runs OFF the actor thread and its outcome comes back as
/// <see cref="AckPersisted"/>. The write used to be a blocking <c>SaveChanges</c> in the handler, so with the
/// ConfigDb unreachable (no retry strategy ⇒ a full connect timeout per call) N acks, N retry ticks and the
/// deadline's backlog re-try serialised N × timeout on the one coordinator thread, delaying every other message
/// (a new dispatch, the deadline decision) by minutes. Now the timeouts overlap and the mailbox stays live.
/// One write per node at a time; a newer ack for a node with a write in flight is held in
/// <see cref="_pendingBehind"/> and started when that write returns.
/// </summary>
/// <returns><see langword="true"/> when the ack is persisted and counted.</returns>
private bool TryPersistAck(ApplyAck msg)
private void StartAckPersist(ApplyAck msg)
{
try
if (_persisting.ContainsKey(msg.NodeId))
{
PersistNodeAck(msg);
_pendingBehind[msg.NodeId] = msg;
return;
}
catch (Exception ex) when (IsPoison(ex))
_persisting[msg.NodeId] = msg;
var factory = _dbFactory;
// Task.Run: a factory/provider that throws synchronously still faults the TASK, never this thread.
Task.Run(() => PersistNodeAck(factory, msg)).PipeTo(
Self,
success: () => new AckPersisted(msg, null),
failure: ex => new AckPersisted(msg, ex is AggregateException { InnerException: { } inner } ? inner : ex));
}
/// <summary>The outcome of an off-thread ack write: counts the ack on success, queues its retry on failure.</summary>
private void HandleAckPersisted(AckPersisted result)
{
var node = result.Ack.NodeId;
_persisting.Remove(node);
if (_current is null || result.Ack.DeploymentId != _current.Value)
{
// The deployment closed (or was superseded) while the write ran: nothing to count or retry.
_pendingBehind.Remove(node);
return;
}
var counted = ApplyPersistOutcome(result.Ack, result.Error);
if (_pendingBehind.Remove(node, out var next) && _current is not null && next.DeploymentId == _current.Value)
StartAckPersist(next);
if (_current is null) return;
if (counted && _acks.Count >= _expectedAcks.Count && _expectedAcks.Count > 0)
{
CompleteFromAcks();
return;
}
// A deadline that was deferred on unpersisted acks decides as soon as the last write lands, rather than
// waiting out its re-armed delay.
if (_deadlineDeferredSinceUtc is not null && _unpersisted.Count == 0 && _persisting.Count == 0)
{
Timers.Cancel(DeadlineTimerKey);
Self.Tell(new DeadlineElapsed(_current.Value));
}
}
/// <summary>
/// Counts a persisted ack (and drops any older unpersisted ack of that node, with its retry timer — review L3).
/// On failure the ack is held in <see cref="_unpersisted"/> and retried on a backoff.
/// </summary>
/// <returns><see langword="true"/> when the ack is now counted.</returns>
private bool ApplyPersistOutcome(ApplyAck msg, Exception? error)
{
if (error is not null && IsPoison(error))
{
// Third review #1: a write the DB REJECTS (constraint, truncation, …) fails identically on every retry;
// retrying it forever wedged the deployment (the deadline deferred on it) and every later deploy. The
// node DID ack, so count it from memory and say loudly that its row is not recorded.
_log.Error(ex,
_log.Error(error,
"The ApplyAck from {Node} for {Id} ({Outcome}) was REJECTED by the ConfigDb and will not be retried; " +
"counting it from memory. Its NodeDeploymentState row stays unrecorded",
msg.NodeId, msg.DeploymentId, msg.Outcome);
@@ -653,8 +716,10 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
CountAck(msg);
return true;
}
catch (Exception ex)
if (error is not null)
{
var ex = error;
var attempts = _unpersisted.TryGetValue(msg.NodeId, out var prior) ? prior.Attempts + 1 : 1;
_unpersisted[msg.NodeId] = new PendingPersist(msg, attempts);
_lastPersistError = ex.Message;
@@ -728,6 +793,8 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
private void HandleRetryAckPersist(RetryAckPersist msg)
{
if (!_unpersisted.TryGetValue(msg.Ack.NodeId, out var pending) || !ReferenceEquals(pending.Ack, msg.Ack)) return;
// A write for this node is already in flight (e.g. kicked by the deadline): its outcome re-arms the retry itself.
if (_persisting.ContainsKey(msg.Ack.NodeId)) return;
HandleAck(msg.Ack);
}
@@ -751,9 +818,10 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
private static string AckRetryTimerKey(NodeId node) => $"ack-retry:{node.Value.ToUpperInvariant()}";
private void PersistNodeAck(ApplyAck msg)
/// <summary>Writes one node's ack row. Static and touching no actor state: it runs on a pool thread (#996 / H-6).</summary>
private static void PersistNodeAck(IDbContextFactory<OtOpcUaConfigDbContext> dbFactory, ApplyAck msg)
{
using var db = _dbFactory.CreateDbContext();
using var db = dbFactory.CreateDbContext();
var row = db.NodeDeploymentStates
.FirstOrDefault(x => x.NodeId == msg.NodeId.Value && x.DeploymentId == msg.DeploymentId.Value);
if (row is null) return;
@@ -830,11 +898,14 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
}
// Review M2: an ack that ARRIVED but is not yet persisted must never be timed out as "no ack from" its node.
// Persist the backlog now; if the DB still refuses, defer the decision (the terminal write needs it too).
if (_unpersisted.Count > 0)
if (_unpersisted.Count > 0 || _persisting.Count > 0)
{
foreach (var pending in _unpersisted.Values.ToList()) TryPersistAck(pending.Ack);
// #996 / H-6: kick the whole backlog off-thread at once (the connect timeouts overlap, they no longer
// serialise on this thread); the deadline is re-armed below and also fires early once the last write lands.
foreach (var pending in _unpersisted.Values.ToList()) StartAckPersist(pending.Ack);
_deadlineDeferredSinceUtc ??= DateTime.UtcNow;
if (_unpersisted.Count > 0 && DateTime.UtcNow - _deadlineDeferredSinceUtc.Value >= MaxDeadlineDeferral)
var capped = DateTime.UtcNow - _deadlineDeferredSinceUtc.Value >= MaxDeadlineDeferral;
if (capped)
{
// Third review #1: bounded. Past the cap the outcome is decided from what was RECEIVED — the nodes did
// ack — rather than waiting on rows that may never be writable.
@@ -848,13 +919,15 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
_memoryOnlyAcks[pending.Ack.NodeId] = pending.Ack;
CountAck(pending.Ack);
}
// A write still in flight at the cap is decided from memory too (its late outcome is discarded).
foreach (var inflight in _persisting.Values) CountAck(inflight);
}
if (_unpersisted.Count > 0)
else if (_unpersisted.Count > 0 || _persisting.Count > 0)
{
var delay = Backoff(_unpersisted.Values.Min(p => p.Attempts));
var delay = _unpersisted.Count > 0 ? Backoff(_unpersisted.Values.Min(p => p.Attempts)) : Backoff(1);
_log.Warning(
"Deployment {Id} reached its apply deadline with {Count} received ack(s) not yet persisted; deferring " +
"the outcome {Delay} until they are", _current.Value, _unpersisted.Count, delay);
"the outcome {Delay} until they are", _current.Value, _unpersisted.Count + _persisting.Count, delay);
Timers.StartSingleTimer(DeadlineTimerKey, msg, delay);
return;
}
@@ -936,6 +1009,7 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
ReportPersistBacklog();
}
_memoryOnlyAcks.Clear();
_pendingBehind.Clear();
_current = null;
_expectedAcks.Clear();
_acks.Clear();
@@ -945,6 +1019,9 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
private const string DeadlineTimerKey = "apply-deadline";
private const string LoadRetryTimerKey = "recovery-load-retry";
/// <summary>The outcome of an off-thread ack write (#996 / H-6): <see langword="null"/> error = persisted.</summary>
private sealed record AckPersisted(ApplyAck Ack, Exception? Error);
/// <summary>An ack whose persist failed, re-delivered by its retry timer.</summary>
private sealed record RetryAckPersist(ApplyAck Ack);
@@ -10,6 +10,7 @@ using ZB.MOM.WW.Health.EntityFrameworkCore;
using ZB.MOM.WW.LocalDb.Replication;
using ZB.MOM.WW.OtOpcUa.Cluster;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.Configuration.Queries;
using ZB.MOM.WW.OtOpcUa.Host.Configuration;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
@@ -85,7 +86,7 @@ public static class HealthEndpoints
tags: new[] { ZbHealthTags.Ready, ZbHealthTags.Active },
args: new DatabaseHealthCheckOptions<OtOpcUaConfigDbContext>
{
ProbeQuery = static (db, ct) => db.Deployments.AsNoTracking().Take(1).ToListAsync(ct),
ProbeQuery = static (db, ct) => DeploymentQueries.ProbeQuery(db).ToListAsync(ct),
});
// lmxopcua#868: Degraded (still 200) while the deploy coordinator singleton on this node is retrying
@@ -452,6 +452,7 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
_server.NodeManager.HistoryReadBatchParallelism = _serverHistorianOptions.HistoryReadBatchParallelism;
_server.NodeManager.MaxConcurrentHistoryReadBatches = _serverHistorianOptions.MaxConcurrentHistoryReadBatches;
_server.NodeManager.HistoryReadDeadline = _serverHistorianOptions.HistoryReadDeadline;
_server.NodeManager.MaxEventsPerRead = _serverHistorianOptions.MaxEventsPerRead;
// HistoryUpdate is Primary-only (BadInvalidState elsewhere, and closed until this node's first
// redundancy snapshot) and refuses a SourceTimestamp beyond now + HistoryUpdateMaxFutureSkew (BadOutOfRange),
@@ -175,6 +175,30 @@ internal static class HistoryPaging
}
}
/// <summary>
/// Advertise the server events cap as <c>HistoryServerCapabilities/MaxReturnEventValues</c> (Part 11 §5.4.2; 0 = no
/// limit), the events twin of <see cref="AdvertiseMaxReturnDataValues"/>. Idempotent, never throws, advisory only.
/// </summary>
/// <param name="server">The running server (null before start).</param>
/// <param name="maxEventsPerRead">The cap (&lt;= 0 advertises 0 = no limit).</param>
/// <returns><c>true</c> when the property was written.</returns>
public static bool AdvertiseMaxReturnEventValues(IServerInternal? server, int maxEventsPerRead)
{
if (server?.DiagnosticsNodeManager is not DiagnosticsNodeManager diagnostics) return false;
try
{
var capabilities = diagnostics.GetDefaultHistoryCapabilitiesAsync().AsTask().GetAwaiter().GetResult();
if (capabilities?.MaxReturnEventValues is not { } property) return false;
property.Value = (uint)Math.Max(0, maxEventsPerRead);
property.ClearChangeMasks(diagnostics.SystemContext, false);
return true;
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// Decide whether a just-returned read is "full" and therefore MAY be followed by more data —
/// the signal to emit a continuation point. A read is full when it was issued with a finite request
@@ -650,6 +650,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
// #736: HistoryServerCapabilities/MaxReturnDataValues (i=11273) carries the source's raw-page cap
// (0 = unlimited), re-synced on every source assignment like the aggregate set above.
HistoryPaging.AdvertiseMaxReturnEventValues(Server, MaxEventsPerRead);
if (!HistoryPaging.AdvertiseMaxReturnDataValues(Server, source.MaxRawValuesPerRead))
{
_logger.LogWarning(
@@ -918,6 +919,30 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
/// </summary>
public int MaxConcurrentHistoryReadBatches { get; set; } = DefaultMaxConcurrentHistoryReadBatches;
/// <summary>The default of <see cref="MaxEventsPerRead"/>: 10 000 events per HistoryReadEvents page.</summary>
public const int DefaultMaxEventsPerRead = 10_000;
private int _maxEventsPerRead = DefaultMaxEventsPerRead;
/// <summary>
/// The most events ONE HistoryReadEvents page returns for a node, and the most the backend is asked for in one read
/// (lmxopcua#996, review U-6) — the events twin of the raw cap <c>ServerHistorian:MaxRawValuesPerRead</c>. A request's
/// <c>NumValuesPerNode = 0</c> ("all values") no longer materialises a whole window in memory (backend list, multi-source
/// merge, per-event field lists, encoder): it is served as pages of at most this many events, each with a continuation
/// point (Part 11 allows fewer than requested with one); a larger <c>NumValuesPerNode</c> is paged at it too. Advertised as
/// <c>HistoryServerCapabilities/MaxReturnEventValues</c>. Mirrors <c>ServerHistorianOptions.MaxEventsPerRead</c>; the
/// Host sets it at <c>StartAsync</c>. Non-positive = unbounded (the pre-#996 behaviour).
/// </summary>
public int MaxEventsPerRead
{
get => Volatile.Read(ref _maxEventsPerRead);
set
{
Volatile.Write(ref _maxEventsPerRead, value);
HistoryPaging.AdvertiseMaxReturnEventValues(Server, value);
}
}
/// <summary>The CPU-scaled default of <see cref="MaxConcurrentHistoryReadBatches"/>: <c>clamp(2 × ProcessorCount, 4, 16)</c>.</summary>
public static int DefaultMaxConcurrentHistoryReadBatches { get; } = Math.Clamp(Environment.ProcessorCount * 2, 4, 16);
@@ -9453,6 +9478,13 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
}
}
// #996 (U-6): the server's own per-page event ceiling. Applied AFTER the request/cursor normalisation above (an
// end-only 0-count read keeps its forward meaning) and before the cursor is built, so the capped size is the
// page size the cursor carries: 0 ("all") and any larger N become pages of the cap, each with a continuation point.
var eventCap = MaxEventsPerRead;
if (eventCap > 0 && (numValuesPerNode == 0 || numValuesPerNode > (uint)eventCap))
numValuesPerNode = (uint)eventCap;
// A reverse read on a backend that cannot read newest-first (the Gateway) is never sent there (it is refused
// here); instead it is walked back from bounded forward reads — the raw walk, with ties ordered by
// EventId because the gateway orders by event time only. Decided by the capability, not by catching an
@@ -22,6 +22,26 @@ public static partial class DeploymentArtifact
return parsed.ParseDataConnections(nodeId);
}
/// <summary>
/// Read the node-effective data connections of SEVERAL nodes from one artifact, inflating and opening the blob
/// once (lmxopcua#996 / A-5: two nodes on one deployment used to inflate the same blob twice).
/// </summary>
/// <param name="blob">The artifact blob.</param>
/// <param name="nodeIds">The nodes to project for.</param>
/// <returns>One entry per distinct node id (case-insensitive).</returns>
public static IReadOnlyDictionary<string, IReadOnlyList<DataConnection>> ParseDataConnections(
ReadOnlySpan<byte> blob,
IEnumerable<string> nodeIds
)
{
using var parsed = Open(blob.ToArray());
var result = new Dictionary<string, IReadOnlyList<DataConnection>>(StringComparer.OrdinalIgnoreCase);
foreach (var node in nodeIds)
if (!result.ContainsKey(node))
result[node] = parsed.ParseDataConnections(node);
return result;
}
/// <summary>Read the node-effective data exports from an artifact.</summary>
public static IReadOnlyList<DataExport> ParseDataExports(ReadOnlySpan<byte> blob, string nodeId)
{
@@ -1477,12 +1477,15 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
return;
}
var deployment = db.Deployments
// Hash only: the whole row drags the multi-MB ArtifactBlob (#996 / C-6).
var revisionHash = db.Deployments
.AsNoTracking()
.FirstOrDefault(d => d.DeploymentId == latest.DeploymentId);
var revision = deployment is null
.Where(d => d.DeploymentId == latest.DeploymentId)
.Select(d => d.RevisionHash)
.FirstOrDefault();
var revision = revisionHash is null
? (RevisionHash?)null
: RevisionHash.Parse(deployment.RevisionHash);
: RevisionHash.Parse(revisionHash);
switch (latest.Status)
{
@@ -2,6 +2,7 @@ using Akka.Actor;
using Akka.Event;
using Microsoft.EntityFrameworkCore;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.Configuration.Queries;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Health;
@@ -96,7 +97,8 @@ public sealed class DbHealthProbeActor : ReceiveActor, IWithTimers
// Local to this lease — the pool resets it on return (see DriverHostActor.LoadArtifactBlob).
if (db.Database.IsRelational())
db.Database.SetCommandTimeout(CommandTimeout);
_ = db.Deployments.AsNoTracking().Take(1).ToList();
// Id-only projection: a whole Deployment row drags ArtifactBlob (#996 / C-6).
_ = DeploymentQueries.ProbeQuery(db).ToList();
return new DbHealthStatus(true, DateTime.UtcNow, null);
}
catch (Exception ex)
@@ -225,6 +225,20 @@ public sealed class ServerHistorianOptions
/// </summary>
public int MaxRawValuesPerRead { get; init; } = DefaultMaxRawValuesPerRead;
/// <summary>The default of <see cref="MaxEventsPerRead"/>: 10 000 events per HistoryReadEvents page.</summary>
public const int DefaultMaxEventsPerRead = 10_000;
/// <summary>
/// Every backend: the most events the server returns on ONE HistoryReadEvents page and asks a backend for in one read
/// (lmxopcua#996, review U-6) — the events twin of <see cref="MaxRawValuesPerRead"/>. A client's
/// <c>NumValuesPerNode = 0</c> ("all values") or any larger N is served as pages of at most this many events, each with
/// a continuation point (Part 11 allows fewer values than requested with one), so a whole-history read of an
/// alarm-owning folder can no longer buffer millions of events (several times over) and fail at encode time. Advertised as
/// <c>HistoryServerCapabilities/MaxReturnEventValues</c>. Default 10 000. Non-positive = unbounded, the pre-#996
/// behaviour (a <see cref="Validate"/> warning).
/// </summary>
public int MaxEventsPerRead { get; init; } = DefaultMaxEventsPerRead;
/// <summary>
/// <see cref="MaxRawValuesPerRead"/> as the backends and the node manager apply it: <c>0</c> (unbounded) when
/// non-positive, otherwise at least <see cref="MinMaxRawValuesPerRead"/>. The one place the rule lives.
@@ -285,6 +299,8 @@ public sealed class ServerHistorianOptions
warnings.Add($"ServerHistorian:MaxConcurrentHistoryReadBatches is {MaxConcurrentHistoryReadBatches} — must be > 0; the process-wide HistoryRead batch limiter is disabled.");
if (MaxTimeWeightedRawRows <= 0)
warnings.Add($"ServerHistorian:MaxTimeWeightedRawRows is {MaxTimeWeightedRawRows} — must be > 0; time-weighted aggregate reads on the SqlServer/QuestDb backends stream an unbounded number of raw samples.");
if (MaxEventsPerRead <= 0)
warnings.Add($"ServerHistorian:MaxEventsPerRead is {MaxEventsPerRead} — must be > 0; HistoryRead-Events pages are unbounded, so a client asking for a whole window (NumValuesPerNode = 0) materialises every event in memory.");
if (MaxRawValuesPerRead <= 0)
warnings.Add($"ServerHistorian:MaxRawValuesPerRead is {MaxRawValuesPerRead} — must be > 0; HistoryRead-Raw pages and backend raw reads are unbounded, so a client asking for a whole window (NumValuesPerNode = 0) materialises every sample in memory.");
else if (MaxRawValuesPerRead < MinMaxRawValuesPerRead)