# 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`. ## 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`). - **In progress:** gates (see "Gates"). - **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 InitialAlarmStateDelivered`; args `(IReadOnlyList 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:` (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 (filled below) ## Open questions (none yet)