Files
lmxopcua/docs/plans/evidence/grpc-data-ext/A1-core.md
T

22 KiB
Raw Blame History

A1 (core condition state) — progress log and evidence

Phase A1 of docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md (revision 7), core condition-state part only (placements / condition_key / c1. ids are a parallel agent's; the six real native drivers are a later agent's). Branch worktree-agent-ad44f71fa7ab46039, based on master cbb5b396.

Drivers part — progress log (resume from here; detail in "Drivers" at the end)

  • Done: all six native sources implement IAlarmInitialStateSignal — Galaxy (b7f742ef), OpcUaClient (4e984b16), FOCAS (dbbc35e8), AbCip (8f1be256), Heidenhain (add4bc81), MTConnect (9167ea23); real-driver Runtime rig (141e4412); L4 harness + evidence A1-L4.md (3c2cf96a).
  • In progress: final gates (see "Drivers — gates").
  • Next: reviewer sign-off; Galaxy / Heidenhain L4 legs when their rigs are reachable.

Progress log (resume from here)

  • Done: IAlarmInitialStateSignal (Abstractions); NM condition state in the partial OtOpcUaNodeManager.ConditionState.cs + record types ConditionStateRecords.cs (6836efae, tests ConditionStateNodeManagerTests 12/12 incl. parity (a)–(g), T1, T3, MaxConditions); ConditionStateHub + DI + hosted-service wiring (923c2511, ConditionStateHubTests 5/5 incl. falsely-empty). OpcUaPublishActor.MarkConditionsKnown + G3 (d64578b1, OpcUaPublishActorConditionKnownTests 5/5); driver actors: signal forward, routing, OpcUaClient backstop, F5 timeout (DriverHostActor.ConditionSignals.cs, ConditionSignalOptions), tests + reusable rig NativeAlarmSignalTestBase/FakeSignallingAlarmDriver (47bf3a1c, NativeAlarmInitialStateSignalTests 6/6). Scripted OnInputsEstablished engine → host (a2486167, ScriptedAlarmEngineInputsEstablishedTests 4/4, ScriptedAlarmHostInputsEstablishedTests 2/2); manifest key A1 (81ebdf4f).
  • Gates passed (see "Gates"). The A1 core part is complete on this branch.
  • Next (other agents): the six real drivers (seams below); placements / condition_key / c1. ids (parallel agent); A2 wire. L4 calibration is not run here.

