Merge #977: restart restores last Applied deployment, planner covers every composition field, degraded/revision/restart bookkeeping, superseded deployment closed

This commit is contained in:
Joseph Doherty
2026-12-03 10:47:07 -05:00
14 changed files with 1215 additions and 33 deletions
@@ -527,6 +527,13 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
guardRowVersion = guard?.RowVersion;
}
// Gitea #977 (H-4): a DIFFERENT deployment is still in flight. Adopting the new one overwrites _current, clears
// the acks and replaces the single deadline timer — so nothing would ever write a terminal status for the old
// one: its row stayed AwaitingApplyAcks forever and AdminOps refused every later deploy as
// AnotherDeploymentInFlight. Close it first (TimedOut, only if still in flight, with a reason naming the
// successor), then adopt the new one.
if (_current is { } prior && prior != msg.DeploymentId) CloseSuperseded(prior, msg.DeploymentId);
_current = msg.DeploymentId;
_acks.Clear();
_degraded.Clear();
@@ -602,6 +609,44 @@ public sealed class ConfigPublishCoordinator : ReceiveActor, IWithTimers, IWithU
}
}
/// <summary>
/// Gitea #977 (H-4): writes the terminal <see cref="DeploymentStatus.TimedOut"/> for the in-flight deployment
/// <paramref name="prior"/> that <paramref name="successor"/> is about to replace, and resets the per-deployment
/// state. Conditioned on the row still being in flight (a row something else already closed is left alone), and
/// never fatal: a failed write is logged and the new dispatch proceeds — the AdminOps lost-dispatch closure and
/// the coordinator's recovery remain the backstops for a row this could not close.
/// </summary>
private void CloseSuperseded(DeploymentId prior, DeploymentId successor)
{
var acked = _acks.Count;
var expected = _expectedAcks.Count;
try
{
using var db = _dbFactory.CreateDbContext();
UpdateDeploymentStatus(db, prior, DeploymentStatus.TimedOut, onlyIfInFlight: true);
var entry = TrackStub(db, prior, onlyIfInFlight: true);
if (entry is not null)
{
entry.Entity.FailureReason = Truncate(
$"Superseded by deployment {successor} before its acks completed ({acked}/{expected} landed). " +
"Its nodes were dispatched the newer deployment instead; redeploy this revision if it is still wanted.");
entry.Property(x => x.FailureReason).IsModified = true;
}
db.SaveChanges();
_log.Warning(
"Deployment {Id} was still in flight ({Acked}/{Total} acks) when deployment {Next} was dispatched — closed as TimedOut (superseded)",
prior, acked, expected, successor);
}
catch (Exception ex)
{
_log.Error(ex,
"Deployment {Id} was superseded by {Next} but could not be closed; it may stay in flight until recovery or the lost-dispatch closure ends it",
prior, successor);
}
ResetForNext();
}
private void HandleAck(ApplyAck msg)
{
if (_current is null || msg.DeploymentId != _current.Value)
@@ -82,11 +82,23 @@ public sealed class AddressSpaceApplier
/// </summary>
/// <param name="plan">The plan to apply.</param>
/// <returns>A AddressSpaceApplyOutcome summarizing the applied changes.</returns>
public AddressSpaceApplyOutcome Apply(AddressSpacePlan plan)
public AddressSpaceApplyOutcome Apply(AddressSpacePlan plan) => Apply(plan, forceRebuild: false);
/// <summary>
/// <see cref="Apply(AddressSpacePlan)"/>, optionally forcing a full rebuild whatever the plan's kind. Gitea #977
/// (R-20): a caller whose diff BASELINE is not known to match the served address space (the publish actor after a
/// supervision restart reset its last-applied composition to empty while the node manager kept every node) cannot
/// trust a surgical apply — removed nodes would never be removed and in-place attribute edits would be skipped — so
/// it rebuilds once, even for an otherwise empty plan.
/// </summary>
/// <param name="plan">The plan to apply.</param>
/// <param name="forceRebuild">Rebuild the sink's address space regardless of the plan's classification.</param>
/// <returns>A AddressSpaceApplyOutcome summarizing the applied changes.</returns>
public AddressSpaceApplyOutcome Apply(AddressSpacePlan plan, bool forceRebuild)
{
ArgumentNullException.ThrowIfNull(plan);
if (plan.IsEmpty)
if (plan.IsEmpty && !forceRebuild)
{
_logger.LogDebug("AddressSpaceApplier: plan is empty; skipping sink writes");
return new AddressSpaceApplyOutcome(RemovedNodes: 0, AddedNodes: 0, ChangedNodes: 0, RebuildCalled: false);
@@ -110,18 +122,20 @@ public sealed class AddressSpaceApplier
// removed-vtag-only deploy. v3 Batch 4: removed raw containers/tags + UNS reference variables are
// likewise real removals.
removedCount += plan.RemovedEquipmentVirtualTags.Count +
plan.RemovedRawContainers.Count + plan.RemovedRawTags.Count + plan.RemovedUnsReferenceVariables.Count;
plan.RemovedRawContainers.Count + plan.RemovedRawTags.Count + plan.RemovedUnsReferenceVariables.Count +
plan.RemovedUnsAreas.Count + plan.RemovedUnsLines.Count + plan.RemovedVirtualTagFolders.Count;
var changedCount =
plan.ChangedEquipment.Count + plan.ChangedDrivers.Count + plan.ChangedAlarms.Count +
plan.ChangedEquipmentVirtualTags.Count +
plan.ChangedRawContainers.Count + plan.ChangedRawTags.Count + plan.ChangedUnsReferenceVariables.Count +
// A UNS Area/Line rename is an in-place change to an existing folder node.
plan.RenamedFolders.Count;
plan.RenamedFolders.Count + plan.ChangedEquipmentScriptedAlarms.Count;
var addedCount =
plan.AddedEquipment.Count + plan.AddedDrivers.Count + plan.AddedAlarms.Count +
plan.AddedEquipmentVirtualTags.Count +
plan.AddedRawContainers.Count + plan.AddedRawTags.Count + plan.AddedUnsReferenceVariables.Count;
plan.AddedRawContainers.Count + plan.AddedRawTags.Count + plan.AddedUnsReferenceVariables.Count +
plan.AddedUnsAreas.Count + plan.AddedUnsLines.Count;
// Classify the plan and route each delta class to its MINIMAL mutation instead of
// rebuilding the world for any topology change. AddressSpaceChangeClassifier is a pure policy over
@@ -147,7 +161,7 @@ public sealed class AddressSpaceApplier
// ChangedDrivers is node-inert (routes through DriverHostActor's spawn plan) — the classifier leaves
// a driver-only plan AttributeOnly, so it never rebuilds here.
var kind = AddressSpaceChangeClassifier.Classify(plan);
var mustRebuild = kind is AddressSpaceChangeKind.Rebuild;
var mustRebuild = forceRebuild || kind is AddressSpaceChangeKind.Rebuild;
// PureRemove + AddRemoveMix both run the in-place remove pass below (AddRemoveMix's adds are handled
// afterward by the publish actor's Materialise passes + announce).
var hasRemovePass = kind is AddressSpaceChangeKind.PureRemove or AddressSpaceChangeKind.AddRemoveMix;
@@ -358,6 +372,15 @@ public sealed class AddressSpaceApplier
if (!SafeRemoveVariable(surgical, nodeId, AddressSpaceRealm.Uns)) return false;
}
// #977 U-9 — a VirtualTag sub-folder no remaining VirtualTag uses goes with its last variable. The folder is a
// plain UNS folder, and RemoveEquipmentSubtree removes any indexed folder by id (the name predates this use);
// it runs after the variable removals above, so the folder is empty by then. Unknown ⇒ false ⇒ the rebuild
// ratchet, as for every other surgical remove.
foreach (var f in plan.RemovedVirtualTagFolders.Where(f => NotSubsumed(f.EquipmentId)))
{
if (!SafeRemoveEquipmentSubtree(surgical, UnsSubFolder(f.EquipmentId, f.FolderPath), AddressSpaceRealm.Uns)) return false;
}
// Removed scripted alarms for surviving equipment — the terminal RemovedConditionState was already
// written by the top-of-Apply removal block; here we tear the condition node down in place.
foreach (var alarm in plan.RemovedAlarms.Where(a => NotSubsumed(a.EquipmentId)))
@@ -365,6 +388,14 @@ public sealed class AddressSpaceApplier
if (!SafeRemoveAlarmCondition(surgical, alarm.ScriptedAlarmId, AddressSpaceRealm.Uns)) return false;
}
// #977 U-2 — a scripted condition that stops existing without its thin row going: the alarm was DISABLED (or its
// predicate script vanished). Terminal removed state first, so a subscriber sees it end, then the in-place remove.
foreach (var alarm in plan.ScriptedConditionRemoves().Where(a => NotSubsumed(a.EquipmentId)))
{
if (!SafeWriteAlarmCondition(alarm.ScriptedAlarmId, RemovedConditionState, ts, AddressSpaceRealm.Uns)) failedNodes++;
if (!SafeRemoveAlarmCondition(surgical, alarm.ScriptedAlarmId, AddressSpaceRealm.Uns)) return false;
}
// v3 Batch 4 — removed UNS reference variables (Uns realm, plain value nodes): terminal Bad then
// in-place remove.
//
@@ -399,6 +430,18 @@ public sealed class AddressSpaceApplier
if (!SafeRemoveEquipmentSubtree(surgical, eq.EquipmentId, AddressSpaceRealm.Uns)) return false;
}
// #977 U-3 — removed UNS Lines, then removed Areas (children before parents), AFTER their equipment above. The
// folder ids are the line/area ids MaterialiseHierarchy placed them at. A folder that still had live content
// would be taken with it, but nothing can: an equipment moved off a removed line is a ChangedEquipment (rebuild).
foreach (var line in plan.RemovedUnsLines)
{
if (!SafeRemoveEquipmentSubtree(surgical, line.UnsLineId, AddressSpaceRealm.Uns)) return false;
}
foreach (var area in plan.RemovedUnsAreas)
{
if (!SafeRemoveEquipmentSubtree(surgical, area.UnsAreaId, AddressSpaceRealm.Uns)) return false;
}
// v3 Batch 4 — removed RAW tags (Raw realm): an alarm-bearing raw tag is a condition node (terminal
// RemovedConditionState + RemoveAlarmConditionNode); a plain raw value tag is a variable (terminal Bad
// + RemoveVariableNode).
@@ -525,8 +568,23 @@ public sealed class AddressSpaceApplier
// folder is a UNS-realm node, announced in the Uns realm like every id this method returns. Added RAW
// containers/tags have Raw-realm parents and are computed separately (ComputeRawAddAnnouncements).
foreach (var v in plan.AddedUnsReferenceVariables) ids.Add(v.EquipmentId);
foreach (var eq in plan.AddedEquipment)
ids.Add(string.IsNullOrWhiteSpace(eq.UnsLineId) ? eq.EquipmentId : eq.UnsLineId);
// #977: a condition enabled in place hangs under its equipment folder.
foreach (var a in plan.ScriptedConditionAdds()) ids.Add(a.EquipmentId);
// Folders: each added folder announces its parent — unless that parent is ITSELF added in this plan (its own
// announcement covers the whole new subtree, as in ComputeRawAddAnnouncements). An added Area hangs under the
// shared root, which has no announceable id, so it announces itself, as does an equipment with no line.
var addedFolders = new HashSet<string>(StringComparer.Ordinal);
foreach (var a in plan.AddedUnsAreas) addedFolders.Add(a.UnsAreaId);
foreach (var l in plan.AddedUnsLines) addedFolders.Add(l.UnsLineId);
void AnnounceFolder(string nodeId, string? parentNodeId)
{
if (string.IsNullOrWhiteSpace(parentNodeId)) ids.Add(nodeId);
else if (!addedFolders.Contains(parentNodeId)) ids.Add(parentNodeId);
}
foreach (var eq in plan.AddedEquipment) AnnounceFolder(eq.EquipmentId, eq.UnsLineId);
foreach (var line in plan.AddedUnsLines) AnnounceFolder(line.UnsLineId, line.UnsAreaId);
foreach (var area in plan.AddedUnsAreas) AnnounceFolder(area.UnsAreaId, null);
var list = ids.ToList();
list.Sort(StringComparer.Ordinal);
@@ -93,7 +93,15 @@ public static class AddressSpaceChangeClassifier
plan.ChangedAlarms.Count > 0 ||
plan.ChangedRawContainers.Count > 0 ||
plan.ChangedRawTags.Any(d => !RawTagDeltaIsSurgicalEligible(d)) ||
plan.ChangedEquipmentVirtualTags.Any(d => !VtagDeltaIsNodeIrrelevant(d)))
plan.ChangedEquipmentVirtualTags.Any(d => !VtagDeltaIsNodeIrrelevant(d)) ||
// #977 U-2: a scripted alarm's node-shaping fields (Name / AlarmType / Severity, and its EquipmentId) changed
// on a condition that exists before AND after — the node keeps its old type/name/severity otherwise
// (MaterialiseAlarmCondition is idempotent on an existing id). Enabled flips are adds/removes, below.
plan.ChangedEquipmentScriptedAlarms.Any(d => !ScriptedAlarmDeltaIsSurgical(d)) ||
// #977 U-3: a Line moved to another Area (or any future non-name Area/Line field). EnsureFolder early-returns
// on an existing folder, so only a rebuild re-parents it; a name-only delta is served by RenamedFolders.
plan.ChangedUnsAreas.Any(d => !(d.Previous with { DisplayName = d.Current.DisplayName }).Equals(d.Current)) ||
plan.ChangedUnsLines.Any(d => !(d.Previous with { DisplayName = d.Current.DisplayName }).Equals(d.Current)))
{
return AddressSpaceChangeKind.Rebuild;
}
@@ -101,16 +109,23 @@ public static class AddressSpaceChangeClassifier
// Driver deltas (Added/Removed/ChangedDrivers) are node-INERT — they never touch the address-space
// topology (they route to DriverHostActor's spawn plan in Runtime), so they are excluded from the
// add/remove split below and leave a driver-only plan classified AttributeOnly.
// #977: added Areas/Lines are materialised by the always-full MaterialiseHierarchy pass; a scripted alarm that
// becomes enabled (or whose rich row appears) is an add, one that becomes disabled (or loses its rich row) a remove;
// removed Areas/Lines and orphaned VirtualTag sub-folders are torn down in place by ApplyPureRemove.
var hasAdds =
plan.AddedEquipment.Count + plan.AddedAlarms.Count +
plan.AddedEquipmentVirtualTags.Count +
plan.AddedRawContainers.Count + plan.AddedRawTags.Count +
plan.AddedUnsReferenceVariables.Count > 0;
plan.AddedUnsReferenceVariables.Count +
plan.AddedUnsAreas.Count + plan.AddedUnsLines.Count +
plan.ScriptedConditionAdds().Count > 0;
var hasRemoves =
plan.RemovedEquipment.Count + plan.RemovedAlarms.Count +
plan.RemovedEquipmentVirtualTags.Count +
plan.RemovedRawContainers.Count + plan.RemovedRawTags.Count +
plan.RemovedUnsReferenceVariables.Count > 0;
plan.RemovedUnsReferenceVariables.Count +
plan.RemovedUnsAreas.Count + plan.RemovedUnsLines.Count +
plan.ScriptedConditionRemoves().Count + plan.RemovedVirtualTagFolders.Count > 0;
// 3 — additions AND removals.
if (hasAdds && hasRemoves) return AddressSpaceChangeKind.AddRemoveMix;
@@ -142,6 +157,27 @@ public static class AddressSpaceChangeClassifier
Enabled = d.Current.Enabled,
}).Equals(d.Current);
// #977 U-2: a scripted alarm's condition node is derived from {ScriptedAlarmId, EquipmentId, Name, AlarmType, Severity}
// and exists only while Enabled. So a delta is node-irrelevant when the alarm is disabled on EITHER side (no node before
// ⇒ it is an add; no node after ⇒ a remove — both handled surgically via AddressSpacePlan.ScriptedConditionAdds/Removes),
// or when only the engine-side fields moved (predicate / template / dependencies / historize / retain), which
// ScriptedAlarmHostActor adopts from its own apply. Any other difference — including a FUTURE field — is
// default-closed to a rebuild via the with-equality whitelist.
/// <summary>Whether a changed rich scripted-alarm plan can be applied without a full rebuild.</summary>
/// <param name="d">The rich scripted-alarm delta.</param>
/// <returns><see langword="true"/> when the node is unaffected, or the change is a pure enable/disable flip.</returns>
internal static bool ScriptedAlarmDeltaIsSurgical(AddressSpacePlan.EquipmentScriptedAlarmDelta d) =>
!d.Previous.Enabled || !d.Current.Enabled ||
(d.Previous with
{
MessageTemplate = d.Current.MessageTemplate,
PredicateScriptId = d.Current.PredicateScriptId,
PredicateSource = d.Current.PredicateSource,
DependencyRefs = d.Current.DependencyRefs,
HistorizeToAveva = d.Current.HistorizeToAveva,
Retain = d.Current.Retain,
}).Equals(d.Current);
// v3 surgical raw-tag eligibility: a NON-alarm raw tag whose only differences are the in-place-updatable
// attributes (Writable / IsHistorized / HistorianTagname / HistorianReadOnly / DataType / IsArray / ArrayLength / ArrayWritable)
// and/or its ReferencingEquipmentPaths. ArrayWritable only feeds the node's writability — the
@@ -96,6 +96,83 @@ public sealed record AddressSpacePlan(
/// <inheritdoc cref="AddedUnsReferenceVariables"/>
public IReadOnlyList<UnsReferenceDelta> ChangedUnsReferenceVariables { get; init; } = Array.Empty<UnsReferenceDelta>();
/// <summary>
/// Gitea #977 (U-3) — the UNS Area / Line folders themselves, keyed by their stable ids. Before these sets the
/// planner looked at Areas and Lines only through <see cref="RenamedFolders"/>, so an added or removed Area/Line
/// and — worse — a Line RE-PARENTED to another Area (<see cref="UnsLineProjection.UnsAreaId"/>) never reached a
/// plan: the Line folder stayed under its old Area until some unrelated rebuild, and with ACLs on, every node under
/// it was denied because the live folder chain no longer matched the generation's. A changed record whose only
/// difference is the display name is still served in place through <see cref="RenamedFolders"/>; any other
/// difference (a re-parent) is a full rebuild (<see cref="AddressSpaceChangeClassifier"/>). Init-only, default empty.
/// </summary>
public IReadOnlyList<UnsAreaProjection> AddedUnsAreas { get; init; } = Array.Empty<UnsAreaProjection>();
/// <inheritdoc cref="AddedUnsAreas"/>
public IReadOnlyList<UnsAreaProjection> RemovedUnsAreas { get; init; } = Array.Empty<UnsAreaProjection>();
/// <inheritdoc cref="AddedUnsAreas"/>
public IReadOnlyList<UnsAreaDelta> ChangedUnsAreas { get; init; } = Array.Empty<UnsAreaDelta>();
/// <inheritdoc cref="AddedUnsAreas"/>
public IReadOnlyList<UnsLineProjection> AddedUnsLines { get; init; } = Array.Empty<UnsLineProjection>();
/// <inheritdoc cref="AddedUnsAreas"/>
public IReadOnlyList<UnsLineProjection> RemovedUnsLines { get; init; } = Array.Empty<UnsLineProjection>();
/// <inheritdoc cref="AddedUnsAreas"/>
public IReadOnlyList<UnsLineDelta> ChangedUnsLines { get; init; } = Array.Empty<UnsLineDelta>();
/// <summary>
/// Gitea #977 (U-2) — the RICH scripted-alarm host plans (<see cref="AddressSpaceComposition.EquipmentScriptedAlarms"/>),
/// keyed by <see cref="EquipmentScriptedAlarmPlan.ScriptedAlarmId"/>. The thin <see cref="AddedAlarms"/> /
/// <see cref="ChangedAlarms"/> sets diff only id / equipment / predicate-script id / template, but the four fields that
/// decide whether and how a scripted condition NODE exists — <c>Enabled</c>, <c>AlarmType</c>, <c>Severity</c>,
/// <c>Name</c> — live only on the rich record. Without these sets enabling a disabled alarm produced an empty plan
/// (the condition was never materialised, every engine write a silent no-op), disabling one left the node
/// browsable, and a type/name edit kept the old node indefinitely. Init-only, default empty.
/// </summary>
public IReadOnlyList<EquipmentScriptedAlarmPlan> AddedEquipmentScriptedAlarms { get; init; } = Array.Empty<EquipmentScriptedAlarmPlan>();
/// <inheritdoc cref="AddedEquipmentScriptedAlarms"/>
public IReadOnlyList<EquipmentScriptedAlarmPlan> RemovedEquipmentScriptedAlarms { get; init; } = Array.Empty<EquipmentScriptedAlarmPlan>();
/// <inheritdoc cref="AddedEquipmentScriptedAlarms"/>
public IReadOnlyList<EquipmentScriptedAlarmDelta> ChangedEquipmentScriptedAlarms { get; init; } = Array.Empty<EquipmentScriptedAlarmDelta>();
/// <summary>
/// Gitea #977 (U-9) — VirtualTag <c>FolderPath</c> sub-folders (<c>{EquipmentId}/{FolderPath}</c>) the previous
/// composition used and the next one does not, on an equipment that SURVIVES (a removed equipment's subtree
/// removal takes its sub-folders with it). Without it, removing the last VirtualTag in a sub-folder removed the
/// variable in place and left the empty folder browsable until the next rebuild. Init-only, default empty.
/// </summary>
public IReadOnlyList<VirtualTagFolder> RemovedVirtualTagFolders { get; init; } = Array.Empty<VirtualTagFolder>();
/// <summary>
/// The scripted condition nodes this plan brings into existence BEYOND the thin <see cref="AddedAlarms"/>: a rich
/// alarm row that appeared enabled (e.g. its predicate script only now arrived) and an alarm flipped from
/// disabled to enabled. Only meaningful on a non-rebuild apply (a rebuild materialises the whole composition).
/// </summary>
/// <returns>The rich alarm rows whose condition node must be materialised.</returns>
public IReadOnlyList<EquipmentScriptedAlarmPlan> ScriptedConditionAdds()
{
var list = new List<EquipmentScriptedAlarmPlan>();
foreach (var a in AddedEquipmentScriptedAlarms) if (a.Enabled) list.Add(a);
foreach (var d in ChangedEquipmentScriptedAlarms) if (!d.Previous.Enabled && d.Current.Enabled) list.Add(d.Current);
return list;
}
/// <summary>
/// The scripted condition nodes this plan takes away BEYOND the thin <see cref="RemovedAlarms"/> (which the applier
/// already tears down): an enabled alarm flipped to disabled, and an enabled rich row that vanished while its thin
/// row survived (its predicate script is gone).
/// </summary>
/// <returns>The previous rich alarm rows whose condition node must be removed.</returns>
public IReadOnlyList<EquipmentScriptedAlarmPlan> ScriptedConditionRemoves()
{
var list = new List<EquipmentScriptedAlarmPlan>();
if (RemovedEquipmentScriptedAlarms.Count > 0)
{
var thinRemoved = new HashSet<string>(RemovedAlarms.Select(a => a.ScriptedAlarmId), StringComparer.Ordinal);
foreach (var a in RemovedEquipmentScriptedAlarms)
if (a.Enabled && !thinRemoved.Contains(a.ScriptedAlarmId)) list.Add(a);
}
foreach (var d in ChangedEquipmentScriptedAlarms) if (d.Previous.Enabled && !d.Current.Enabled) list.Add(d.Previous);
return list;
}
/// <summary>Gets a value indicating whether the composition plan contains no changes.</summary>
public bool IsEmpty =>
AddedEquipment.Count == 0 && RemovedEquipment.Count == 0 && ChangedEquipment.Count == 0 &&
@@ -105,12 +182,27 @@ public sealed record AddressSpacePlan(
AddedRawContainers.Count == 0 && RemovedRawContainers.Count == 0 && ChangedRawContainers.Count == 0 &&
AddedRawTags.Count == 0 && RemovedRawTags.Count == 0 && ChangedRawTags.Count == 0 &&
AddedUnsReferenceVariables.Count == 0 && RemovedUnsReferenceVariables.Count == 0 && ChangedUnsReferenceVariables.Count == 0 &&
RenamedFolders.Count == 0;
RenamedFolders.Count == 0 &&
AddedUnsAreas.Count == 0 && RemovedUnsAreas.Count == 0 && ChangedUnsAreas.Count == 0 &&
AddedUnsLines.Count == 0 && RemovedUnsLines.Count == 0 && ChangedUnsLines.Count == 0 &&
AddedEquipmentScriptedAlarms.Count == 0 && RemovedEquipmentScriptedAlarms.Count == 0 &&
ChangedEquipmentScriptedAlarms.Count == 0 &&
RemovedVirtualTagFolders.Count == 0;
public sealed record EquipmentDelta(EquipmentNode Previous, EquipmentNode Current);
public sealed record DriverDelta(DriverInstancePlan Previous, DriverInstancePlan Current);
public sealed record AlarmDelta(ScriptedAlarmPlan Previous, ScriptedAlarmPlan Current);
public sealed record EquipmentVirtualTagDelta(EquipmentVirtualTagPlan Previous, EquipmentVirtualTagPlan Current);
/// <summary>A rich scripted-alarm plan present in both snapshots (same id) with ≥1 differing field.</summary>
public sealed record EquipmentScriptedAlarmDelta(EquipmentScriptedAlarmPlan Previous, EquipmentScriptedAlarmPlan Current);
/// <summary>A UNS Area present in both snapshots (same id) with ≥1 differing field.</summary>
public sealed record UnsAreaDelta(UnsAreaProjection Previous, UnsAreaProjection Current);
/// <summary>A UNS Line present in both snapshots (same id) with ≥1 differing field — a rename and/or a re-parent.</summary>
public sealed record UnsLineDelta(UnsLineProjection Previous, UnsLineProjection Current);
/// <summary>One VirtualTag <c>FolderPath</c> sub-folder of an equipment (node id <c>{EquipmentId}/{FolderPath}</c>).</summary>
/// <param name="EquipmentId">The owning equipment folder id.</param>
/// <param name="FolderPath">The VirtualTag FolderPath (non-empty).</param>
public sealed record VirtualTagFolder(string EquipmentId, string FolderPath);
/// <summary>A Raw container node present in both snapshots (same RawPath) with ≥1 differing field.</summary>
public sealed record RawContainerDelta(RawContainerNode Previous, RawContainerNode Current);
@@ -207,6 +299,25 @@ public static class AddressSpacePlanner
.Concat(DiffRenames(previous.UnsLines, next.UnsLines, l => l.UnsLineId, l => l.DisplayName))
.ToList();
// #977 U-3 — the Area/Line folders in full: added/removed folders and every field difference (a Line moved to
// another Area is a changed UnsAreaId). The classifier lets a rename-only delta through surgically (served by
// RenamedFolders above) and rebuilds on anything else.
var (addedAreas, removedAreas, changedAreas) = DiffById(
previous.UnsAreas, next.UnsAreas, a => a.UnsAreaId,
(a, b) => new AddressSpacePlan.UnsAreaDelta(a, b));
var (addedLines, removedLines, changedLines) = DiffById(
previous.UnsLines, next.UnsLines, l => l.UnsLineId,
(a, b) => new AddressSpacePlan.UnsLineDelta(a, b));
// #977 U-2 — the rich scripted-alarm rows: Enabled / AlarmType / Severity / Name decide the condition node and
// live only here. EquipmentScriptedAlarmPlan already has element-wise value equality.
var (addedRichAlarms, removedRichAlarms, changedRichAlarms) = DiffById(
previous.EquipmentScriptedAlarms, next.EquipmentScriptedAlarms, a => a.ScriptedAlarmId,
(a, b) => new AddressSpacePlan.EquipmentScriptedAlarmDelta(a, b));
// #977 U-9 — VirtualTag sub-folders the next composition no longer uses, on equipment that survives.
var removedVtagFolders = DiffVirtualTagFolders(previous, next);
return new AddressSpacePlan(
addedEq, removedEq, changedEq,
addedDrv, removedDrv, changedDrv,
@@ -225,9 +336,41 @@ public static class AddressSpacePlanner
RemovedUnsReferenceVariables = removedUnsRefs,
ChangedUnsReferenceVariables = changedUnsRefs,
RenamedFolders = renamedFolders,
AddedUnsAreas = addedAreas,
RemovedUnsAreas = removedAreas,
ChangedUnsAreas = changedAreas,
AddedUnsLines = addedLines,
RemovedUnsLines = removedLines,
ChangedUnsLines = changedLines,
AddedEquipmentScriptedAlarms = addedRichAlarms,
RemovedEquipmentScriptedAlarms = removedRichAlarms,
ChangedEquipmentScriptedAlarms = changedRichAlarms,
RemovedVirtualTagFolders = removedVtagFolders,
};
}
/// <summary>The (EquipmentId, FolderPath) sub-folders some previous VirtualTag used that no next VirtualTag uses,
/// restricted to equipment present in <paramref name="next"/> (a removed equipment's subtree removal subsumes them).
/// Ordinal-sorted for determinism.</summary>
private static List<AddressSpacePlan.VirtualTagFolder> DiffVirtualTagFolders(
AddressSpaceComposition previous, AddressSpaceComposition next)
{
static HashSet<AddressSpacePlan.VirtualTagFolder> Folders(AddressSpaceComposition c) =>
c.EquipmentVirtualTags
.Where(v => !string.IsNullOrWhiteSpace(v.FolderPath))
.Select(v => new AddressSpacePlan.VirtualTagFolder(v.EquipmentId, v.FolderPath))
.ToHashSet();
var survivors = new HashSet<string>(next.EquipmentNodes.Select(e => e.EquipmentId), StringComparer.Ordinal);
var removed = Folders(previous);
removed.ExceptWith(Folders(next));
return removed
.Where(f => survivors.Contains(f.EquipmentId))
.OrderBy(f => f.EquipmentId, StringComparer.Ordinal)
.ThenBy(f => f.FolderPath, StringComparer.Ordinal)
.ToList();
}
/// <summary>
/// Emit a <see cref="AddressSpacePlan.FolderRename"/> for every folder present in
/// BOTH snapshots (matched by stable <paramref name="identity"/>) whose <paramref name="displayName"/>
@@ -1500,13 +1500,11 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
_log.Warning("DriverHost {Node}: found orphan Applying row for deployment {Id}; replaying",
_localNode, latest.DeploymentId);
if (revision is not null) BeginDirectApply(new DeploymentId(latest.DeploymentId), revision.Value, CorrelationId.NewId());
else BecomeSteady();
else RestoreLastApplied(db, latest.DeploymentId, "its orphan Applying row names a deployment that no longer exists");
break;
case NodeDeploymentStatus.Failed:
default:
_log.Info("DriverHost {Node}: prior deployment {Id} failed; entering Steady at last known rev",
_localNode, latest.DeploymentId);
BecomeSteady();
RestoreLastApplied(db, latest.DeploymentId, $"the newest deployment on this node ended {latest.Status}");
break;
}
}
@@ -1522,6 +1520,53 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
}
}
/// <summary>
/// Gitea #977 (R-1). The newest node row is not Applied (a failed deploy, or an orphan Applying row whose deployment
/// is gone) — but a failed apply never stopped this node serving the revision BEFORE it ("Staying on revision A and
/// continuing to serve it"). Booting straight to an empty Steady here used to serve nothing after any restart that
/// followed a failed deploy, logged at Info, with nothing to heal it. Restore the newest APPLIED deployment for this
/// node instead; with none, fall back to the node-local cache, and only then to Steady with no revision.
/// </summary>
/// <param name="db">The open bootstrap context.</param>
/// <param name="newestId">The newest (non-Applied) row's deployment, for the log.</param>
/// <param name="why">Why the newest row cannot be restored, for the log.</param>
private void RestoreLastApplied(OtOpcUaConfigDbContext db, Guid newestId, string why)
{
var lastApplied = db.NodeDeploymentStates
.AsNoTracking()
.Where(s => s.NodeId == _localNode.Value && s.Status == NodeDeploymentStatus.Applied)
.OrderByDescending(s => s.StartedAtUtc)
.Select(s => s.DeploymentId)
.Take(8)
.ToList()
// The newest Applied row whose deployment row (and so its revision) still exists.
.Select(id => (Id: id, Deployment: db.Deployments.AsNoTracking()
.Where(d => d.DeploymentId == id)
.Select(d => new { d.RevisionHash })
.FirstOrDefault()))
.FirstOrDefault(x => x.Deployment is not null && !string.IsNullOrWhiteSpace(x.Deployment.RevisionHash));
if (lastApplied.Deployment is { } applied)
{
var revision = RevisionHash.Parse(applied.RevisionHash);
_currentRevision = revision;
_log.Warning(
"DriverHost {Node}: {Why} (deployment {Newest}); restoring the last APPLIED deployment {Id} (rev {Rev}) — the revision it was serving before",
_localNode, why, newestId, lastApplied.Id, revision);
BecomeSteady();
RestoreApplied(new DeploymentId(lastApplied.Id), revision);
return;
}
_log.Warning(
"DriverHost {Node}: {Why} (deployment {Newest}) and no earlier deployment was ever applied here; trying the node-local cache",
_localNode, why, newestId);
if (TryBootFromCache(configDbReachable: true)) return;
_log.Warning("DriverHost {Node}: nothing to restore; entering Steady with no revision until the next dispatch", _localNode);
BecomeSteady();
}
/// <summary>
/// Per-cluster mesh Phase 3 boot for <c>FetchAndCache</c> mode. Restores served state from the
/// LocalDb pointer without any central-SQL read.
@@ -1622,7 +1667,9 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
/// would have been without a cache at all.
/// </para>
/// </remarks>
private bool TryBootFromCache()
/// <param name="configDbReachable">True when the ConfigDb answered (Gitea #977 R-1: it simply holds no applied
/// deployment for this node) — the node is then not "running from cache" in the outage sense.</param>
private bool TryBootFromCache(bool configDbReachable = false)
{
if (_deploymentArtifactCache is null)
return false;
@@ -1661,6 +1708,16 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
_currentRevisionUnconfirmed = true;
BecomeSteady();
if (configDbReachable)
{
// #977 R-1: the ConfigDb answered but holds no Applied deployment for this node — not an outage.
_log.Warning(
"DriverHost {Node}: booted deployment {Id} (rev {Rev}) cached at {CachedAtUtc:o} from the node-local " +
"cache, because the ConfigDb records no applied deployment for this node; a re-dispatch re-applies it.",
_localNode, deploymentId, revision, cached.AppliedAtUtc);
return true;
}
_isRunningFromCache = true;
_log.Warning(
"DriverHost {Node}: RUNNING FROM CACHE — central ConfigDb is unreachable, so this node " +
@@ -3282,7 +3339,10 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
return;
}
_currentRevision = msg.Revision;
// #977 R-15: _currentRevision now advances BELOW, after the last step that can throw (subscription push,
// cache write, catalog completion). Advancing it here let a throw in those steps leave the new revision
// current with no address-space rebuild sent for it, and a re-dispatch of the same revision then short-
// circuited to a CLEAN Applied ack over an address space that never received it.
// lmxopcua#868 review M1: the own row stays APPLYING (written by BeginDirectApply) until the
// address-space outcome is known — AwaitAddressSpaceOutcomeThenAck / ReleasePendingAck write the
// final Applied (clean, or with the degraded reason). Writing Applied/null here, up to ~105 s before
@@ -3319,6 +3379,9 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
&& _catalogCoordinator is not null
&& !_catalogCoordinator.Complete(_catalogAttempt, topologySucceeded: true)
&& _catalogAttempt.Expected;
// Advanced only now (R-15) — and before the ack hold below, whose no-publish-actor path settles this
// revision's confirmed/unconfirmed flag immediately and must find it current.
_currentRevision = msg.Revision;
AwaitAddressSpaceOutcomeThenAck(msg.DeploymentId, msg.Revision, msg.Correlation, catalogFailed);
_opcUaPublishActor?.Tell(new ZB.MOM.WW.OtOpcUa.Runtime.OpcUa.OpcUaPublishActor.RebuildAddressSpace(
msg.Correlation, msg.DeploymentId, appliedBlob, ReportOutcome: true, CatalogAttempt: _catalogAttempt));
@@ -3340,6 +3403,11 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
// A throw after the Applied ack was put on hold — the Failed ack below is this apply's one
// answer, so the held Applied must never follow it when the address-space outcome lands.
DropPendingAck(msg.Correlation);
// #977 R-15: whatever revision is current now, a throw part-way through the apply means the drivers and the
// routing maps (ApplyDesiredSubscriptions clears them before repopulating) may already be the NEW revision's,
// partially. Nothing about the current revision is known-served any more, so a re-dispatch of EITHER revision
// must re-apply rather than short-circuit to a clean Applied ack.
_currentRevisionUnconfirmed = true;
UpsertNodeDeploymentState(msg.DeploymentId, NodeDeploymentStatus.Failed, ex.Message);
SendAck(msg.DeploymentId, ApplyAckOutcome.Failed, ex.Message, msg.Correlation);
OtOpcUaTelemetry.DeploymentApplied.Add(1, new KeyValuePair<string, object?>("outcome", "reject"));
@@ -193,6 +193,10 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
internal Func<ParsedDeploymentArtifact, string, DataPlaneAuthorityProjection>? ParseAuthority { get; init; }
}
/// <summary>Test-only (registered only when <see cref="TestHooks"/> are supplied): throws from the handler so a test
/// can drive a supervision RESTART of this actor (Gitea #977 R-20).</summary>
internal sealed record CrashForTests;
/// <summary>The default bound on <see cref="_deferred"/>: distinct (realm, id) keys held while a plan is in flight.</summary>
internal const int DefaultDeferredWriteCapacity = 250_000;
@@ -307,6 +311,16 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
/// that pass is itself clean.
/// </summary>
private bool _lastAppliedDegraded;
/// <summary>
/// Gitea #977 (R-20): this instance was created by a supervision RESTART, so <see cref="_lastApplied"/> is the
/// empty seed while the sink (the node manager, which outlives the actor) still serves the previous instance's
/// address space. Diffing against the seed would make every node look added — an idempotent no-op that never
/// removes what the deploy dropped and skips every in-place attribute edit — and report clean. While set, the
/// next apply is a forced full rebuild (even of an otherwise empty plan); cleared once a rebuild succeeds.
/// Persisting <see cref="_lastApplied"/> across the restart was the alternative; a rebuild needs no state to
/// survive the crash that caused it, which is why it was chosen.
/// </summary>
private bool _baselineUnknown;
private DbHealthProbeActor.DbHealthStatus? _lastDbHealth;
private RedundancyStateChanged? _lastSnapshot;
private (bool Ok, DateTime At)? _probeAboutMe;
@@ -623,6 +637,8 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
RecomputeServiceLevel();
});
Receive<WarmRetry>(_ => RecomputeServiceLevel());
if (hooks is not null)
Receive<CrashForTests>(_ => throw new InvalidOperationException("simulated handler fault (test)"));
}
/// <summary>
@@ -643,6 +659,14 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
base.PreRestart(reason, message);
}
/// <summary>Gitea #977 (R-20): the new instance does not know what the sink serves — see <see cref="_baselineUnknown"/>.</summary>
/// <inheritdoc />
protected override void PostRestart(Exception reason)
{
_baselineUnknown = true;
base.PostRestart(reason);
}
/// <inheritdoc />
protected override void PostStop()
{
@@ -1551,7 +1575,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
var composition = ready.Composition;
var plan = ready.Plan;
if (plan.IsEmpty)
if (plan.IsEmpty && !_baselineUnknown)
{
if (_lastAppliedDegraded)
{
@@ -1580,7 +1604,16 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
return (false, null);
}
var outcome = _applier!.Apply(plan);
// #977 R-20: after a supervision restart _lastApplied is the empty seed while the node manager still serves
// the previous incarnation's address space — a diff against it would add everything idempotently, never
// remove what this deploy dropped, and skip every in-place edit. The first apply of a restarted instance
// therefore rebuilds, whatever its plan says.
var forceRebuild = _baselineUnknown;
if (forceRebuild)
_log.Warning(
"OpcUaPublish: first apply after a restart of this actor (correlation={Correlation}) — the served address space is not known to match any composition, so it is REBUILT rather than diffed",
msg.Correlation);
var outcome = _applier!.Apply(plan, forceRebuild);
rebuilt = outcome.RebuildCalled;
// Sum swallowed per-node materialise failures across every pass together with Apply's own
@@ -1592,7 +1625,13 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
// exist to bound — and every node the delta passes add needs its ancestor folders to already
// exist, so narrowing it would mean re-deriving each add's ancestor closure (strictly more work).
failedNodes += _applier.MaterialiseHierarchy(composition);
failedNodes += MaterialiseNodes(plan, composition, fullComposition: outcome.RebuildCalled);
// #977 R-4: while the last applied composition is known DEGRADED (a rebuild advanced it with failures), a
// non-rebuild apply re-ensures the WHOLE composition, not just this plan's delta. The node that rebuild failed
// to place is inside _lastApplied and will never appear in a diff again, so a delta-only apply of an unrelated
// change used to clear the degraded flag and report clean over a still-partial address space.
var repairingDegraded = _lastAppliedDegraded && !outcome.RebuildCalled;
failedNodes += MaterialiseNodes(plan, composition, fullComposition: outcome.RebuildCalled || repairingDegraded);
if (outcome.RebuildCalled) _baselineUnknown = outcome.RebuildFailed;
// 2026-08-15 surgical-deploys review C1 — record the composition as applied ONLY when the apply was
// clean, or when a rebuild ran. Two reasons this sits HERE (after the materialise passes) rather
@@ -1703,12 +1742,10 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
/// <c>UnsReferenceDelta</c> by REMOVING the previous node and leaving the recreate to this pass, so
/// the subset must carry the <i>current</i> side of every changed reference as well as the added ones
/// — otherwise a re-pointed, renamed, or backing-edited UNS node is removed and never comes back.</para>
/// <para><b>Accepted narrowing.</b> The plan diffs the THIN <c>ScriptedAlarmPlans</c> projection, so
/// the added-alarm subset is the rich <c>EquipmentScriptedAlarms</c> rows whose id the plan reports as
/// added. An alarm already present in both compositions whose predicate SCRIPT row only now arrived
/// (making it materialisable for the first time) is not in that set — but neither is it in any diff
/// set at all, so on its own it already produced an empty plan and materialised nothing. The delta
/// path extends that pre-existing blindness to the case where it rides along with another change.</para>
/// <para><b>Scripted alarms.</b> The added-alarm subset is the rich <c>EquipmentScriptedAlarms</c> rows whose
/// id the thin diff reports as added, plus (Gitea #977 U-2) every condition the rich diff brings into existence:
/// an alarm enabled in place, or one whose predicate script only now arrived. Before #977 the plan diffed only
/// the thin projection, so both were invisible.</para>
/// </remarks>
/// <param name="plan">The plan just applied — the source of the delta subsets.</param>
/// <param name="composition">The full composition, always passed as the passes' lookup context.</param>
@@ -1798,10 +1835,14 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
private static IReadOnlyList<EquipmentScriptedAlarmPlan> DeltaScriptedAlarms(
AddressSpacePlan plan, AddressSpaceComposition composition)
{
if (plan.AddedAlarms.Count == 0 || composition.EquipmentScriptedAlarms.Count == 0)
// #977 U-2: plus the conditions the RICH diff brings into existence — an alarm enabled in place, or one whose rich
// row only now appeared (its predicate script arrived) — which the thin AddedAlarms never named.
var richAdds = plan.ScriptedConditionAdds();
if ((plan.AddedAlarms.Count == 0 && richAdds.Count == 0) || composition.EquipmentScriptedAlarms.Count == 0)
return Array.Empty<EquipmentScriptedAlarmPlan>();
var addedIds = new HashSet<string>(plan.AddedAlarms.Select(a => a.ScriptedAlarmId), StringComparer.Ordinal);
addedIds.UnionWith(richAdds.Select(a => a.ScriptedAlarmId));
return composition.EquipmentScriptedAlarms.Where(a => addedIds.Contains(a.ScriptedAlarmId)).ToList();
}