Compare commits

...

5 Commits

Author SHA1 Message Date
Joseph Doherty 10a6ac6f3e docs(historian-gateway): note FU-3 alias handling (review fix) in follow-up plan
v2-ci / build (pull_request) Failing after 41s
v2-ci / unit-tests (tests/Core/ZB.MOM.WW.OtOpcUa.Cluster.Tests) (pull_request) Has been skipped
v2-ci / unit-tests (tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests) (pull_request) Has been skipped
v2-ci / unit-tests (tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests) (pull_request) Has been skipped
v2-ci / unit-tests (tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests) (pull_request) Has been skipped
v2-ci / unit-tests (tests/Server/ZB.MOM.WW.OtOpcUa.Security.Tests) (pull_request) Has been skipped
v2-ci / integration (tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests) (pull_request) Has been skipped
v2-ci / integration (tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests) (pull_request) Has been skipped
Claude-Session: https://claude.ai/code/session_012SDSQ3AcaXqPcBtDESBRii
2026-06-27 00:57:14 -04:00
Joseph Doherty 60695179ee fix(historian-gateway): historize EVERY aliased tag sharing a mux ref (FU-3 review — close silent-drop)
Code review found a residual silent-data-loss path: a single driver ref (mux
ref) can back SEVERAL historized equipment tags via aliasing (identical machines
sharing a register — DriverHostActor._nodeIdByDriverRef is a HashSet), each with
its own HistorianTagname. The muxRef->single-name map collapsed last-wins, so
under alias + divergent overrides only one historian tag got the value and the
rest were silently dropped — the exact failure class FU-3 exists to eliminate.

Model the fan as muxRef -> HashSet<historianName> and append ONE outbox entry per
name in OnValueChangedAsync (a per-name append failure drops only that name and
continues). Convergence removes/adds each (muxRef, name) pair individually from
the per-ref set, dropping the mux key only when its last name is removed — so
removing one alias leaves the shared ref fanning for the others with no mux churn.

Tests: aliased-refs-each-get-the-value (one fan → both historian names written),
removing-one-alias-keeps-the-ref-registered, and the override-rename test now
feeds a value post-rename to prove the write target actually moved to the new
name. Runtime 350/0, OpcUaServer 327/0; 0 warnings.

Claude-Session: https://claude.ai/code/session_012SDSQ3AcaXqPcBtDESBRii
2026-06-27 00:56:17 -04:00
Joseph Doherty 00cc1da362 docs(historian-gateway): mark follow-up plan status — FU-1 documented-limitation, FU-2/3/4 done
Record the execution outcomes in the follow-up plan: FU-1 resolved as a documented
protocol limitation (gateway pending.md C4; not fixable without histsdk wire-capture
evidence), FU-2 done + live-validated (exact round-trip), FU-3 done (mux-ref vs
historian-name decoupled via HistorizedTagRef), FU-4 done. FU-5 (pre-existing Modbus
failure) and FU-6 (post-merge propagation) remain tracked.

Claude-Session: https://claude.ai/code/session_012SDSQ3AcaXqPcBtDESBRii
2026-06-27 00:45:19 -04:00
Joseph Doherty 111adc92b6 fix(historian-gateway): historize under the historian name, not the mux ref, when HistorianTagname overrides (FU-3)
The continuous-historization recorder conflated two identifiers into one string:
the dependency mux fans DependencyValueChanged keyed by the driver FullName
(the mux ref), but a value must be historized under the resolved historian name
(HistorianTagname override, else FullName). In the common no-override case the
two are equal, so it worked; with an override they diverge and the recorder
registered mux interest under a key the mux never fans — that tag's values were
never captured (and, had they been, would have been written under the mux ref).

Carry BOTH identifiers through the seam: a new HistorizedTagRef(MuxRef,
HistorianName) record on IHistorizedTagSubscriptionSink. The applier resolves
MuxRef = FullName and HistorianName = override-or-FullName. The recorder now
keeps a muxRef->historianName map: it registers/filters mux interest by MuxRef
but writes the outbox entry (and drains) under HistorianName. The convergence
handler re-registers the mux only when the registered key-set changes, so an
override-only rename (same FullName) updates the write target without mux churn.

Tests: a divergent-override recorder test (interest by mux ref, value written
under the override name, never the mux ref) + an override-rename no-churn test;
the applier feed tests now assert the full (mux ref, historian name) pairs.
Runtime 348/0, OpcUaServer 327/0; 0 warnings. Closes FU-3.

Claude-Session: https://claude.ai/code/session_012SDSQ3AcaXqPcBtDESBRii
2026-06-27 00:43:28 -04:00
Joseph Doherty b2276b5b04 test(historian-gateway): cover AlarmHistorianOptions.Validate MaxAttempts<=0 warning (FU-4)
The MaxAttempts<=0 warning branch in AlarmHistorianOptions.Validate() was the
only one without a test (the sibling DrainIntervalSeconds/Capacity/
DeadLetterRetentionDays warnings are covered). Add the matching case. Closes FU-4.