Decisions and deviations (each with a reason)

  • MarkConditionsKnown takes a realm ((source, conditionIds, realm)): NM keys are realm-qualified; native = Raw/RawPath, scripted = Uns/ScriptedAlarmId. A sibling MarkConditionsUnknown exists because the plan's test "an input reverting to never-pushed makes the scripted condition unknown again" needs a way back to unknown.

  • The sink members are default interface methods (like CompleteAddressSpaceApply) so the ~20 test fakes compile; DeferredAddressSpaceSink/SdkAddressSpaceSink/NullOpcUaAddressSpaceSink implement them (the reflection forwarding guard covers the deferred one automatically).

  • Hub types live in OpcUaServer (IConditionStateSink, ConditionStateRecord, ConditionSnapshotSlice) because Runtime references OpcUaServer, not the reverse; the hub implementation is Runtime/DataConnections/ConditionStateHub.cs.

  • Overflow = per-reader reset, not a whole-partition epoch bump. A full partition evicts its oldest record and raises its floor; only a reader whose cursor is below the floor gets ResetRequired. Same guarantee as the plan's epoch invalidation, without resetting caught-up readers. Versions are global (one counter), so a slice watermark orders deltas for every condition in it.

  • Snapshot slices by key order, not by hub partition: keys are enumerated + filtered OFF Lock, then copied in ≤ MaxConditions slices, each with its own watermark under the same hold. Consumers must register for deltas BEFORE snapshotting (A2) so a condition created after enumeration arrives as its materialise delta.

  • A rebuild does not emit removal records for conditions that come back. Removal records for conditions the rebuild dropped for good are emitted at CompleteAddressSpaceApply (otherwise a consumer would retire an active alarm mid-rebuild — a T2 violation).

  • Carry-over carries the known flag, not "known = true": a native condition that was unknown before the rebuild stays unknown after it (no falsely-normal known). Plan text says "carried-over state is known".

  • Activation marker: incarnation = a GUID per node-manager lifetime (ConditionIncarnation); the materialise record does not advance the basis, and scripted conditions keep their basis across a rebuild (_rebuildScriptedActivation) so the engine's re-assert of a still-active alarm is not a new occurrence; native ones ride NativeConditionCarryOver (+ActivationSequence/Active/Acked, StateKnown) per the plan.

  • snapshot_complete readiness = ConditionStateHub.IsSnapshotComplete = NM apply complete (false at boot and from RebuildAddressSpace until CompleteAddressSpaceApply) AND IDriverPrimaryRoleSource.ShouldActAsPrimary.

  • AlarmStateUpdate gained an optional Source (driver id / OpcUaPublishActor.ScriptedSource) so G3 can discard exactly the source that lost a projection. An unattributed loss (null source, e.g. the #760 ack-revert write) discards every deferred mark — conservative. A deferred QUALITY drop does not discard marks.

  • Live + deferred: like AlarmStateUpdate, a mark received during a plan is applied live (to the old nodes) AND deferred; the deferred copy replays after every deferred alarm/quality.

  • F5 window starts at each ConnectivityChanged(Connected) edge and covers every alarm ref the driver owns at that instant (_alarmRefsByDriver); a Bad edge cancels the F5 and backstop timers. Conditions added by a later deploy while connected are not covered by F5 until the next Good edge (they still become known on the next signal). Diagnostic cleared when a signal empties the pending set, or the driver is removed.

  • Backstop applies only to driver type OpcUaClient (ConditionKnownSettle:OpcUaClient, default 60 s); an Unsignalable report from any other type is logged and ignored (the conditions stay unknown).

  • Scripted flips are one event with a flag — ScriptedAlarmEngine.OnInputsEstablished(ScriptedAlarmInputsEventArgs (AlarmId, Established)); Established=false is the "input reverted to never-pushed" withdrawal. Queued "last in pending" by subclassing the per-call pending list (PendingEmissions) and firing its flips after every emission (FirePending), so no evaluation signature changed. LoadAsync clears the engine's established set, so every reload re-raises the flip for every established alarm — that is how scripted conditions become known again after a rebuild re-created them unknown.

  • The scripted host holds flips during a load until OnAlarmsLoaded has queued the post-load re-assert of non-normal conditions; otherwise the flip LoadAsync fires before its pipe-back would mark a freshly re-materialised (inactive) node known ahead of the re-assert of its persisted active state — a falsely-normal known. Held flips are dropped by a newer ApplyScriptedAlarms (that load re-raises them). Residual: a flip from a superseded load that is raised after the newer apply arrives is held and flushed with the newer load (rare; at worst it re-marks an alarm the newer load also established).

  • A flip is raised on "established" whenever no input is never-pushed, even when an input is pushed-but-Bad (the engine then holds its prior state; the consumer sees Quality Bad). That is the plan's predicate.

Seams for the driver agent (ii, iii, vi, vii, viii, ix)

  • Interface: src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/IAlarmInitialStateSignal.cs — event EventHandler<AlarmInitialStateEventArgs> InitialAlarmStateDelivered; args (IReadOnlyList<string> ConditionIds, bool Unsignalable = false). Raise it synchronously on the OnAlarmEvent thread/path, after the last event it covers, only while an alarm subscription is live, with ConditionIds = the RawPaths it established. OpcUaClient without ConditionRefresh raises it once with Unsignalable: true (backstop applies).
  • Nothing else to wire per driver: DriverInstanceActor.AttachAlarmSource/DetachAlarmSource attach the signal with the alarm handler for any IAlarmSource that also implements IAlarmInitialStateSignal; DriverHostActor routes it (DriverHostActor.ConditionSignals.cs).
  • Hooks (plan §5.1 table): Galaxy GatewayGalaxyAlarmFeed.Dispatch sentinel (:168) → GalaxyDriver re-raises; OpcUaClient RefreshEndEventType route (OpcUaClientDriver.cs:3066) + SequentialPublishing = true on the alarm subscription (:2445); FOCAS FocasAlarmProjection.PollOnceAsync after Tick per host (:274); AbCip AbCipAlarmProjection.Tick end (:195); Heidenhain HeidenhainAlarmProjection.OnWalk Good status (:214); MTConnect resync emission (MTConnectDriver.Alarms.cs:117).
  • Test helper: tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/NativeAlarmSignalTestBase.cs — inherit it; StartRig(driverType, alarmTags, configure?, driver?) deploys the tags on one enabled driver (any IDriver via the driver param once the class is generalised; today a FakeSignallingAlarmDriver), returns Rig(Host, Publish probe, Driver, Hub); CollectAlarmTraffic (ordered AlarmStateUpdate/MarkConditionsKnown), AssertNoMark, RawPathOf(tag). FakeSignallingAlarmDriver obeys G5 (Raise/Signal are no-ops while unsubscribed), ReplaySnapshot = Galaxy-shaped snapshot + sentinel, SubscribeDelay holds the DriverInstanceActor mailbox (F2), OnSubscribed = post-subscribe replay. To drive a REAL driver through the rig, widen StartRig's driver parameter from FakeSignallingAlarmDriver to IDriver and drop the Subscribed wait.
  • Config: DataConnections:ConditionKnownSignalTimeout:<DriverType> (s or TimeSpan; default 120 s), DataConnections:ConditionKnownSettle:OpcUaClient (default 60 s) — ConditionSignalOptions; tests use WithSignalTimeout / WithOpcUaClientSettle.

Tests (A1 manifest key)

Test What it pins
O ConditionStateNodeManagerTests (12) parity (a) cold start, (b) Warm standby → promotion, (c) rebuild carry-over (known at once, same marker, never-known stays unknown, no removal record for a returning condition, removal for a dropped one), (d) SDK-applied native ack through the real Acknowledge.OnCall wrapper, (e) ConditionClass-only (state-only record, no event), (f) ack-revert (+ F4 marker bump), (g) quality-only — each asserted as "delta stream folded == fresh node snapshot"; T1 (state-only known record after the cut, negative + positive control, repeat no-op); MarkConditionsUnknown; T3 marker edges; scripted marker kept across a rebuild re-assert; structural MaxConditions: 25 conditions, max 10 ⇒ holds [10,10,5], Lock not held at the hook, a delta between holds lands inside slice 2 / after slice 1's watermark
R ConditionStateHubTests (5) global versions, per-reader overflow reset, snapshot_complete = apply complete ∧ Primary, F5 diagnostic, falsely-empty (real NM + hub: not complete until CompleteAddressSpaceApply; no known-inactive record for a standing alarm before its projection)
R OpcUaPublishActorConditionKnownTests (5) live order; F2 during a held plan (mark replayed after the alarm); G3 overflow (mark discarded, next signal marks) and out-of-scope skip (only that source's mark discarded); withdrawal → MarkConditionsUnknown
R NativeAlarmInitialStateSignalTests (6) real DriverInstanceActor + DriverHostActor + fake driver: known only on the signal, after the projection; (iv) Galaxy-shaped, DriverInstanceActor delayed 800 ms ⇒ mark still last; (v) F5 (no mark, diagnostic, late signal clears); OpcUaClient backstop; no backstop for other types; (xi) G5
S ScriptedAlarmEngineInputsEstablishedTests (4) (i) late input ⇒ no flip before the first real evaluation, flip after its Activated; seeded at load; reverting to never-pushed ⇒ unknown again, re-established on a value; reload re-raises
R ScriptedAlarmHostInputsEstablishedTests (2) (iv) scripted: mark after the Active projection; a reload holds the mark until after the re-assert

Mutation (red/green) checks, each restored after the red run:

Mutation Red
NM: no record in ReportConditionEvent, no state-only record in WriteAlarmCondition 7 of 12 ConditionStateNodeManagerTests (b, d, e, f, g, T3, MaxConditions)
Publish actor: SourceLost always false (no G3 discard) both G3 tests
DriverInstanceActor: signal forwarded straight from the driver thread to the parent (bypassing the mailbox) F2-delayed and G5 order tests
Engine: flips fired BEFORE the pending emissions (i) and seeded-at-load tests
Scripted host: flips never held during a load reload-holds-the-mark test

Gates

Run one at a time on this branch after the last code commit:

Gate Result
dotnet build ZB.MOM.WW.OtOpcUa.slnx 0 errors / 0 warnings
run-unit-phase.py A1 (OpcUaServer 24, Runtime 94, ScriptedAlarms 56, Commons 20) passed
run-unit-phase.py H4 / H3 / H2 / H1 / X0 all passed
Runtime.Tests (Category!=E2E&Category!=LiveIntegration) 1933 passed, 3 skipped, 0 failed
OpcUaServer.Tests (same filter) 1432 passed, 1 skipped, 0 failed
Core.ScriptedAlarms.Tests 122 passed
Commons.Tests 505 passed

The first full Runtime run found one regression in a test, not in production: ScriptedAlarmHostActorRestartTests .An_alarm_command_whose_store_hangs_is_bounded_and_the_mailbox_moves_on used strict ExpectMsg on the publish probe and now also receives the new MarkConditionsKnown that follows the first projection. That test now ignores the mark.

Open questions

  • Serving incarnation for the activation marker is a GUID per node-manager lifetime. A2 may want the serving incarnation that the data-connection Serving already carries. That would be a one-line ConditionIncarnation setter.
  • The F5 window ignores conditions added by a deploy while the driver is connected until the next Good edge. They still become known on the next signal. Should a deploy re-arm F5 for the added refs?
  • MaxConditions per hold is a parameter (default 1,000). A2 should pass the mapping's configured MaxConditions.
  • The hub never pushes; readers poll Watermark/Read. A2 decides on a wake signal. It must not run under the node manager's Lock.

Drivers (the six native sources, T2 (ii)/(iii)/(vi)/(vii)/(viii)/(ix), L4)

Hook points (plan §5.1 table)

Every driver raises the signal synchronously on the same thread and path as its OnAlarmEvent, after the events it covers. It is raised under the same lock and the same handler/subscription gate as those events (G5). ConditionIds are the RawPaths the completed read established (G1).

Driver Hook Covers G5 gate
Galaxy GatewayGalaxyAlarmFeed.Dispatch, SnapshotComplete case → new feed event IGalaxyAlarmFeed.SnapshotDelivered (default no-op accessors, so test fakes compile), raised on every sentinel including each reopened stream's; GalaxyDriver.OnAlarmFeedSnapshotDelivered re-raises it the live subscription's refs (_alarmSubscriptionRefs, replaced with the single handle in SubscribeAlarmsAsync) no live handle ⇒ nothing
OpcUaClient RouteAlarmEvent: IsRefreshEnd(fields) is checked before projection, under _alarmStateLock; SequentialPublishing = true on the alarm subscription (options now built by BuildAlarmSubscriptionOptions); TryConditionRefreshAsync's "unsupported" catch → ReportRefreshUnsignalable ⇒ Unsignalable: true that subscription's RemoteAlarmSubscription.AlarmRefs (the RawPaths of its source index) handle not in _alarmSubscriptions ⇒ nothing
FOCAS FocasAlarmProjection.Tick end (reached only after NoteAlarmReadSucceeded(host); TickFailed raises nothing) that host's subscribed ALARM: tags superseded subscription or no OnAlarmEvent handler ⇒ nothing
AbCip AbCipAlarmProjection.Tick end ALMD nodes whose InAlarm read Good; ALMA nodes whose every plan ref read Good subscription no longer the registered one in _subs ⇒ nothing
Heidenhain HeidenhainAlarmProjection.OnWalk, after the Good-walk diff (new optional ctor arg initialState) that host's subscribed ALARM: tags no current subscription or no handler ⇒ nothing; a non-Good walk returns before it
MTConnect EmitConditionTransitions, after the events of a full emission (touchedDataItemIds == null: subscribe resync, the restarted pump's first act, comms-loss recovery) or of a /current re-baseline (baselineRead, from ApplyAndFanOut(..., baseline: true)), only over a tracker with HasBaseline (new, set by Apply(baseline: true), reset by Clear) subscribed conditions with a known, non-Unavailable level no subscription or no handler ⇒ nothing

Tests (A1 manifest: one entry per driver test project, filter (Feature=GrpcData&Phase=A1))

Test Pins Mutation (red, then restored)
GalaxyInitialAlarmStateSignalTests (4) real GatewayGalaxyAlarmFeed over test streams: (ii) snapshot events then the signal; no signal before the sentinel; (xi) a sentinel while unsubscribed raises nothing; (vii) a reopened stream re-signals, and a deploy-added ref (re-subscribe) is covered by the NEXT sentinel, not by the subscribe G5 check removed + a fallback ref ⇒ the G5 test is red
OpcUaClientInitialAlarmStateSignalTests (5) (iii) F1: the refresh "returned" with nothing signalled, refreshed event, then RefreshEnd ⇒ signal last; released subscription ⇒ nothing; (vi) unsupported refresh ⇒ Unsignalable with the refs; (ix) config pin SequentialPublishing; (ix) G2 through the real SDK Subscription (worker started via StartKeepAliveTimer, messages fed to SaveMessageInCache by reflection): seq 2 (RefreshEnd) arrives 300 ms before seq 1 (the refreshed Active event) ⇒ delivered 1, 2 SequentialPublishing = false ⇒ both the pin and the SDK out-of-order test are red (before the 300 ms gap was added the SDK test was green on the mutation, so it was not discriminating)
FocasInitialAlarmStateSignalTests (3) real poll loop: (ii) Raise then signal covering the device; (viii) G1 two CNCs, one failing ⇒ every signal names only the reachable one; (xi) no handler ⇒ no signal signal over sub.References instead of the device's tags ⇒ G1 test red
AbCipInitialAlarmStateSignalTests (4) real ALMD poll loop over fake runtimes: (ii); (viii) G1 two controllers, B's reads throw ⇒ only A; (xi) an unregistered subscription's tick and a released subscription ⇒ nothing establish before the Good check + drop the live gate ⇒ the G1 and stale tests are red
HeidenhainInitialAlarmStateSignalTests (3) OnWalk per host: (ii); (viii) G1 host 2 failing ⇒ only host 1, then host 2 signals once Good; (xi) no handler / unsubscribed ⇒ nothing signal over all subscribed tags ⇒ G1 test red
MTConnectInitialAlarmStateSignalTests (4) (ii) standing Fault in /current ⇒ Raise then signal, an unobserved condition excluded; Unavailable excluded; a /sample delta does not signal, an Agent-restart re-baseline does; (xi) no handler ⇒ nothing Unavailable check removed ⇒ the Unavailable test is red
R RealDriverInitialStateSignalTests (2) the real FocasDriver through the real DriverHostActor + DriverInstanceActor (StartRig(IDriver, …)): (ii) the Active AlarmStateUpdate precedes the MarkConditionsKnown; (viii) unreachable CNC B is never marked, F5 diagnostic counts B alone (1), A stays known FOCAS signals before its events ⇒ (ii) red

NativeAlarmSignalTestBase.StartRig gained an IDriver overload ((Host, Publish, Hub) + an optional readiness predicate). The fake-driver overload delegates to it, so the existing tests are unchanged.

L4

See A1-L4.md. The measured p99 values, from quality Good, are:

  • OpcUaClient: 0.64 s (1.37 s with connect);
  • FOCAS: 0.26 s;
  • MTConnect: about 0 s (0.12 s with connect);
  • AbCip: 1.0 s, on a private same-image ab_server, because the shared fixture has no ALMD.

ConditionKnownSignalTimeout stays at 120 s for every type, which is at least 29× the measured p99. The Galaxy and Heidenhain legs are blocked: Galaxy needs the VPN and mxaccessgw, and Heidenhain has no fixture.

Deviations (each with a reason)

  • Galaxy covers the subscription's refs, not "every condition of the feed". The feed is unfiltered, but the host routes only the subscribed RawPaths, so the subscribed set is exactly what a sentinel establishes on this driver.
  • Galaxy: a subscribe never signals by itself. A condition added by a deploy while the stream is open waits for the next sentinel, which comes only on a stream reopen. Until then F5 diagnoses it.
    • This is by design (vii): the snapshot that preceded the subscribe may have carried that alarm while it was unroutable.
    • Open question: should the driver ask the gateway for a fresh snapshot on a changed subscription set?
  • OpcUaClient: no signal suppression on an SDK-reported sequence gap during a refresh. Plan G2 says such a RefreshEnd "does not signal".
    • The SDK 2.0.1 surface the driver sees (the per-item Notification callback) exposes no per-message gap or republish failure, so this was not implemented.
    • With SequentialPublishing the worker waits for the missing sequence number (republish) before delivering later ones.
    • Residual: a gap the SDK gives up on could let a RefreshEnd signal over a lost refreshed event. Logged here as an open question for the reviewer.
  • MTConnect also signals on a mid-stream /current re-baseline (OUT_OF_RANGE / Agent restart), not only on the subscribe resync and the pump's first act. A re-baseline is a complete re-read, and without the signal a restarted Agent's conditions would wait for the next reconnect.
  • MTConnect never signals a condition with no observation at all (tracker.Get == null), as well as excluding Unavailable. Never observed is not established.
  • AbCip G5 is "still the registered subscription", because AbCip delivers events with no handler gate. A tick racing an unsubscribe raises nothing.
  • The OpcUaClient (vi) test uses a seam (ReportRefreshUnsupportedForTest) instead of a server that refuses ConditionRefresh. The catch → ReportRefreshUnsignalable wiring itself is covered only by review.
  • The Runtime end-to-end rig uses FOCAS only. Galaxy's InitializeAsync with injected seams also starts its deploy watcher and platform seed, so the other drivers are covered at driver level, where the ordering contract lives.