fix(history): a folder's event history reads the Galaxy objects behind its native conditions (#886)
v2-ci / unit-tests (push) Has been cancelled

A notifier folder read one event source, its NodeId identifier (a RawPath or an EquipmentId). AVEVA stores a
Galaxy object's A&E history under the object's tag_name (Source_Object), so AVEVA's own alarm and event
history reached no production folder. Its lower-case property keys were also missed, so every row read
Severity 1 with no ConditionName.

Sources. A folder's event history now reads its own source plus the Galaxy object of every native condition
that fires on it live: those parented under it and those WireAlarmNotifiers wired to it. Live and history use
the same membership. The object comes from the condition's Galaxy alarm reference, its raw tag's attributeRef,
up to the first '.':
- The composer reads it with the driver's own parser (GalaxyAttributeRef, shared with GalaxyDriver), only for
  a GalaxyMxGateway tag with an alarm (RawTagPlan.NativeAlarmReference, part of plan equality).
- The applier binds it after materialising the condition (IOpcUaAddressSpaceSink.BindNativeAlarmHistory,
  forwarded by the deferred sink). A rebuild or the condition's removal forgets it.
Each object is read with the #882 rule: its own events and <Object>.<Attribute> rows, never a prefix sibling.

Fan-out. historiangw's ReadEvents filter is a single predicate, so there is one request per source; the wire
contract is unchanged. EventSourceFanOut merges the reads as one source:
- order is (time, source position, arrival), reversed for a reverse read; ties are never re-sorted by EventId,
  so the boundary skip stays stable;
- duplicates by EventId are dropped and the merge is cut to the cap;
- a truncated source bounds the page at the time it stopped.
Paging, continuation points (bound to the whole source set), the walked-back reverse read and the tie-cluster
over-fetch are unchanged. A folder with one source is read exactly as before.

ACL. Every source is read inside the folder's own HistoryRead, after AuthorizeHistoryRead (#826). A denied
folder reads nothing and fails closed.

Mapping (EventMapper, property names now case-insensitive):
- Severity: an AVEVA row's priority goes through GalaxyAlarmPriority, the table live Galaxy alarms use
  (MxAccessSeverityMapper now delegates to it), so history matches live. Otherwise severity (OtOpcUa's own
  rows, which AVEVA stores lower-cased), clamped. AVEVA's own 1-4 severity is ignored. The table ranks a
  higher priority as more severe, which inverts AVEVA's convention: filed as #887.
- An AVEVA row whose source_conditionvariable names a native condition that fires on the folder takes that
  condition's SourceNode and live ConditionName. Otherwise ConditionName is alarmname or the condition
  variable's attribute.
- alarm_id/alarmid map to AlarmId.

Tests:
- GalaxyEquipmentEventHistoryWireTests (4, real SDK session, production Gateway backend, AVEVA-shaped fake
  gateway): equipment EqA backed by objects Oven_007 + OvenDoor_07. Covers object and attribute events from
  both objects, the prefix sibling excluded, cross-object and in-object ties, forward paging at 1-4 a page,
  reverse whole and paged, SourceNode/ConditionName/Severity, the raw device folder, ACL deny with no backend
  call plus a granted positive control, and a rebuild forgetting the bindings.
- EventSourceFanOutTests (8), EventMapper AVEVA cases (11), GalaxyAttributeRefTests (16), a composer test and
  an applier ordering test.
- Mutation-checked, 17 mutants, all killed. Covered: parent-only membership, no scope, a case-sensitive
  condition match, no condition rewrite, no truncation bound, EventId tie order, no sort, no cap, no stop at
  the bound, unreversed source order, no dedupe, no '.' boundary, priority ignored, case-sensitive keys, no
  applier bind, no deferred forward, and a composer that ignores the driver type. The forget-on-rematerialise
  guard survives as belt-and-braces: the rebuild clear covers it.