Claude-Session: https://claude.ai/code/session_012SDSQ3AcaXqPcBtDESBRii
2026-06-27 00:24:12 -04:00
8 changed files with 390 additions and 94 deletions
@@ -7,6 +7,22 @@ the live `Category=LiveIntegration` suite is green (read ✅, write-persist ✅,
alarm-readback ⏭ skip). This doc tracks everything deliberately deferred or surfaced during
validation, with the **owning repo** for each.
> **Execution update (2026-06-27 — this follow-up pass):**
> - **FU-1 — RESOLVED as a documented protocol limitation** (NOT a fixable gateway bug): the captured
> CM_EVENT event-send wire never carries `SourceName`, so `Source_Object` cannot be populated by the
> gateway. Recorded as `pending.md` **C4** + a CLAUDE.md note in the HistorianGateway repo (commit
> `174a4a9` on `fix/gateway-otopcua-followups`). The OtOpcUa live test stays skipped with the corrected
> reason. See FU-1 below for the (now-confirmed) root cause.
> - **FU-2 — ✅ DONE + live-validated** in HistorianGateway (`fix/gateway-otopcua-followups`, commits
> `150868c` + `1c2d11d`). The SQL live-write path converts UTC→server-local in-SQL via
> `DATEADD(MINUTE, DATEPART(TZOFFSET, SYSDATETIMEOFFSET()), @dt)`; an explicit-timestamp round-trip is
> now EXACT against the live historian (delta 00:00:00).
> - **FU-3 — ✅ DONE** in OtOpcUa (this branch, commit `111adc92`): `HistorizedTagRef(MuxRef, HistorianName)`
> carried through the sink/recorder; interest registered by mux ref, values written under the historian
> name. Recorder + applier tests green.
> - **FU-4 — ✅ DONE** in OtOpcUa (this branch, commit `b2276b5b`).
> - **FU-5** — still pre-existing/not-ours (tracked below). **FU-6** — still pending the merges.
**Live-validation harness recap (how to reproduce any of the live findings below):** run the
HistorianGateway locally against the live historian, then point the OtOpcUa live tests (or `grpcurl`)
at it. The gateway boots from env-var config (secrets from `~/.zshenv`):
@@ -34,7 +50,15 @@ always include an `EventTimeUtc` range. `sqlcmd -S $HISTORIAN_GRPC_HOST -d Runti
**Owning repo: `~/Desktop/HistorianGateway` (HistorianGateway).** OtOpcUa code is correct for both;
these are gateway defects that gate the "write OtOpcUa's own data, read it back" use case.
### FU-1 — `SendEvent` does not populate `Source_Object` (alarm write-back-by-source)
### FU-1 — `SendEvent` does not populate `Source_Object` — ✅ RESOLVED as a documented protocol limitation (2026-06-27)
> **Outcome:** root-caused and confirmed **not fixable at the gateway** — the captured CM_EVENT event-send
> wire (`HistorianEventWriteProtocol.SerializeEventValueBlob`) serializes Namespace/Type/properties but
> **never `SourceName`** (the gateway threads it correctly; the wire drops it). `Source_Object` is a
> Galaxy-platform association for object-raised events. Documented as `pending.md` **C4** + a CLAUDE.md note
> in HistorianGateway; likely won't-fix (would need new wire-capture evidence in `histsdk` — vendored
> sources aren't hand-edited). The "Investigation/Proposed fix" below is retained for the record; option 1
> is now known to be infeasible.
**Symptom (live-proven):** OtOpcUa's `GatewayAlarmHistorianWriter.SendEvent` of an event with
`source_name="HistGW.LiveTest.AlarmSource"` **acks** and **lands in `Runtime.dbo.Events`** with the
correct `Type` (`LimitAlarm`) and `EventTimeUtc` (no shift) — but with **`Source_Object = NULL`** (and
@@ -74,7 +98,13 @@ window. Then **un-skip** `Alarm_SendEvent_then_ReadEvents` in
`tests/Drivers/.../Live/GatewayLiveIntegrationTests.cs` (it currently `Assert.Skip`s on a 0-result with
the accurate reason).
### FU-2 — `WriteLiveValues` shifts an explicit timestamp by the local↔UTC offset (~+4h)
### FU-2 — `WriteLiveValues` shifts an explicit timestamp by the local↔UTC offset (~+4h) — ✅ DONE + live-validated (2026-06-27)
> **Outcome:** fixed in HistorianGateway (`fix/gateway-otopcua-followups`). The SQL live-write path now
> converts UTC→server-local in-SQL via `DATEADD(MINUTE, DATEPART(TZOFFSET, SYSDATETIMEOFFSET()), @dt)` (a
> single atomic offset read). An explicit-timestamp round-trip (real SQL write → gateway UTC ReadRaw) is now
> EXACT against the live 2023 R2 historian (delta 00:00:00); offline unit test locks the exact conversion
> expression. The OtOpcUa live write test can now be tightened (see acceptance).
**Symptom (live-proven, reproduces via raw `grpcurl` — no OtOpcUa code involved):** a `WriteLiveValues`
with an **explicit** `timestamp=2026-06-27T03:45:00Z` lands in the historian at
`2026-06-27T07:45:00Z` (+4h = the deployment's local↔UTC delta). A **server-stamped** write (null
@@ -106,7 +136,17 @@ window anchored on the write time.
## Priority 2 — OtOpcUa-side follow-ups
**Owning repo: `~/Desktop/OtOpcUa` (this repo).**
### FU-3 — Continuous-historization `HistorianTagname` override edge case
### FU-3 — Continuous-historization `HistorianTagname` override edge case — ✅ DONE (2026-06-27, commit `111adc92`)
> **Outcome:** implemented the "carry both identifiers" fix below. A new `HistorizedTagRef(MuxRef,
> HistorianName)` record threads through `IHistorizedTagSubscriptionSink` → the recorder; the recorder keeps
> a **muxRef → SET-of-historian-names** map, registers/filters mux interest by `MuxRef` (= driver `FullName`)
> but writes under every `HistorianName` (override-or-FullName) sharing that ref. The applier resolves both.
> The set (not a single name) closes a code-review **Critical**: one driver ref can back several historized
> equipment tags via aliasing (identical machines sharing a register), each with its own override — a single
> fan must write ALL of them, not silently drop all but one. Tests: divergent-override, aliased-refs-each-
> get-the-value, remove-one-alias-keeps-the-ref, override-rename updates the write target without mux churn;
> applier feed tests assert the full pairs. Commits `111adc92` + `60695179` (review fix).
The `ContinuousHistorizationRecorder` registers `DependencyMuxActor` interest **by the resolved
historian name** (`HistorianTagname` override else `FullName`) — the same key the EnsureTags hook and
the writer use. The mux fans `DependencyValueChanged` **keyed by `FullReference`** (the driver's
@@ -120,7 +160,7 @@ under the resolved historian name — i.e. carry both identifiers through `IHist
a divergent override. **Low urgency** (overrides are uncommon); only matters for non-Galaxy historized
tags that set an explicit `HistorianTagname`.
### FU-4 — `AlarmHistorianOptions.Validate()` `MaxAttempts<=0` test coverage (minor)
### FU-4 — `AlarmHistorianOptions.Validate()` `MaxAttempts<=0` test coverage (minor) — ✅ DONE (2026-06-27, commit `b2276b5b`)
T19 pruned the Wonderware-shaped fields and reworked `AlarmHistorianRegistrationTests`. The
`MaxAttempts <= 0` warning branch in `AlarmHistorianOptions.Validate()` is exercised in prod but not
covered by a test (the sibling warnings for `DrainIntervalSeconds`/`Capacity`/`DeadLetterRetentionDays`
@@ -1,5 +1,35 @@
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions;
/// <summary>
/// A single historized tag the recorder tracks, carrying BOTH identifiers it needs — kept distinct
/// because a <c>HistorianTagname</c> override makes them diverge:
/// <list type="bullet">
/// <item>
/// <see cref="MuxRef"/> — the driver-published reference the per-node dependency mux fans its
/// <c>DependencyValueChanged</c> by (the tag's driver-side <c>FullName</c>). The recorder
/// registers mux interest and matches incoming values by THIS.
/// </item>
/// <item>
/// <see cref="HistorianName"/> — the resolved historian tag name the value is written under (a
/// non-alarm historized value variable's <c>HistorianTagname</c> override, else its
/// <c>FullName</c>) — the SAME name the EnsureTags provisioning hook ensures.
/// </item>
/// </list>
/// In the common (no-override) case the two are the same string; an override is the only case they
/// diverge, and conflating them would silently drop that tag's values (interest registered under a
/// key the mux never fans).
/// </summary>
/// <param name="MuxRef">The driver ref the mux fans by (and the key the recorder registers interest under).</param>
/// <param name="HistorianName">The resolved historian tag name the value is historized under.</param>
public sealed record HistorizedTagRef(string MuxRef, string HistorianName)
{
/// <summary>The no-override identity: the mux ref and historian name are the same string (the tag has
/// no <c>HistorianTagname</c> override, so it historizes under its own driver <c>FullName</c>).</summary>
/// <param name="reference">The driver ref that serves as both the mux key and the historian name.</param>
/// <returns>A ref whose <see cref="MuxRef"/> and <see cref="HistorianName"/> are equal.</returns>
public static HistorizedTagRef ForSelf(string reference) => new(reference, reference);
}
/// <summary>
/// Server-side feed that keeps the continuous-historization recorder's set of historized tag refs
/// in step with the deployed address space. The <c>AddressSpaceApplier</c> (in the
@@ -18,15 +48,16 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions;
public interface IHistorizedTagSubscriptionSink
{
/// <summary>
/// Converge the recorder's historized-ref interest by an add/remove delta. The refs are
/// resolved EXACTLY as the EnsureTags provisioning hook resolves them (a non-alarm historized
/// value variable's <c>HistorianTagname</c> override, else its driver-side <c>FullName</c>).
/// The recorder applies the delta to its tracked full set and re-registers mux interest only
/// when the set actually changes.
/// Converge the recorder's historized-ref interest by an add/remove delta. Each ref carries both
/// its <see cref="HistorizedTagRef.MuxRef"/> (the driver ref the mux fans by) and its
/// <see cref="HistorizedTagRef.HistorianName"/> (the resolved override-or-FullName the value is
/// historized under) — the same name the EnsureTags provisioning hook ensures. The recorder
/// applies the delta to its tracked full set and re-registers mux interest (keyed by
/// <see cref="HistorizedTagRef.MuxRef"/>) only when the registered key-set actually changes.
/// </summary>
/// <param name="added">Historized refs newly historized by this deploy (added/changed-into tags).</param>
/// <param name="removed">Historized refs no longer historized by this deploy (removed/changed-out tags).</param>
void UpdateHistorizedRefs(IReadOnlyList<string> added, IReadOnlyList<string> removed);
void UpdateHistorizedRefs(IReadOnlyList<HistorizedTagRef> added, IReadOnlyList<HistorizedTagRef> removed);
}
/// <summary>
@@ -42,7 +73,7 @@ public sealed class NullHistorizedTagSubscriptionSink : IHistorizedTagSubscripti
private NullHistorizedTagSubscriptionSink() { }
/// <inheritdoc />
public void UpdateHistorizedRefs(IReadOnlyList<string> added, IReadOnlyList<string> removed)
public void UpdateHistorizedRefs(IReadOnlyList<HistorizedTagRef> added, IReadOnlyList<HistorizedTagRef> removed)
{
}
}
@@ -309,37 +309,38 @@ public sealed class AddressSpaceApplier
{
try
{
List<string>? added = null;
List<string>? removed = null;
List<HistorizedTagRef>? added = null;
List<HistorizedTagRef>? removed = null;
// Added historized value variables → new interest.
foreach (var tag in plan.AddedEquipmentTags)
{
if (HistorizedRef(tag) is { } r) (added ??= new List<string>()).Add(r);
if (HistorizedRef(tag) is { } r) (added ??= new List<HistorizedTagRef>()).Add(r);
}
// Removed historized value variables → drop interest.
foreach (var tag in plan.RemovedEquipmentTags)
{
if (HistorizedRef(tag) is { } r) (removed ??= new List<string>()).Add(r);
if (HistorizedRef(tag) is { } r) (removed ??= new List<HistorizedTagRef>()).Add(r);
}
// Changed tags: the historized ref may have flipped on/off or been renamed (override/FullName
// change). Compare previous-vs-current resolved refs — an unchanged ref is a no-op.
// change). Compare previous-vs-current resolved ref PAIRS (record equality compares both the
// mux ref and the historian name) — an unchanged pair is a no-op.
foreach (var d in plan.ChangedEquipmentTags)
{
var prev = HistorizedRef(d.Previous);
var cur = HistorizedRef(d.Current);
if (string.Equals(prev, cur, StringComparison.Ordinal)) continue;
if (prev is not null) (removed ??= new List<string>()).Add(prev);
if (cur is not null) (added ??= new List<string>()).Add(cur);
if (prev == cur) continue;
if (prev is not null) (removed ??= new List<HistorizedTagRef>()).Add(prev);
if (cur is not null) (added ??= new List<HistorizedTagRef>()).Add(cur);
}
if (added is null && removed is null) return;
_historizedSubscriptions.UpdateHistorizedRefs(
added ?? (IReadOnlyList<string>)Array.Empty<string>(),
removed ?? (IReadOnlyList<string>)Array.Empty<string>());
added ?? (IReadOnlyList<HistorizedTagRef>)Array.Empty<HistorizedTagRef>(),
removed ?? (IReadOnlyList<HistorizedTagRef>)Array.Empty<HistorizedTagRef>());
}
catch (Exception ex)
{
@@ -350,16 +351,21 @@ public sealed class AddressSpaceApplier
}
/// <summary>
/// Resolve the historized tag ref for <paramref name="tag"/> EXACTLY as the provisioning hook /
/// materialiser do: a non-alarm historized value variable's <c>HistorianTagname</c> override,
/// else its driver-side <c>FullName</c>. Returns <c>null</c> when the tag is not a historized
/// Resolve the historized tag ref for <paramref name="tag"/> as a
/// <see cref="HistorizedTagRef"/> carrying BOTH identifiers the recorder needs: the
/// <c>MuxRef</c> = the driver-side <c>FullName</c> the dependency mux fans values by, and the
/// <c>HistorianName</c> = the value the EnsureTags hook / materialiser write under (a non-alarm
/// historized value variable's <c>HistorianTagname</c> override, else its <c>FullName</c>). The
/// two diverge ONLY when an override is set. Returns <c>null</c> when the tag is not a historized
/// value variable (not historized, or a native-alarm condition node).
/// </summary>
/// <param name="tag">The equipment tag to resolve a historized ref for.</param>
/// <returns>The resolved historian ref, or <c>null</c> when the tag is not a historized value variable.</returns>
private static string? HistorizedRef(EquipmentTagPlan tag) =>
/// <returns>The resolved historized ref pair, or <c>null</c> when the tag is not a historized value variable.</returns>
private static HistorizedTagRef? HistorizedRef(EquipmentTagPlan tag) =>
tag.IsHistorized && tag.Alarm is null
? (string.IsNullOrWhiteSpace(tag.HistorianTagname) ? tag.FullName : tag.HistorianTagname)
? new HistorizedTagRef(
tag.FullName,
string.IsNullOrWhiteSpace(tag.HistorianTagname) ? tag.FullName : tag.HistorianTagname)
: null;
private void SafeRebuild()
@@ -24,7 +24,7 @@ public sealed class ActorHistorizedTagSubscriptionSink : IHistorizedTagSubscript
}
/// <inheritdoc />
public void UpdateHistorizedRefs(IReadOnlyList<string> added, IReadOnlyList<string> removed)
public void UpdateHistorizedRefs(IReadOnlyList<HistorizedTagRef> added, IReadOnlyList<HistorizedTagRef> removed)
{
ArgumentNullException.ThrowIfNull(added);
ArgumentNullException.ThrowIfNull(removed);
@@ -1,5 +1,6 @@
using Akka.Actor;
using Akka.Event;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.Historian;
using ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags;
@@ -67,12 +68,14 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers
/// Converge the recorder's historized-ref interest by an add/remove DELTA — sent by the
/// address-space applier (via <see cref="ZB.MOM.WW.OtOpcUa.Core.Abstractions.IHistorizedTagSubscriptionSink"/>)
/// after every deploy. The applier only ever sees a plan diff, so it feeds a delta; the recorder
/// holds the full set and re-registers it (see <see cref="OnUpdateHistorizedRefs"/>). The refs are
/// the same ones the EnsureTags provisioning hook resolves (override-or-FullName).
/// holds the full set and re-registers it (see <see cref="OnUpdateHistorizedRefs"/>). Each ref
/// carries both its mux key (<see cref="HistorizedTagRef.MuxRef"/>, the driver ref the mux fans by)
/// and the resolved historian name (<see cref="HistorizedTagRef.HistorianName"/>,
/// override-or-FullName — the same name the EnsureTags provisioning hook ensures).
/// </summary>
/// <param name="Added">Refs newly historized by this deploy.</param>
/// <param name="Removed">Refs no longer historized by this deploy.</param>
public sealed record UpdateHistorizedRefs(IReadOnlyList<string> Added, IReadOnlyList<string> Removed);
public sealed record UpdateHistorizedRefs(IReadOnlyList<HistorizedTagRef> Added, IReadOnlyList<HistorizedTagRef> Removed);
/// <summary>A point-in-time snapshot of the recorder's counters.</summary>
/// <param name="QueuedDepth">Un-acked entries currently held in the durable outbox.</param>
@@ -93,8 +96,15 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers
private readonly IActorRef _dependencyMux;
private readonly IHistorianValueWriter _writer;
private readonly IHistorizationOutbox _outbox;
private readonly IReadOnlyList<string> _historizedRefs;
private readonly HashSet<string> _historizedSet;
/// <summary>The tracked historized tags, keyed by mux ref (<see cref="HistorizedTagRef.MuxRef"/> — the
/// driver ref the mux fans by, and the key mux interest is registered under) → the SET of historian
/// names that ref's value is written under (<see cref="HistorizedTagRef.HistorianName"/>). It is a SET,
/// not a single name, because one driver ref can back SEVERAL historized equipment tags via aliasing
/// (identical machines sharing a register), each with its own <c>HistorianTagname</c> — the mux fans
/// one value per ref and every aliased historian tag must receive it. In the common case the set holds
/// a single name equal to the mux ref (no override, no alias).</summary>
private readonly Dictionary<string, HashSet<string>> _refMap;
private readonly int _drainBatchSize;
private readonly TimeSpan _drainInterval;
private readonly TimeSpan _minBackoff;
@@ -157,8 +167,15 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers
_dependencyMux = dependencyMux ?? throw new ArgumentNullException(nameof(dependencyMux));
_writer = writer ?? throw new ArgumentNullException(nameof(writer));
_outbox = outbox ?? throw new ArgumentNullException(nameof(outbox));
_historizedRefs = historizedRefs ?? throw new ArgumentNullException(nameof(historizedRefs));
_historizedSet = new HashSet<string>(_historizedRefs, StringComparer.Ordinal);
ArgumentNullException.ThrowIfNull(historizedRefs);
// The ctor seed is the no-override identity (mux ref == historian name); production seeds an EMPTY
// set and converges via UpdateHistorizedRefs on each deploy (which carries diverging override pairs).
_refMap = new Dictionary<string, HashSet<string>>(StringComparer.Ordinal);
foreach (string r in historizedRefs)
{
AddRef(r, r);
}
_drainBatchSize = drainBatchSize > 0 ? drainBatchSize : 64;
_drainInterval = drainInterval is { } di && di > TimeSpan.Zero ? di : TimeSpan.FromSeconds(2);
_minBackoff = minBackoff is { } mb && mb > TimeSpan.Zero ? mb : TimeSpan.FromSeconds(1);
@@ -182,8 +199,9 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers
/// <inheritdoc />
protected override void PreStart()
{
// Register interest for the historized refs so the mux fans their DependencyValueChanged to us.
_dependencyMux.Tell(new DependencyMuxActor.RegisterInterest(_historizedRefs, Self));
// Register interest by mux ref (the key the mux fans DependencyValueChanged by) so it fans those
// tags' values to us. Historian-name overrides are tracked separately for the write side.
_dependencyMux.Tell(new DependencyMuxActor.RegisterInterest(_refMap.Keys.ToList(), Self));
// Seed the steady drain cadence; appends also nudge a prompt drain (see OnValueChangedAsync).
Timers.StartSingleTimer(DrainTimerKey, DrainTick.Instance, _drainInterval);
base.PreStart();
@@ -202,8 +220,12 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers
private async Task OnValueChangedAsync(VirtualTagActor.DependencyValueChanged msg)
{
// Defensive: only historize refs we registered interest for (the mux already scopes to these).
if (!_historizedSet.Contains(msg.TagId))
// The mux fans values keyed by the driver ref (msg.TagId == the mux ref). Only historize refs we
// registered interest for, and resolve the HISTORIAN NAME(s) to write under — which differ from the
// mux ref under a HistorianTagname override, and there can be MORE THAN ONE when several historized
// equipment tags alias the same driver ref. (The mux already scopes to our registered refs; this is
// also the defensive filter.)
if (!_refMap.TryGetValue(msg.TagId, out HashSet<string>? historianNames) || historianNames.Count == 0)
{
return;
}
@@ -217,38 +239,49 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers
return;
}
var entry = new HistorizationOutboxEntry(
Guid.NewGuid(),
msg.TagId,
numeric,
GoodQuality,
DateTime.SpecifyKind(msg.TimestampUtc, DateTimeKind.Utc));
var timestampUtc = DateTime.SpecifyKind(msg.TimestampUtc, DateTimeKind.Utc);
// Durable boundary: append (awaited so appends stay serialized) BEFORE the value is considered
// captured. The outbox drops the oldest entry on capacity overflow and tracks DroppedCount.
try
// One outbox entry PER historian name: a single mux fan-out must reach every aliased historized tag
// (each its own historian name), not just one — collapsing to one name here would silently drop the
// rest. Snapshot the names first: although the mailbox is suspended across the awaits below (so the
// set cannot be mutated concurrently), iterating a snapshot is robust and clearer.
foreach (string historianName in historianNames.ToList())
{
await _outbox.AppendAsync(entry, _lifetime.Token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (_lifetime.IsCancellationRequested)
{
// Normal shutdown raced the append — not a fault. Drop quietly.
return;
}
catch (Exception ex)
{
// A durable-boundary failure (e.g. a PerEntry fsync hitting disk-full / I/O error) must NEVER
// propagate out of the handler — that would trip Akka supervision into a restart, and under a
// persistent disk fault the actor would restart-loop (re-register → next value → append fails
// → restart → …). Mirror the drain path's catch-all: meter the failure (category only, no
// value content), drop this value, and stay alive. Do NOT record it or nudge the drain.
_outboxAppendFailures++;
_log.Warning("ContinuousHistorization: outbox append failed ({Exception}); value dropped.",
ex.GetType().Name);
return;
}
// Record under the historian name (override-or-FullName), NOT the mux ref — the outbox entry +
// the drain's WriteLiveValues target the historian tag the EnsureTags hook provisioned.
var entry = new HistorizationOutboxEntry(
Guid.NewGuid(),
historianName,
numeric,
GoodQuality,
timestampUtc);
_totalRecorded++;
// Durable boundary: append (awaited so appends stay serialized) BEFORE the value is considered
// captured. The outbox drops the oldest entry on capacity overflow and tracks DroppedCount.
try
{
await _outbox.AppendAsync(entry, _lifetime.Token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (_lifetime.IsCancellationRequested)
{
// Normal shutdown raced the append — not a fault. Drop quietly (abandon the rest too).
return;
}
catch (Exception ex)
{
// A durable-boundary failure (e.g. a PerEntry fsync hitting disk-full / I/O error) must
// NEVER propagate out of the handler — that would trip Akka supervision into a restart, and
// under a persistent disk fault the actor would restart-loop (re-register → next value →
// append fails → restart → …). Mirror the drain path's catch-all: meter the failure
// (category only, no value content), drop THIS name's value, and continue with the rest.
_outboxAppendFailures++;
_log.Warning("ContinuousHistorization: outbox append failed ({Exception}); value dropped.",
ex.GetType().Name);
continue;
}
_totalRecorded++;
}
// Nudge a prompt drain attempt; the DrainTick handler de-dups (already draining) and honours
// any active backoff window, so this never bypasses a failure cooldown.
@@ -277,31 +310,68 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers
/// </summary>
private void OnUpdateHistorizedRefs(UpdateHistorizedRefs msg)
{
var next = new HashSet<string>(_historizedSet, StringComparer.Ordinal);
next.ExceptWith(msg.Removed);
next.UnionWith(msg.Added);
if (next.SetEquals(_historizedSet))
// Snapshot the registered mux key-set BEFORE applying the delta, so we re-register only when the
// set the mux fans by actually changes (an override-only rename updates the WRITE target but not
// which refs the mux fans — no mux churn for those).
var beforeKeys = new HashSet<string>(_refMap.Keys, StringComparer.Ordinal);
// Apply removed-then-added so a ref present in BOTH (a HistorianTagname override changed while the
// mux ref / FullName stayed the same) ends mapped to its NEW historian name. Each (muxRef, name)
// pair is removed/added INDIVIDUALLY from the per-ref name set, so aliased tags sharing a mux ref
// are converged independently (removing one alias's name leaves the others fanning).
foreach (HistorizedTagRef r in msg.Removed)
{
// No net change — stay idempotent (no mux churn).
if (_refMap.TryGetValue(r.MuxRef, out HashSet<string>? names))
{
names.Remove(r.HistorianName);
if (names.Count == 0)
{
_refMap.Remove(r.MuxRef);
}
}
}
foreach (HistorizedTagRef r in msg.Added)
{
AddRef(r.MuxRef, r.HistorianName);
}
if (_refMap.Keys.ToHashSet(StringComparer.Ordinal).SetEquals(beforeKeys))
{
// Mux key-set unchanged (no-op delta, an override-only rename, or an alias add/remove that
// leaves the ref still fanned) — the per-ref name sets (write targets) are already updated;
// stay idempotent at the mux (no register/unregister churn).
return;
}
_historizedSet.Clear();
_historizedSet.UnionWith(next);
if (_historizedSet.Count == 0)
if (_refMap.Count == 0)
{
// The mux has no per-ref unregister; drop ALL interest in one message.
_dependencyMux.Tell(new DependencyMuxActor.UnregisterInterest(Self));
}
else
{
// RegisterInterest REPLACES the prior set at the mux, so one message converges it exactly.
_dependencyMux.Tell(new DependencyMuxActor.RegisterInterest(_historizedSet.ToList(), Self));
// RegisterInterest REPLACES the prior set at the mux, so one message (carrying the mux keys)
// converges it exactly.
_dependencyMux.Tell(new DependencyMuxActor.RegisterInterest(_refMap.Keys.ToList(), Self));
}
_log.Debug("ContinuousHistorization: historized-ref interest converged to {Count} ref(s).",
_historizedSet.Count);
_log.Debug("ContinuousHistorization: historized-ref interest converged to {Count} mux ref(s).",
_refMap.Count);
}
/// <summary>Adds a <c>(mux ref → historian name)</c> mapping to the tracked set, creating the per-ref
/// name set on first use. Idempotent — adding the same pair twice is a no-op (a <see cref="HashSet{T}"/>
/// add).</summary>
private void AddRef(string muxRef, string historianName)
{
if (!_refMap.TryGetValue(muxRef, out HashSet<string>? names))
{
names = new HashSet<string>(StringComparer.Ordinal);
_refMap[muxRef] = names;
}
names.Add(historianName);
}
private void OnDrainTick()
@@ -147,17 +147,17 @@ public sealed class AddressSpaceApplierProvisioningTests
/// ref deltas the applier feeds it. A <see cref="Throw"/> flag simulates a faulting feed.</summary>
private sealed class CapturingSubscriptionSink : IHistorizedTagSubscriptionSink
{
/// <summary>Refs the applier fed as ADDED.</summary>
public List<string> Added { get; } = new();
/// <summary>Ref pairs the applier fed as ADDED (mux ref + historian name).</summary>
public List<HistorizedTagRef> Added { get; } = new();
/// <summary>Refs the applier fed as REMOVED.</summary>
public List<string> Removed { get; } = new();
/// <summary>Ref pairs the applier fed as REMOVED.</summary>
public List<HistorizedTagRef> Removed { get; } = new();
/// <summary>When true, <see cref="UpdateHistorizedRefs"/> throws synchronously.</summary>
public bool Throw { get; init; }
/// <inheritdoc />
public void UpdateHistorizedRefs(IReadOnlyList<string> added, IReadOnlyList<string> removed)
public void UpdateHistorizedRefs(IReadOnlyList<HistorizedTagRef> added, IReadOnlyList<HistorizedTagRef> removed)
{
if (Throw) throw new InvalidOperationException("boom");
Added.AddRange(added);
@@ -182,7 +182,13 @@ public sealed class AddressSpaceApplierProvisioningTests
applier.Apply(plan);
sink.Added.ShouldBe(new[] { "Pump1.Temp", "40001" }, ignoreOrder: true); // override + FullName fallback
// Each ref carries BOTH identifiers: the override tag feeds (mux ref = FullName "ref", historian
// name = override "Pump1.Temp"); the no-override tag feeds (FullName "40001" as both).
sink.Added.ShouldBe(new[]
{
new HistorizedTagRef("ref", "Pump1.Temp"),
new HistorizedTagRef("40001", "40001"),
}, ignoreOrder: true);
sink.Removed.ShouldBeEmpty();
}
@@ -218,8 +224,14 @@ public sealed class AddressSpaceApplierProvisioningTests
applier.Apply(plan);
sink.Added.ShouldBe(new[] { "Pump1.B" }, ignoreOrder: true);
sink.Removed.ShouldBe(new[] { "Pump1.Old", "Pump1.A" }, ignoreOrder: true);
// All three tags default FullName "ref" (the mux ref); the override rename changes only the
// historian name, so the changed tag feeds removed (ref, Pump1.A) + added (ref, Pump1.B).
sink.Added.ShouldBe(new[] { new HistorizedTagRef("ref", "Pump1.B") }, ignoreOrder: true);
sink.Removed.ShouldBe(new[]
{
new HistorizedTagRef("ref", "Pump1.Old"),
new HistorizedTagRef("ref", "Pump1.A"),
}, ignoreOrder: true);
}
/// <summary>A synchronously-throwing subscription sink must NOT block or break the publish — the
@@ -152,6 +152,13 @@ public sealed class AlarmHistorianRegistrationTests
opts.Validate().ShouldContain(w => w.Contains("DeadLetterRetentionDays"));
}
[Fact]
public void Validate_warns_on_non_positive_max_attempts()
{
var opts = new AlarmHistorianOptions { Enabled = true, DatabasePath = "/abs/h.db", MaxAttempts = 0 };
opts.Validate().ShouldContain(w => w.Contains("MaxAttempts"));
}
[Fact]
public void Validate_accumulates_multiple_warnings()
{
@@ -1,6 +1,7 @@
using Akka.Actor;
using Akka.TestKit.Xunit2;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.Historian;
using ZB.MOM.WW.OtOpcUa.Runtime.Historian;
using ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags;
@@ -49,7 +50,8 @@ public sealed class ContinuousHistorizationRecorderTests : TestKit
Assert.Empty(initial.TagRefs);
rec.Tell(new ContinuousHistorizationRecorder.UpdateHistorizedRefs(
new[] { "Pump1.Temp", "Pump2.Flow" }, Array.Empty<string>()));
new[] { HistorizedTagRef.ForSelf("Pump1.Temp"), HistorizedTagRef.ForSelf("Pump2.Flow") },
Array.Empty<HistorizedTagRef>()));
var reg = mux.ExpectMsg<DependencyMuxActor.RegisterInterest>();
Assert.Equal(new[] { "Pump1.Temp", "Pump2.Flow" }, reg.TagRefs.OrderBy(x => x, StringComparer.Ordinal));
@@ -65,13 +67,14 @@ public sealed class ContinuousHistorizationRecorderTests : TestKit
mux.ExpectMsg<DependencyMuxActor.RegisterInterest>(); // PreStart (empty)
rec.Tell(new ContinuousHistorizationRecorder.UpdateHistorizedRefs(
new[] { "A", "B" }, Array.Empty<string>()));
new[] { HistorizedTagRef.ForSelf("A"), HistorizedTagRef.ForSelf("B") }, Array.Empty<HistorizedTagRef>()));
var first = mux.ExpectMsg<DependencyMuxActor.RegisterInterest>();
Assert.Equal(new[] { "A", "B" }, first.TagRefs.OrderBy(x => x, StringComparer.Ordinal));
// Add "C", remove "A" → converge to {B, C}. The mux's RegisterInterest is a full-REPLACE, so the
// recorder sends ONE RegisterInterest carrying exactly the converged set (C registered, A gone).
rec.Tell(new ContinuousHistorizationRecorder.UpdateHistorizedRefs(new[] { "C" }, new[] { "A" }));
rec.Tell(new ContinuousHistorizationRecorder.UpdateHistorizedRefs(
new[] { HistorizedTagRef.ForSelf("C") }, new[] { HistorizedTagRef.ForSelf("A") }));
var second = mux.ExpectMsg<DependencyMuxActor.RegisterInterest>();
Assert.Equal(new[] { "B", "C" }, second.TagRefs.OrderBy(x => x, StringComparer.Ordinal));
Assert.DoesNotContain("A", second.TagRefs);
@@ -88,7 +91,8 @@ public sealed class ContinuousHistorizationRecorderTests : TestKit
Assert.Equal(new[] { "A", "B" }, initial.TagRefs.OrderBy(x => x, StringComparer.Ordinal));
// A delta with no net effect (add an already-present ref, remove an absent one) → no mux churn.
rec.Tell(new ContinuousHistorizationRecorder.UpdateHistorizedRefs(new[] { "A" }, new[] { "Z" }));
rec.Tell(new ContinuousHistorizationRecorder.UpdateHistorizedRefs(
new[] { HistorizedTagRef.ForSelf("A") }, new[] { HistorizedTagRef.ForSelf("Z") }));
mux.ExpectNoMsg(TimeSpan.FromMilliseconds(300));
}
@@ -102,10 +106,136 @@ public sealed class ContinuousHistorizationRecorderTests : TestKit
mux.ExpectMsg<DependencyMuxActor.RegisterInterest>(); // PreStart {A}
// The mux has no per-ref unregister; an empty converged set drops ALL interest in one message.
rec.Tell(new ContinuousHistorizationRecorder.UpdateHistorizedRefs(Array.Empty<string>(), new[] { "A" }));
rec.Tell(new ContinuousHistorizationRecorder.UpdateHistorizedRefs(
Array.Empty<HistorizedTagRef>(), new[] { HistorizedTagRef.ForSelf("A") }));
mux.ExpectMsg<DependencyMuxActor.UnregisterInterest>();
}
[Fact]
public async Task HistorianTagname_override_registers_by_mux_ref_but_writes_under_historian_name()
{
// FU-3: a HistorianTagname override makes the mux ref (driver FullName the mux fans by) DIVERGE
// from the historian name (the value is stored under). Interest MUST be registered under the mux
// ref (else the mux never fans this tag), and the value MUST be written under the override name.
var mux = CreateTestProbe();
var writer = new FakeValueWriter { Succeed = true };
var outbox = new InMemoryOutbox();
var rec = Sys.ActorOf(ContinuousHistorizationRecorder.Props(
mux.Ref, writer, outbox, historizedRefs: Array.Empty<string>()));
mux.ExpectMsg<DependencyMuxActor.RegisterInterest>(); // PreStart (empty)
rec.Tell(new ContinuousHistorizationRecorder.UpdateHistorizedRefs(
new[] { new HistorizedTagRef("Area/Line/Pump1", "HIST.Pump1.Temp") },
Array.Empty<HistorizedTagRef>()));
// Interest is registered under the MUX REF (the driver ref the mux keys fan-out by), NOT the name.
var reg = mux.ExpectMsg<DependencyMuxActor.RegisterInterest>();
Assert.Equal(new[] { "Area/Line/Pump1" }, reg.TagRefs);
// The mux fans the value keyed by the driver ref; the recorder must historize it under the OVERRIDE.
rec.Tell(new VirtualTagActor.DependencyValueChanged("Area/Line/Pump1", 55.0, DateTime.UtcNow));
await AwaitAssertAsync(() =>
Assert.Contains(writer.Snapshot(), w => w.Tag == "HIST.Pump1.Temp" && w.Value == 55.0));
// ...and NEVER under the mux ref (the pre-fix behaviour wrote under msg.TagId == the mux ref).
Assert.DoesNotContain(writer.Snapshot(), w => w.Tag == "Area/Line/Pump1");
}
[Fact]
public async Task Override_rename_with_same_mux_ref_updates_target_without_mux_churn()
{
// An override changing while the driver FullName (mux ref) stays the same: removed+added carry the
// SAME mux ref with different historian names. The recorder must update the write target but NOT
// re-register the mux (the fanned key-set is unchanged).
var mux = CreateTestProbe();
var writer = new FakeValueWriter { Succeed = true };
var rec = Sys.ActorOf(ContinuousHistorizationRecorder.Props(
mux.Ref, writer, new InMemoryOutbox(), historizedRefs: Array.Empty<string>()));
mux.ExpectMsg<DependencyMuxActor.RegisterInterest>(); // PreStart (empty)
rec.Tell(new ContinuousHistorizationRecorder.UpdateHistorizedRefs(
new[] { new HistorizedTagRef("Area/Pump1", "HIST.Old") }, Array.Empty<HistorizedTagRef>()));
var reg = mux.ExpectMsg<DependencyMuxActor.RegisterInterest>();
Assert.Equal(new[] { "Area/Pump1" }, reg.TagRefs);
// Override renamed: same mux ref, new historian name. Key-set unchanged → no further mux message.
rec.Tell(new ContinuousHistorizationRecorder.UpdateHistorizedRefs(
new[] { new HistorizedTagRef("Area/Pump1", "HIST.New") },
new[] { new HistorizedTagRef("Area/Pump1", "HIST.Old") }));
mux.ExpectNoMsg(TimeSpan.FromMilliseconds(300));
// ...and the WRITE TARGET actually updated: a value now historizes under HIST.New, never HIST.Old.
rec.Tell(new VirtualTagActor.DependencyValueChanged("Area/Pump1", 9.0, DateTime.UtcNow));
await AwaitAssertAsync(() =>
Assert.Contains(writer.Snapshot(), w => w.Tag == "HIST.New" && w.Value == 9.0));
Assert.DoesNotContain(writer.Snapshot(), w => w.Tag == "HIST.Old");
}
[Fact]
public async Task Aliased_refs_with_distinct_overrides_each_get_the_value()
{
// Two historized tags share ONE driver ref ("Area/Pump1" — identical machines sharing a register),
// each with its OWN HistorianTagname. The mux fans a SINGLE value for the shared ref; BOTH historian
// tags must be written. A muxRef→single-name map would silently drop one (the FU-3 review's Critical).
var mux = CreateTestProbe();
var writer = new FakeValueWriter { Succeed = true };
var outbox = new InMemoryOutbox();
var rec = Sys.ActorOf(ContinuousHistorizationRecorder.Props(
mux.Ref, writer, outbox, historizedRefs: Array.Empty<string>()));
mux.ExpectMsg<DependencyMuxActor.RegisterInterest>(); // PreStart (empty)
rec.Tell(new ContinuousHistorizationRecorder.UpdateHistorizedRefs(
new[]
{
new HistorizedTagRef("Area/Pump1", "HIST.MachineA.Temp"),
new HistorizedTagRef("Area/Pump1", "HIST.MachineB.Temp"),
},
Array.Empty<HistorizedTagRef>()));
// ONE mux ref is registered (both aliases share it).
var reg = mux.ExpectMsg<DependencyMuxActor.RegisterInterest>();
Assert.Equal(new[] { "Area/Pump1" }, reg.TagRefs);
rec.Tell(new VirtualTagActor.DependencyValueChanged("Area/Pump1", 71.0, DateTime.UtcNow));
// BOTH historian names receive the single fanned value.
await AwaitAssertAsync(() =>
{
var snap = writer.Snapshot();
Assert.Contains(snap, w => w.Tag == "HIST.MachineA.Temp" && w.Value == 71.0);
Assert.Contains(snap, w => w.Tag == "HIST.MachineB.Temp" && w.Value == 71.0);
});
}
[Fact]
public void Removing_one_alias_keeps_the_shared_mux_ref_registered_for_the_other()
{
// Removing ONE alias's historian name from a shared mux ref must NOT drop the mux registration —
// the ref is still fanned for the surviving alias (key-set unchanged → no mux churn).
var mux = CreateTestProbe();
var rec = Sys.ActorOf(ContinuousHistorizationRecorder.Props(
mux.Ref, new FakeValueWriter(), new InMemoryOutbox(), historizedRefs: Array.Empty<string>()));
mux.ExpectMsg<DependencyMuxActor.RegisterInterest>(); // PreStart (empty)
rec.Tell(new ContinuousHistorizationRecorder.UpdateHistorizedRefs(
new[]
{
new HistorizedTagRef("Area/Pump1", "HIST.A"),
new HistorizedTagRef("Area/Pump1", "HIST.B"),
},
Array.Empty<HistorizedTagRef>()));
mux.ExpectMsg<DependencyMuxActor.RegisterInterest>(); // {Area/Pump1}
// Drop only HIST.A — Area/Pump1 still fans for HIST.B, so the key-set is unchanged: no mux churn.
rec.Tell(new ContinuousHistorizationRecorder.UpdateHistorizedRefs(
Array.Empty<HistorizedTagRef>(), new[] { new HistorizedTagRef("Area/Pump1", "HIST.A") }));
mux.ExpectNoMsg(TimeSpan.FromMilliseconds(300));
}
[Fact]
public async Task DependencyValueChanged_appends_to_outbox_then_drains_to_writer()
{