- Live, read-only, no WinRM, vd03 HistorianGateway ea9f21c: equipment folder EQ-886-ZipsenLeft (objects
  DevWinPlatform + Left_001). It read 0 events before and 92 now, equal to the unfiltered read's rows for both
  objects. 1/7-event pages and reverse whole/5-event pages agree, and 73 rows resolve to their live condition.
  diff_runs vs the #882 run: 221/226 identical. The 5 that differ are expected: DevWinPlatform Severity
  1 -> 750/1000, and #881 capabilities.

Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
This commit is contained in:
Joseph Doherty
2026-11-12 11:34:50 -05:00
parent 1e1fad76c4
commit 3a312ffdd1
25 changed files with 1531 additions and 95 deletions
@@ -82,6 +82,13 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
/// <see cref="_alarmConditions"/> so a re-materialise as the other kind is correct.</summary>
private readonly HashSet<RealmKey> _nativeAlarmNodeIds = new();
/// <summary>
/// Gitea #886 — native condition key → its Galaxy alarm reference (<c>tag_name.AlarmAttribute</c>), recorded by
/// <see cref="BindNativeAlarmHistory"/>. Every folder the condition fires on live reads the history AVEVA stores
/// under the reference's object (<see cref="ResolveEventHistoryScope"/>). Guarded by <c>Lock</c>; maintained in
/// lock-step with <see cref="_nativeAlarmNodeIds"/> (dropped wherever a condition is, cleared on rebuild).
/// </summary>
private readonly Dictionary<RealmKey, string> _nativeAlarmReferences = new();
/// <summary>
/// Gitea #797 — the explicit binding from each LIVE scripted condition to the equipment that owns it.
/// A scripted condition's NodeId is its opaque <c>ScriptedAlarmId</c> and cannot be split into an ACL
/// scope, so with <c>Security:Acl:Enabled</c> its Part 9 commands are authorized at the owner's scope
@@ -2319,6 +2326,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
// H6a: re-materialising the same id as the OTHER kind (native↔scripted) must reflect the new
// kind, so always drop the stale native flag first and only re-add it below when isNative.
_nativeAlarmNodeIds.Remove(conditionKey);
_nativeAlarmReferences.Remove(conditionKey);
// Gitea #797: the dropped instance's owner binding goes with it; the new one is bound below.
_scriptedAlarmOwners.Remove(conditionKey);
@@ -2721,6 +2729,21 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
}
}
/// <inheritdoc cref="IOpcUaAddressSpaceSink.BindNativeAlarmHistory"/>
public void BindNativeAlarmHistory(string alarmNodeId, AddressSpaceRealm alarmRealm, string alarmReference)
{
ArgumentException.ThrowIfNullOrEmpty(alarmNodeId);
if (string.IsNullOrWhiteSpace(alarmReference)) return;
var key = MapKey(alarmRealm, alarmNodeId);
lock (Lock)
{
// Only a materialised NATIVE condition carries an upstream reference; anything else (a mid-rebuild race, a
// scripted id) is a no-op, never a throw — a deploy must not fault on it.
if (!_alarmConditions.ContainsKey(key) || !_nativeAlarmNodeIds.Contains(key)) return;
_nativeAlarmReferences[key] = alarmReference.Trim();
}
}
/// <summary>Tear down (bidirectionally) every notifier wired for the condition at <paramref name="alarmKey"/>
/// and drop its tracking entry. MUST be called under <c>Lock</c>. Used on condition-removal + full rebuild
/// so no inverse-notifier entry leaks. A no-op when the condition has no wired notifiers.</summary>
@@ -4648,6 +4671,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
// H6a: drop the native-alarm flags in lock-step with the conditions they classify, so a
// re-materialise on the next apply (possibly as the other kind) starts from a clean slate.
_nativeAlarmNodeIds.Clear();
_nativeAlarmReferences.Clear();
_scriptedAlarmOwners.Clear();
foreach (var f in _folders.Values) PredefinedNodes?.Remove(f.NodeId);
@@ -4812,6 +4836,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
condition.Parent?.RemoveChild(condition);
ForgetPredefinedSubtree(condition);
_nativeAlarmNodeIds.Remove(key);
_nativeAlarmReferences.Remove(key);
_scriptedAlarmOwners.Remove(key);
LowerAllEventsMonitoring(condition);
e = BuildNodesRemovedModelChange(alarmNodeId, realm);
@@ -4922,6 +4947,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
if (c.Parent is { } parent && !removedParents.Contains(parent)) parent.RemoveChild(c);
ForgetPredefinedSubtree(c);
_nativeAlarmNodeIds.Remove(key);
_nativeAlarmReferences.Remove(key);
_scriptedAlarmOwners.Remove(key);
LowerAllEventsMonitoring(c);
return;
@@ -7830,8 +7856,10 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
continue;
}
var sn = sourceName;
work.Add(() => ServeEventsAsync(handle, sn, details, selectClauses, where, filterContext, nodesToRead, session,
// #886: the folder's own source plus the Galaxy objects of the native conditions that fire on it, taken
// under Lock now so the whole read (every page source, every SourceNode) sees one membership.
var scope = ResolveEventHistoryScope(handle.NodeId, sourceName);
work.Add(() => ServeEventsAsync(handle, scope, details, selectClauses, where, filterContext, nodesToRead, session,
results, errors, ct));
}
@@ -7839,6 +7867,42 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
});
}
/// <summary>
/// Gitea #886 — what one notifier folder's event history reads: its own registered source (OtOpcUa's own events,
/// as before) plus the Galaxy object of every native condition that fires on it live — those parented under it
/// and those <see cref="WireAlarmNotifiers"/> wired to it — and those conditions by their Galaxy reference, so an
/// AVEVA row resolves to the same condition its live event comes from. Taken under <c>Lock</c>.
/// </summary>
/// <param name="folderNodeId">The notifier folder.</param>
/// <param name="ownSource">The folder's registered event source (its NodeId identifier).</param>
/// <returns>The folder's scope; just <paramref name="ownSource"/> when no Galaxy condition fires on it.</returns>
private EventHistoryScope ResolveEventHistoryScope(NodeId folderNodeId, string ownSource)
{
lock (Lock)
{
if (_nativeAlarmReferences.Count == 0 || !_notifierFolders.TryGetValue(folderNodeId, out var folder))
return EventHistoryScope.Single(ownSource);
List<string>? objects = null;
Dictionary<string, EventHistoryCondition>? conditions = null;
foreach (var (key, reference) in _nativeAlarmReferences)
{
if (!_alarmConditions.TryGetValue(key, out var alarm)) continue;
var firesHere = ReferenceEquals(alarm.Parent, folder)
|| (_alarmNotifierWiring.TryGetValue(key, out var wiring)
&& ReferenceEquals(wiring.Alarm, alarm) && wiring.Folders.Contains(folder));
if (!firesHere) continue;
if (GalaxyAttributeRef.ObjectNameOf(reference) is { } objectName) (objects ??= []).Add(objectName);
// Galaxy names are case-insensitive, and the driver matches its live alarm references the same way.
conditions ??= new Dictionary<string, EventHistoryCondition>(StringComparer.OrdinalIgnoreCase);
conditions.TryAdd(reference, new EventHistoryCondition(
key.Id, alarm.ConditionName?.Value ?? alarm.DisplayName.Text ?? key.Id));
}
return conditions is null ? EventHistoryScope.Single(ownSource) : EventHistoryScope.Create(ownSource, objects, conditions);
}
}
/// <summary>
/// Serve one registered event-history notifier handle: reads the source's events over the request
/// window, projects them onto the select clauses, and fills the service-level results/errors slots.
@@ -7847,7 +7911,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
/// <c>BadTimeout</c>.
/// </summary>
/// <param name="handle">The notifier node handle; <c>handle.Index</c> indexes results/errors.</param>
/// <param name="sourceName">The registered historian event-source name for this notifier.</param>
/// <param name="scope">The notifier's event-history sources and the native conditions that fire on it (#886).</param>
/// <param name="details">The event-read details (window + count cap).</param>
/// <param name="selectClauses">The event-filter select clauses (the fields to emit, in order).</param>
/// <param name="where">The event filter's where-clause, or null for none.</param>
@@ -7857,7 +7921,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
/// <param name="ct">Per-request deadline token.</param>
private async Task ServeEventsAsync(
NodeHandle handle,
string? sourceName,
EventHistoryScope scope,
ReadEventDetails details,
ArrayOf<SimpleAttributeOperand> selectClauses,
ContentFilter? where,
@@ -7873,6 +7937,12 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
var resumed = inboundCp is { Length: > 0 };
// One snapshot of the (hot-swappable) source for the whole read: the capability check and every call must agree.
var source = _historianDataSource;
// The folder's sources read as ONE source (#886): a single source is read directly, several are fanned out and
// merged in (EventTimeUtc, source, arrival) order (EventSourceFanOut), so the paging below is the same either way.
// The cursor is bound to the whole source set.
var sourceName = scope.CursorKey;
Task<HistoricalEventsResult> ReadSourcesAsync(DateTime from, DateTime to, int max, bool rev, CancellationToken token) =>
EventSourceFanOut.ReadAsync(source, scope.Sources, from, to, max, rev, token);
try
{
var startUtc = SdkValueBoundary.ToClrTimestamp(details.StartTime);
@@ -7888,14 +7958,13 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
// for THIS node only.
var state = _historyContinuationStore.TryTake(session, inboundCp.ToArray());
// A point is bound to the node that issued it: another node's source name is a miss too.
if (state is null || !HistoryContinuationMatches(state, handle.NodeId, historyEpoch) || state.Kind != HistoryCursorKind.Events || state.Tagname != (sourceName ?? string.Empty))
if (state is null || !HistoryContinuationMatches(state, handle.NodeId, historyEpoch) || state.Kind != HistoryCursorKind.Events || state.Tagname != sourceName)
{
errors[handle.Index] = StatusCodes.BadContinuationPointInvalid;
results[handle.Index] = new SdkHistoryReadResult { StatusCode = StatusCodes.BadContinuationPointInvalid };
return;
}
sourceName = state.Tagname;
startUtc = state.NextStartUtc;
endUtc = state.EndUtc;
boundarySkip = state.BoundarySkipCount;
@@ -7956,8 +8025,8 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
// continuation point (the walk itself cannot flag truncation).
var want = numValuesPerNode == 0 ? 0u : (uint)Math.Min(uint.MaxValue - 1L, (long)fetch + 1);
var (rows, next) = await ReverseEventsReader.ReadAsync(
source, sourceName, startUtc, endUtc, want, MaxTieClusterOverfetch, Clock.GetUtcNow().UtcDateTime,
walkHint, ct)
(from, to, cap, token) => ReadSourcesAsync(from, to, cap, rev: false, token), source.TimestampResolutionTicks,
sourceName, startUtc, endUtc, want, MaxTieClusterOverfetch, Clock.GetUtcNow().UtcDateTime, walkHint, ct)
.ConfigureAwait(false);
walkHint = next;
var more = want > 0 && rows.Count > fetch;
@@ -7966,8 +8035,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
}
else
{
sourceResult = await source.ReadEventsAsync(
sourceName, startUtc, endUtc, fetch, reverse, ct).ConfigureAwait(false);
sourceResult = await ReadSourcesAsync(startUtc, endUtc, fetch, reverse, ct).ConfigureAwait(false);
}
// Truncation is the SOURCE's word (non-null continuation point) — never inferred from the count, so a
@@ -8004,8 +8072,8 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
// with an explicit bounded cap and page WITHIN it (same scheme as raw).
var resolution = Math.Max(1L, source.TimestampResolutionTicks);
var overfetchCap = (int)Math.Min(int.MaxValue - 1L, (long)Math.Max(1, MaxTieClusterOverfetch) + 1);
IReadOnlyList<HistoricalEvent> cluster = (await source.ReadEventsAsync(
sourceName, startUtc, startUtc.AddTicks(resolution), overfetchCap, reverse: false, ct)
IReadOnlyList<HistoricalEvent> cluster = (await ReadSourcesAsync(
startUtc, startUtc.AddTicks(resolution), overfetchCap, rev: false, ct)
.ConfigureAwait(false)).Events;
// A walked read emitted its ties sorted by EventId; the gateway returns them in any order and its
@@ -8041,7 +8109,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
if (nextStartUtc is { } resumeAt)
{
pendingCursor = new HistoryContinuationState(
sourceName ?? string.Empty, resumeAt, endUtc, nextSkip, numValuesPerNode, HistoryCursorKind.Events,
sourceName, resumeAt, endUtc, nextSkip, numValuesPerNode, HistoryCursorKind.Events,
Reverse: reverse, SegmentWidthTicks: walkHint.WidthTicks, EmptyFromTicks: walkHint.EmptyFromTicks,
EmptyToTicks: walkHint.EmptyToTicks);
}
@@ -8054,7 +8122,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
var skip = 0;
for (var i = events.Count - 1; i >= 0 && events[i].EventTimeUtc == boundary; i--) skip++;
pendingCursor = new HistoryContinuationState(
sourceName ?? string.Empty, boundary, endUtc, skip, numValuesPerNode, HistoryCursorKind.Events,
sourceName, boundary, endUtc, skip, numValuesPerNode, HistoryCursorKind.Events,
Reverse: reverse, SegmentWidthTicks: walkHint.WidthTicks, EmptyFromTicks: walkHint.EmptyFromTicks,
EmptyToTicks: walkHint.EmptyToTicks);
}
@@ -8062,6 +8130,9 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
// The where-clause filters AFTER the page's cursor was taken from the unfiltered events, so paging (time,
// boundary skip) is exactly as without a filter: a page may come back with fewer events — even none — and a
// continuation point, never skipping or repeating one.
// #886: an AVEVA row naming a native condition that fires on this folder carries that condition's SourceNode and
// ConditionName, as the live event does. Rewritten after paging: EventId and time are untouched.
events = scope.ResolveConditions(events);
var historyEvent = ProjectEvents(events, selectClauses, where, filterContext);
var outboundCp = pendingCursor is null ? null : SaveHistoryContinuation(session, handle.NodeId, historyEpoch, pendingCursor);
results[handle.Index] = new SdkHistoryReadResult