Compare commits

...

9 Commits

Author SHA1 Message Date
Joseph Doherty be703a3026 chore(plan): mark FOCAS/Wonderware/AbCip phase tasks complete
v2-ci / build (push) Failing after 48s
v2-ci / unit-tests (tests/Core/ZB.MOM.WW.OtOpcUa.Cluster.Tests) (push) Has been skipped
v2-ci / unit-tests (tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests) (push) Has been skipped
v2-ci / unit-tests (tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests) (push) Has been skipped
v2-ci / unit-tests (tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests) (push) Has been skipped
v2-ci / unit-tests (tests/Server/ZB.MOM.WW.OtOpcUa.Security.Tests) (push) Has been skipped
v2-ci / integration (tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests) (push) Has been skipped
v2-ci / integration (tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests) (push) Has been skipped
2026-06-18 12:48:52 -04:00
Joseph Doherty 4022457000 test(focas): integration test for cnc_getfigure position scaling via focas-mock 2026-06-18 12:44:35 -04:00
Joseph Doherty c8ab8fc348 test(abcip): Emulate-tier nested-UDT live-gate smoke + docs (backlog #6)
Add AbCipEmulateNestedUdtTests (skip-gated, AB_SERVER_PROFILE=emulate) to close
the live-gate gap for nested-struct UDT discovery via CIP Template Object (class 0x6C)
threaded by commits 3d8ce4e8/d203f31c. Compiles + skips cleanly against ab_server
(no CIP Template Object service). Update docs/drivers/AbCip.md nested-struct section
to record the shipped decode path, the Emulate-only live-gate, and offline unit coverage.
2026-06-18 12:40:04 -04:00
Joseph Doherty 70aad3ef48 test(historian): cover PerEventStatus length-mismatch fallback + Retry status mapping 2026-06-18 12:37:31 -04:00
Joseph Doherty e5f568d01f docs(focas): retire stale 'wire backend returns no figures' comments after cnc_getfigure shipped 2026-06-18 12:32:55 -04:00
Joseph Doherty feddc2b80e feat(historian): emit PermanentFail for poison alarm events via additive PerEventStatus sidecar IPC field 2026-06-18 12:30:14 -04:00
Joseph Doherty f320f323ae feat(focas): add cnc_getfigure wire command + focas-mock handler 2026-06-18 12:23:14 -04:00
Joseph Doherty e5b1a5574a docs(plan): implementation plan + tasks for FOCAS/Wonderware/AbCip backlog phase 2026-06-18 12:19:45 -04:00
Joseph Doherty a687821f79 docs(plan): design for FOCAS cnc_getfigure + Wonderware poison-event status + AbCip nested-UDT live-gate 2026-06-18 12:17:13 -04:00
19 changed files with 1143 additions and 47 deletions
+17 -7
View File
@@ -132,13 +132,23 @@ Variables — in addition to the UDT container tag itself.
separate Variable node under the UDT's `Discovered/` sub-folder, addressable by its member
path (e.g. `MyUdt.Temperature`, `MyUdt.Flags`). Top-level atomic member discovery is
**functional in production**.
- **Nested struct members** — when a UDT member is itself a struct, the driver walks into it up
to a **depth cap of 8 levels**. Nested-struct expansion is a **documented deferral in
production**: the Template Object member block carries no nested template ID, so the
sub-shape cannot be re-fetched from the controller at discovery time. Nested struct leaves are
never mis-emitted — they are simply dropped (the parent member is omitted from discovery if it
is not atomic and its sub-shape is unavailable). Use pre-declared `Members` for nested structs
that must be individually addressed.
- **Nested struct members** — **shipped** (commits 3d8ce4e8 / d203f31c). When a UDT member is
itself a struct, the Template Object member block carries the nested UDT's template instance ID
in the low 12 bits of the member `info` field (struct flag `0x8000` set). The driver captures
this as `AbCipUdtMember.NestedTemplateId` and threads it into a second `FetchUdtShapeAsync`
call (`@udt/{id}`) so the nested struct's atomic leaves are expanded into dot-joined addressable
paths (e.g. `Motor1.Status.Code`, `Motor1.Status.Running`). Recursion is bounded by a
**depth cap of 8 levels**; members at or beyond the cap are dropped rather than emitted.
Nested struct leaves that resolve to no emittable atomic leaf produce no sub-folder (lazy
materialisation).
**Live verification is Emulate-tier only** (`AB_SERVER_PROFILE=emulate` + a Logix Emulate
instance): `ab_server` (the default Docker simulator) does not implement the CIP Template
Object service (class 0x6C), so the nested-id fetch cannot be exercised against it.
See `tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbCip.IntegrationTests/Emulate/AbCipEmulateNestedUdtTests.cs`
for the skip-gated live-gate smoke (backlog #6). Offline unit coverage lives in
`AbCipDriverDiscoveryTests.Controller_discovered_UDT_nested_struct_expands_via_nested_template_id_fetch_no_seam`
and `CipTemplateObjectDecoderTests`.
### Bare-container reads
@@ -0,0 +1,182 @@
# FOCAS cnc_getfigure + Wonderware poison-event status + AbCip nested-UDT live-gate — Design
**Date:** 2026-06-18
**Branch:** `feat/focas-figure-ww-poison-abcip-gate` (off master `274ba2b1`)
**Backlog items:** `stillpending.md` §A #3 (FOCAS `cnc_getfigure`), #5 (Wonderware poison-event sidecar wire), #6 (AbCip nested-struct prod live-gate)
Three independent backlog items bundled into one phase. They touch disjoint projects
(Driver.FOCAS + its python sim / Driver.Historian.Wonderware{,.Client} + Core.AlarmHistorian /
Driver.AbCip.IntegrationTests + docs), so they are independently implementable and parallelizable.
---
## Standing constraints (in force)
- **NO Commons wire/proto contract change**, NO Core.Abstractions / breaking interface contract change,
NO EF migration, NO bUnit (Razor proven only by live `/run` — N/A this phase, no Razor touched).
- Stage by explicit path, never `git add .`; never stage the never-stage files (`sql_login.txt`,
`src/Server/.../Host/pki/`, `pending.md`, `current.md`, `stillpending.md`, `docker-dev/docker-compose.yml`).
- No force-push, no `--no-verify`. Never echo/commit secrets. Finish = merge to master + push.
- `dangerouslyDisableSandbox: true` for all build/test/rig commands.
---
## Component A — FOCAS `cnc_getfigure` wire command (backlog #3)
### The finding that makes this safe
`WireFocasClient` (the pure-managed FOCAS/2 Ethernet client) is the **production path to real CNCs**
(not the Fwlib P/Invoke path). Its `GetPositionFiguresAsync` is a hard-coded empty-list stub
(`Wire/WireFocasClient.cs:287-297`). The consumer wraps it in a graceful probe:
```csharp
// FocasDriver.cs:662
state.PositionFigures = await SafeProbe(() => client.GetPositionFiguresAsync(ct), []);
```
and `AxisFactor` (`FocasDriver.cs:~853`) uses a per-axis figure **only when present and ≥ 0**, else falls
back to the `PositionDecimalPlaces` config knob. So a wire command that errors or returns empty degrades to
**exactly today's behavior** — implementing it is monotonic and cannot regress real hardware.
The `.NET FocasWireClient` and the python `focas_mock` (`tests/.../FOCAS.IntegrationTests/Docker/focas-mock/`)
speak a **co-designed, internally-consistent** wire protocol: the mock dispatches on command codes in
`server.py:_wire_payload` (0x56=servo-meter, 0x26=axis position, 0x89=axis names, 0x120=timer, …). The
protocol is validated **against the sim**, not against real Fanuc hardware — that validation is bench-CNC-gated
for the *entire* wire backend (`docs/v2/implementation/focas-wire-protocol.md`), not unique to this command.
### Approach (driver-internal + sim; NO interface change — `IFocasClient.GetPositionFiguresAsync` already exists)
1. **`FocasWireClient.ReadPositionFiguresAsync(...)`** — mirror `ReadServoMeterAsync` (`FocasWireClient.cs:351-386`):
send the figure request **paired with the axis-name request (`0x0089`)** so figures align positionally to
axes (exactly how servo-meter pairs `0x0056`+`0x0089`). Pick a wire command id **currently unused by both
the client and the mock** (the mock uses 0x0E/0x10/0x15/0x16/0x18/0x19/0x1A/0x1C/0x1D/0x23/0x24/0x25/0x26/
0x35/0x40/0x56/0x57/0x89/0x8A/0x98/0xE1/0xFC/0x120/0x8001/0x8002 — choose a clearly-unused code, e.g. `0x00D3`,
and document it as sim-consistent / bench-CNC-unvalidated). Response payload = per-axis `short dec`
(decimal-place count); parse into `IReadOnlyList<int>`. `rc != 0` → empty list (graceful).
2. **`WireFocasClient.GetPositionFiguresAsync`** — replace the stub: call the new client method, return its list;
any failure path returns empty (never throws — the `SafeProbe` + per-axis fallback contract is preserved).
Rewrite the now-stale `<returns>` doc.
3. **`focas_mock`** — add a `cnc_getfigure` admin/handler entry + a `_wire_payload` branch for the chosen code
returning per-axis `short dec` from a **new data-store key `position_figures`** (default **0 per axis** →
`10^0 = 1.0` factor → no scaling → every existing integration assertion preserved). Register the method name
in `constants.py:IMPLEMENTED_FOCAS_METHODS` + the server handler map + profile `exports` as needed.
### Testing
- **Driver consumption is already covered offline** by `FocasPositionAutoScaleTests` (FakeFocasClient returns
figures → asserts scaled vs. fallback). No change needed there.
- **New end-to-end proof** = a skip-gated integration test in `Series/WireBackendCoverageTests.cs` (the
established pattern, `[Collection(FocasSimCollection.Name)]` + `if (_fx.SkipReason is not null) Assert.Skip(...)`):
`mock_patch` non-zero `position_figures`, init the wire-backed `FocasDriver`, assert the published
`AbsolutePosition` is the **scaled** value (raw ÷ 10^dec), not the raw integer.
- **Live `/run` for A** = bring the focas-mock up locally on the Mac
(`docker compose -f tests/.../FOCAS.IntegrationTests/Docker/docker-compose.yml up -d --build`) and run the
FOCAS integration suite; the new test executes (does not skip) and passes.
### Honest boundary (documented, not built)
Real-Fanuc validation of the chosen wire code/payload stays bench-CNC-gated — same status as the whole wire
backend. Worst case on real hardware = graceful fallback to the config knob (i.e. no regression).
---
## Component B — Wonderware poison-event per-event status (backlog #5)
### The finding that shapes it
The sidecar IPC reply `WriteAlarmEventsReply.PerEventOk` is a `bool[]` on **both** ends — which are **both in
this repo** (`...Wonderware.Client/Ipc/Contracts.cs` + `...Wonderware/Ipc/Contracts.cs`, MessagePack over TCP;
**not** a Commons proto). The client (`WonderwareHistorianClient.WriteBatchAsync:340-369`) can therefore only
produce `Ack`/`RetryPlease`, never `PermanentFail`, so a poison event loops to the retry cap instead of
dead-lettering immediately. The `HistorianWriteOutcome` enum **already has `PermanentFail`** and the sink
(`SqliteStoreAndForwardSink.cs:456-465`) **already dead-letters it immediately**. The sidecar writer seam
`IAlarmEventWriter.WriteAsync` returns only `bool[]` and its sole real impl is the **infra-gated**
`AahClientManagedAlarmEventWriter` (AAH SDK).
### Approach (additive IPC field + sidecar classifier; NO `IAlarmEventWriter` change, NO Commons)
1. **Additive wire field (both Contracts.cs):** add `[Key(4)] byte[] PerEventStatus` to `WriteAlarmEventsReply`
(0=Ack, 1=Retry, 2=Permanent). **Keep `PerEventOk [Key(3)]`** populated for rolling-deploy back-compat
(new client ↔ old sidecar: empty Key(4) → fall back to PerEventOk; old client ↔ new sidecar: ignores Key(4)).
2. **Sidecar `HistorianFrameHandler.HandleWriteAlarmEventsAsync`:** add a pure `ClassifyEvents(events)` step —
an event that is **structurally malformed** (empty `SourceName`, empty `AlarmType`, or `EventTimeUtcTicks <= 0`)
can never persist → mark **Permanent** and **exclude it from the writer batch** (mirrors the client's existing
corrupt-row exclusion). Remaining events go to the writer; `true`→Ack, `false`→Retry. Populate **both**
`PerEventOk` (Ack→true else false) and `PerEventStatus`.
3. **Client `WriteBatchAsync`:** when `reply.PerEventStatus.Length == batch.Count`, map 0/1/2 →
`Ack`/`RetryPlease`/`PermanentFail`; else fall back to the existing `PerEventOk` path. Rewrite the stale
`<remarks>` + inline "PermanentFail is never emitted" comments.
### Testing (fully offline — no rig)
- Sidecar: pure `ClassifyEvents` unit test (malformed → Permanent + excluded; valid → delegated; writer
false → Retry).
- Client: a `FakeSidecarServer` reply with `PerEventStatus=[2]` → `WriteBatchAsync` returns `PermanentFail`;
a reply with empty `PerEventStatus` → falls back to `PerEventOk` (back-compat).
- End-to-end sink: an existing `SqliteStoreAndForwardSink` test already proves `PermanentFail` → immediate
dead-letter; add/confirm a test that a Permanent classification dead-letters on the **first** drain (vs. the
retry-cap path the finding-002 regression test covers).
### Honest boundary (documented)
SDK-**semantic** permanent rejections (a structurally-valid event the AAH SDK rejects, e.g. unknown tag) still
map to Retry→cap until the infra-gated `AahClientManagedAlarmEventWriter` surfaces richer per-event status — a
noted follow-up. This phase closes the **structurally-malformed (poison)** case the finding describes.
---
## Component C — AbCip nested-struct live-gate (backlog #6)
### Verdict (from the feasibility pass)
A **local** live-gate is architecturally impossible: `ab_server` (the libplctag CIP sim used by the default
`abserver` tier) does **not** implement the CIP Template Object service (class 0x6C) that nested-UDT discovery
depends on. The decode + threading already **shipped** (`3d8ce4e8`/`d203f31c`; `AbCipUdtMember.NestedTemplateId`
→ existing `@udt/{id}` fetch) and 301 offline tests pass. The honest close formalizes the gate at the existing
**Emulate** fidelity tier (Logix Emulate / real ControlLogix).
### Approach (skip-gated test + docs; NO runtime change)
1. **New `AbCipEmulateNestedUdtTests`** (mirror `AbCipEmulateUdtReadTests` + `AbServerProfileGate.SkipUnless(Emulate)`):
drives `FocasDriver`-equivalent AbCip discovery against a nested-UDT-bearing Emulate project and asserts the
nested struct's atomic leaves are addressable (`Parent.Status.Code`, `Parent.Status.Running`) + the nested
sub-folder materializes. Skips cleanly on the default `abserver` tier (which can't serve Template Object).
2. **`docs/drivers/AbCip.md`** — document nested-struct support as **Emulate-tier verified** (ab_server lacks
CIP Template Object), referencing the new test + the existing offline unit coverage.
### Testing
The Emulate test **compiles and skips** locally (no Logix Emulate on this Mac) — proving it is wired into the
suite. The decode/threading risk is already pinned by the shipped offline unit tests
(`CipTemplateObjectDecoderTests` + `AbCipDriverDiscoveryTests`).
---
## Component D — Reconcile + finish
- `stillpending.md` (never-staged): mark #3 (FOCAS wire command shipped + sim-proven), #5 (Wonderware
poison-event structurally-malformed close + the SDK-semantic follow-up boundary), #6 (AbCip live-gate
formalized as the Emulate skip-gated test).
- Update memory (`project_stillpending_backlog.md` + `MEMORY.md` index line).
- Build clean + targeted tests green (FOCAS + Wonderware + AbCip) + Component A live `/run` (focas-mock) +
merge to master + push.
---
## Task slicing (independent → parallelizable)
| Task | Component | Project(s) | Class | Parallel with |
|---|---|---|---|---|
| T1 | FOCAS wire `cnc_getfigure` (client method + stub wire-in + mock handler) | Driver.FOCAS + focas-mock (py) | standard | T2, T3 |
| T2 | Wonderware per-event status (DTO ×2 + sidecar classifier + client consume + tests) | Wonderware{,.Client} + Core.AlarmHistorian.Tests | standard | T1, T3 |
| T3 | AbCip Emulate nested-UDT skip-gated test + AbCip.md | AbCip.IntegrationTests + docs | small | T1, T2 |
| T4 | FOCAS integration test (mock) + live `/run` verify | FOCAS.IntegrationTests | small | none (after T1) |
| T5 | Reconcile stillpending #3/#5/#6 + memory + finish (build, tests, merge+push) | docs (never-staged) | small | none |
Parallel implementers use **worktree isolation** (the shared-tree git-race lesson) since T1/T2/T3 touch disjoint
projects. T4 depends on T1; T5 runs last.
## Done =
Build clean + `dotnet test` green (Driver.FOCAS + Wonderware client/sink + AbCip) + Component A live `/run`
(focas-mock integration test executes & passes) + Components B/C offline-proven + merged to master + pushed.
@@ -0,0 +1,142 @@
# FOCAS cnc_getfigure + Wonderware poison-event status + AbCip nested-UDT live-gate — Implementation Plan
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers-extended-cc:subagent-driven-development to implement this plan task-by-task.
**Goal:** Close three backlog items — FOCAS `cnc_getfigure` wire command (#3), Wonderware poison-event per-event status (#5), AbCip nested-UDT Emulate-tier live-gate (#6).
**Architecture:** Three disjoint-project components. A: a new FOCAS/2 wire command in `FocasWireClient` + matching `focas_mock` handler, wiring the `WireFocasClient` stub. B: an additive `[Key(4)] PerEventStatus` field on the in-repo Wonderware sidecar IPC reply + a sidecar structural-malformed classifier + client consumption. C: a skip-gated Emulate-tier AbCip nested-UDT integration test + docs.
**Tech Stack:** .NET 10 (FOCAS, AbCip) / .NET 4.8 sidecar (Wonderware), MessagePack IPC, python focas-mock, xUnit + Shouldly.
**Design:** `docs/plans/2026-06-18-focas-figure-ww-poison-abcip-gate-design.md` (committed `a687821f`).
**Standing constraints:** NO Commons/proto change · NO Core.Abstractions/breaking-interface change (the sidecar `IAlarmEventWriter` is NOT touched) · NO EF migration · NO bUnit · stage by explicit path (never `git add .`) · never stage `sql_login.txt`/`pki/`/`pending.md`/`current.md`/`stillpending.md`/`docker-dev/docker-compose.yml` · never echo/commit secrets · no force-push / no `--no-verify` · `dangerouslyDisableSandbox:true` for all build/test/rig commands · finish = merge to master + push.
---
### Task 1: FOCAS `cnc_getfigure` wire command + sim handler
**Classification:** standard
**Estimated implement time:** ~5 min
**Parallelizable with:** Task 2, Task 3
**Files:**
- Modify: `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/Wire/FocasWireClient.cs` (add `ReadPositionFiguresAsync`, mirror `ReadServoMeterAsync` at :351-386)
- Modify: `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/Wire/WireFocasClient.cs:287-297` (replace the empty-list stub)
- Modify: `tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.IntegrationTests/Docker/focas-mock/src/focas_mock/server.py` (add `_wire_position_figures` + a `_wire_payload` branch for the chosen command code)
- Modify: `tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.IntegrationTests/Docker/focas-mock/src/focas_mock/data_store.py` (add a default `position_figures` state key)
**Context:** `WireFocasClient` is the production path to real CNCs. `FocasDriver.cs:662` wraps the fetch in `SafeProbe(…, [])` and `AxisFactor` uses a figure only when present & ≥ 0 — so an empty/failed read degrades to today's config-knob behavior (cannot regress). The `.NET FocasWireClient` ↔ python `focas_mock` wire protocol is co-designed & sim-validated (bench-CNC validation is gated for the whole backend — out of scope). `IFocasClient.GetPositionFiguresAsync` already exists — **no interface change.**
**Steps:**
1. **`FocasWireClient.ReadPositionFiguresAsync(CancellationToken, TimeSpan? timeout, ushort? pathId)`** → `Task<FocasResult<IReadOnlyList<int>>>`. Pick a wire command id **unused by both the client and the mock's `_wire_payload`** (e.g. `0x00D3`); add an XML-doc note that the code is sim-consistent and bench-CNC-unvalidated. Send `new RequestBlock(<code>, PathId: requestPathId)`; on `rc != 0` return empty. Parse the response payload as consecutive big-endian `short dec` values (`payload.Length / 2` axes) into a `List<int>` via the existing `ReadInt16` helper. Keep it self-delimiting (no axis-name pairing needed).
2. **`WireFocasClient.GetPositionFiguresAsync`** — replace the stub body: `var r = await _client.ReadPositionFiguresAsync(cancellationToken).ConfigureAwait(false); return r.Rc == 0 && r.Value is not null ? r.Value : Array.Empty<int>();` (match the field/property names actually in `WireFocasClient`). Rewrite the now-inaccurate `<returns>` doc to describe the live fetch + graceful-empty fallback. Never throws.
3. **focas_mock `data_store.py`** — add a `position_figures` key to the default state: a per-axis decimal-place map (or list parallel to `axis_names`), **defaulting every axis to 0** (→ scale factor 1.0 → no change to existing integration assertions). Make it `mock_patch`-targetable.
4. **focas_mock `server.py`** — add `def _wire_position_figures(self) -> bytes:` returning `b"".join(self._u16(dec) for each axis in axis_names order)` reading from `position_figures` (default 0). Add a branch in `_wire_payload`: `if command == <code>: return self._wire_position_figures()`.
5. **Build:** `dotnet build src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS` — clean.
6. **Commit** (stage by explicit path): the two `.cs` files + the two `.py` files.
**Acceptance:** stub gone; client method follows the `ReadServoMeterAsync` pattern; mock returns per-axis figures defaulting to 0; FOCAS project builds clean. (Integration proof is Task 4.)
---
### Task 2: Wonderware poison-event per-event status (sidecar IPC + classifier + client)
**Classification:** standard
**Estimated implement time:** ~5 min
**Parallelizable with:** Task 1, Task 3
**Files:**
- Modify: `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Client/Ipc/Contracts.cs` (add `[Key(4)] byte[] PerEventStatus` to `WriteAlarmEventsReply`, ~:216-228)
- Modify: `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware/Ipc/Contracts.cs` (mirror the same `[Key(4)]` addition, ~:252-266)
- Modify: `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware/Ipc/HistorianFrameHandler.cs:162-199` (classifier + populate both fields)
- Modify: `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Client/WonderwareHistorianClient.cs:301-369` (consume `PerEventStatus`; rewrite stale `<remarks>` + inline comments)
- Test: `tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Tests/` (new file, e.g. `HistorianEventClassifierTests.cs`) — sidecar classifier unit test (project has `InternalsVisibleTo`)
- Test: `tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Client.Tests/WonderwareHistorianClientTests.cs` (client mapping + back-compat via `FakeSidecarServer.OnWriteAlarmEvents`)
**Context:** Both IPC ends are in-repo (MessagePack/TCP — **not** Commons). `HistorianWriteOutcome` already has `PermanentFail`; the sink (`SqliteStoreAndForwardSink.cs:456-465`) already dead-letters it. The sidecar `IAlarmEventWriter.WriteAsync` returns only `bool[]` — **do NOT change that interface** (its only real impl is the infra-gated `AahClientManagedAlarmEventWriter`). `AlarmHistorianEventDto` fields: `EventId`, `SourceName` (req), `ConditionId?`, `AlarmType` (req), `Message?`, `Severity`, `EventTimeUtcTicks`, `AckComment?`.
**Steps:**
1. **DTO (both Contracts.cs, identical):** add `/// <summary>Per-event status parallel to Events: 0=Ack, 1=Retry, 2=Permanent. Empty ⇒ older sidecar; fall back to PerEventOk.</summary>` `[Key(4)] public byte[] PerEventStatus { get; set; } = Array.Empty<byte>();`. **Keep `PerEventOk [Key(3)]`.** Define the 3 byte constants once on each side (e.g. `const byte StatusAck=0, StatusRetry=1, StatusPermanent=2;` local to the consumer, or a tiny shared-by-copy comment — do NOT add a Core.Abstractions enum).
2. **Sidecar `HistorianFrameHandler.HandleWriteAlarmEventsAsync`:** add a pure `internal static byte[] ClassifyAndSplit(AlarmHistorianEventDto[] events, out List<(int index, AlarmHistorianEventDto evt)> writable)` (or equivalent): an event with `string.IsNullOrWhiteSpace(SourceName)` OR `string.IsNullOrWhiteSpace(AlarmType)` OR `EventTimeUtcTicks <= 0` ⇒ **Permanent (2)** and **excluded** from the writer batch; others ⇒ writer-bound. Call `_alarmWriter.WriteAsync(writableEvents)`; map each writer `true`→Ack(0), `false`→Retry(1) back into its original index. Set `reply.PerEventStatus` (full length) AND `reply.PerEventOk` (Ack→true else false) AND `reply.Success = true`. In the no-writer + catch branches, set `PerEventStatus` to all-Retry(1) (matching the existing all-false PerEventOk).
3. **Client `WriteBatchAsync`:** after the `reply.Success` guard, if `reply.PerEventStatus is { Length: > 0 } st && st.Length == batch.Count`, map `0→Ack, 1→RetryPlease, 2→PermanentFail` (unknown→RetryPlease); else keep the existing `PerEventOk` loop. Rewrite the stale `<remarks>` (`:301-311`) + the two inline "PermanentFail is never emitted" comments to describe the new path + the documented SDK-semantic boundary.
4. **Sidecar test:** `ClassifyAndSplit` — malformed (empty SourceName / empty AlarmType / EventTimeUtcTicks ≤ 0) ⇒ Permanent + excluded; valid ⇒ writer-bound; verify index mapping with a mixed batch.
5. **Client test:** (a) `OnWriteAlarmEvents` returns `PerEventStatus=[2]` ⇒ `WriteBatchAsync` yields `PermanentFail`; (b) empty `PerEventStatus` + `PerEventOk=[false]` ⇒ `RetryPlease` (back-compat); (c) `PerEventStatus=[0]` ⇒ `Ack`.
6. **Build + test:** `dotnet build` the two src projects (note: sidecar targets net48 — build via the solution or the specific TFM) + `dotnet test` the two test projects (filter to the new tests).
7. **Commit** (explicit paths): 4 src files + 2 test files.
**Acceptance:** additive `[Key(4)]` on both ends; sidecar classifies structurally-malformed events as Permanent and excludes them; client emits `PermanentFail` from `PerEventStatus` and falls back to `PerEventOk`; stale comments gone; tests green. No `IAlarmEventWriter` / Commons / Core.Abstractions change.
---
### Task 3: AbCip nested-UDT Emulate-tier skip-gated test + docs
**Classification:** small
**Estimated implement time:** ~4 min
**Parallelizable with:** Task 1, Task 2
**Files:**
- Create: `tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbCip.IntegrationTests/Emulate/AbCipEmulateNestedUdtTests.cs`
- Modify: `docs/drivers/AbCip.md` (nested-struct = Emulate-tier verified note, ~:136)
**Context:** Decode/threading already shipped (`3d8ce4e8`/`d203f31c`); offline unit tests pin it (301/301). `ab_server` can't serve CIP Template Object (class 0x6C) → a local gate is impossible; the honest close is an Emulate-tier skip-gated smoke. Mirror `Emulate/AbCipEmulateUdtReadTests.cs` exactly (same `[AbServerFact]` + `AbServerProfileGate.SkipUnless(AbServerProfileGate.Emulate)` + `AB_SERVER_ENDPOINT` env, `Emulate = "emulate"`).
**Steps:**
1. Read `Emulate/AbCipEmulateUdtReadTests.cs` + `AbServerProfileGate.cs` + `AbServerFixture.cs` for the exact collection/attribute/skip pattern.
2. Write `AbCipEmulateNestedUdtTests` with one `[AbServerFact]` test: `SkipUnless(Emulate)`, read `AB_SERVER_ENDPOINT`, init an `AbCipDriver` with `EnableControllerBrowse=true`, run `DiscoverAsync` against a documented nested-UDT Emulate project (parent UDT with a nested struct member), assert the nested atomic leaves are addressable (`<Tag>.Status.Code`, `<Tag>.Status.Running`) and the nested sub-folder materializes. Document the assumed Emulate project shape in an XML/comment header (matching the `AbCipEmulateUdtReadTests` convention).
3. `docs/drivers/AbCip.md`: add/extend the nested-struct paragraph — support **shipped** (`3d8ce4e8`/`d203f31c`), **live-verified Emulate-tier only** because `ab_server` lacks CIP Template Object; reference `AbCipEmulateNestedUdtTests` + the offline unit coverage.
4. **Build + skip-check:** `dotnet build` the AbCip.IntegrationTests project (clean); run the new test by name and confirm it **skips** cleanly on this Mac (no Emulate): `dotnet test tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbCip.IntegrationTests --filter FullyQualifiedName~Nested_struct -- … ` → 0 failed, 1 skipped.
5. **Commit** (explicit paths): the new test file + `docs/drivers/AbCip.md`.
**Acceptance:** the test compiles & skips locally (proving it's wired); docs describe the Emulate-tier gate honestly. No runtime change.
---
### Task 4: FOCAS integration test + Component A live `/run`
**Classification:** small
**Estimated implement time:** ~4 min
**Parallelizable with:** none (after Task 1)
**Files:**
- Modify: `tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.IntegrationTests/Series/WireBackendCoverageTests.cs` (new skip-gated test)
**Steps:**
1. Read `Series/WireBackendTests.cs` + `Series/WireBackendCoverageTests.cs` + `FocasSimFixture.cs` for the `[Collection(FocasSimCollection.Name)]` + `if (_fx.SkipReason is not null) Assert.Skip(...)` + `mock_patch`/`LoadProfileAsync` pattern.
2. Add `Position_figures_scale_axis_via_wire_backend`: load a profile, `mock_patch` axis_names `["X"]`, a dynamic `pos.absolute = 12345`, and `position_figures` so X = 3 decimal places; init the wire-backed `FocasDriver` (FixedTree enabled, probe disabled); `WaitFor` the `AbsolutePosition` snapshot; assert it equals **12.345** (raw ÷ 10^3) — i.e. the auto figure won, not the config knob.
3. **Live `/run` (Component A):** bring the focas-mock up locally and run the FOCAS integration suite:
```
docker compose -f tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.IntegrationTests/Docker/docker-compose.yml up -d --build
dotnet test tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.IntegrationTests --filter FullyQualifiedName~Position_figures_scale
```
Confirm the new test **executes (not skipped)** and passes. Tear the mock down after.
4. **Commit** (explicit path): the integration test file.
**Acceptance:** the new integration test runs against the live focas-mock and proves the scaled position end-to-end.
---
### Task 5: Reconcile backlog + memory + finish (merge + push)
**Classification:** small
**Estimated implement time:** ~4 min
**Parallelizable with:** none (last)
**Files:**
- Modify (NEVER staged): `stillpending.md` (mark #3/#5/#6)
- Modify: memory `project_stillpending_backlog.md` + `MEMORY.md` index line (under the memory dir)
**Steps:**
1. **Full solution build:** `dotnet build ZB.MOM.WW.OtOpcUa.slnx` — 0 errors.
2. **Targeted tests green:** Driver.FOCAS.Tests + Wonderware.Tests + Wonderware.Client.Tests + Core.AlarmHistorian.Tests + AbCip.IntegrationTests (new test skips). Report counts.
3. **`stillpending.md`** (never staged): #3 FOCAS — wire `cnc_getfigure` shipped + focas-mock-proven (real-Fanuc bench-CNC-gated, graceful fallback); #5 Wonderware — structurally-malformed poison events now `PermanentFail` → immediate dead-letter (additive `PerEventStatus`; SDK-semantic boundary noted as follow-up); #6 AbCip — live-gate formalized as the Emulate-tier skip-gated `AbCipEmulateNestedUdtTests`.
4. **Memory:** update `project_stillpending_backlog.md` (new top marker for this 3-item phase) + the `MEMORY.md` index line (keep ≤ ~200 chars; trim if over the soft cap).
5. **Finish** (superpowers-extended-cc:finishing-a-development-branch): verify tests → ff-merge `feat/focas-figure-ww-poison-abcip-gate` → master → push to origin → delete branch → confirm `local master = origin/master`.
**Acceptance:** build clean, tests green, backlog + memory reconciled, merged to master + pushed.
---
## Dependency graph
`{T1 ∥ T2 ∥ T3}` → `T4` (needs T1) → `T5` (last). T1/T2/T3 touch disjoint projects → dispatch implementers concurrently with **worktree isolation** (shared-tree git-race lesson).
@@ -0,0 +1,17 @@
{
"planPath": "docs/plans/2026-06-18-focas-figure-ww-poison-abcip-gate.md",
"executionState": "COMPLETE",
"tasks": [
{"id": 1, "subject": "Task 1: FOCAS cnc_getfigure wire command + sim handler", "classification": "standard", "status": "completed", "commits": ["f320f323", "e5f568d0"]},
{"id": 2, "subject": "Task 2: Wonderware poison-event per-event status (IPC + classifier + client)", "classification": "standard", "status": "completed", "commits": ["feddc2b8", "70aad3ef"]},
{"id": 3, "subject": "Task 3: AbCip nested-UDT Emulate-tier skip-gated test + docs", "classification": "small", "status": "completed", "commits": ["c8ab8fc3"]},
{"id": 4, "subject": "Task 4: FOCAS integration test + Component A live /run", "classification": "small", "status": "completed", "commits": ["40224570"], "liveRun": "PASS — Position_figures_scale_axis_via_wire_backend executed (not skipped) vs local focas-mock, AbsolutePosition=12.345"},
{"id": 5, "subject": "Task 5: Reconcile backlog + memory + finish (merge + push)", "classification": "small", "status": "completed"}
],
"verification": {
"solutionBuild": "0 errors",
"tests": "FOCAS 200/200, Wonderware.Client 40/40, Core.AlarmHistorian 27/27, AbCip 301/301; Wonderware.Tests (net48 sidecar) build-clean but cannot execute on macOS/arm64 (no mono)",
"liveRun": "FOCAS cnc_getfigure proven against local focas-mock"
},
"lastUpdated": "2026-06-18"
}
@@ -657,7 +657,7 @@ public sealed class FocasDriver : IDriver, IReadable, IWritable, ITagDiscovery,
// Per-axis decimal-place figures (cnc_getfigure), fetched once. Auto figures win
// over the manual PositionDecimalPlaces config at the publish seam; an empty list
// (the managed wire backend today) makes every axis fall back to the config knob.
// (or a failed/empty figure read) makes every axis fall back to the config knob.
// Defensive: a figure-read failure must NOT fault device init — default to empty.
state.PositionFigures = await SafeProbe(() => client.GetPositionFiguresAsync(ct), []);
@@ -830,9 +830,8 @@ public sealed class FocasDriver : IDriver, IReadable, IWritable, ITagDiscovery,
// an auto cnc_getfigure figure WINS, and the configured PositionDecimalPlaces is the
// fallback when the CNC didn't report one for that axis (see AxisFactor). A figure of
// 0 yields factor 1.0 — i.e. the integer widened to double, byte-identical to legacy
// behaviour (12345 / 1.0 == 12345.0). CAVEAT: the managed WireFocasClient returns no
// figures today, so the REAL backend always uses the manual fallback; live auto-fetch
// lands when a FocasWireClient cnc_getfigure wire command is added. FeedRate /
// behaviour (12345 / 1.0 == 12345.0). The managed WireFocasClient fetches figures live
// via ReadPositionFiguresAsync; the config knob is the per-axis fallback only. FeedRate /
// SpindleSpeed (rate snapshot) and ServoLoad are NOT position-scaled (published elsewhere).
var factor = AxisFactor(state, axisIndex);
state.LastFixedSnapshots[FixedTreeReference(host, $"Axes/{axis.Display}/AbsolutePosition")] = snap.AbsolutePosition / factor;
@@ -845,8 +844,9 @@ public sealed class FocasDriver : IDriver, IReadable, IWritable, ITagDiscovery,
/// Resolve the position-scale factor (10^figure) for a single axis. Auto
/// (<c>cnc_getfigure</c>) wins per-axis; manual <c>PositionDecimalPlaces</c> is the
/// fallback when the CNC didn't report a figure for that axis. Both clamp non-negative;
/// 0 ⇒ factor 1.0 (legacy byte-identical). The managed wire backend returns no figures
/// today, so the real backend always takes the manual-fallback branch.
/// 0 ⇒ factor 1.0 (legacy byte-identical). The managed wire backend fetches figures live
/// via <c>ReadPositionFiguresAsync</c>; the fallback branch fires only when the CNC
/// reports no figure for a given axis (or the figure read returns empty).
/// </summary>
private static double AxisFactor(DeviceState state, int axisIndex)
{
@@ -1202,8 +1202,8 @@ public sealed class FocasDriver : IDriver, IReadable, IWritable, ITagDiscovery,
/// <summary>
/// Gets or sets the per-axis position decimal-place figures fetched once at init via
/// <c>cnc_getfigure</c> (parallel to the axis-name list; index = axis). An auto figure
/// for an axis WINS over the configured <c>PositionDecimalPlaces</c>; an empty list (the
/// managed wire backend's behaviour today) makes every axis fall back to that config knob.
/// for an axis WINS over the configured <c>PositionDecimalPlaces</c>; an empty list (or
/// a failed/empty figure read) makes every axis fall back to that config knob.
/// </summary>
public IReadOnlyList<int> PositionFigures { get; set; } = [];
@@ -385,6 +385,41 @@ public sealed class FocasWireClient : IAsyncDisposable, IDisposable
return new FocasResult<IReadOnlyList<WireServoMeter>>(rc, result);
}
/// <summary>
/// Read the per-axis position decimal-place figures via <c>cnc_getfigure</c>
/// (command <c>0x00d3</c>). The response payload is a self-delimiting sequence of
/// big-endian <c>short</c> decimal-place counts — one per configured axis — which the
/// driver applies as a <c>10^figure</c> scale on raw position reads.
/// </summary>
/// <remarks>
/// The <c>0x00d3</c> command id is co-designed with the in-tree <c>focas_mock</c> sim and
/// validated against it; like the rest of this managed wire backend the binary shape is
/// sim-consistent and has not been validated against a real Fanuc CNC (bench-CNC-gated).
/// </remarks>
/// <param name="cancellationToken">Cancellation token for the read operation.</param>
/// <param name="timeout">Optional per-call timeout override.</param>
/// <param name="pathId">Optional path ID override; defaults to <see cref="PathId"/>.</param>
public async Task<FocasResult<IReadOnlyList<int>>> ReadPositionFiguresAsync(
CancellationToken cancellationToken = default,
TimeSpan? timeout = null,
ushort? pathId = null)
{
using var callTimeout = CreateCallTimeout(cancellationToken, timeout);
var requestPathId = EffectivePathId(pathId);
var block = await SendSingleRequestAsync(
callTimeout.Token,
new RequestBlock(0x00d3, PathId: requestPathId)).ConfigureAwait(false);
if (block.Rc != 0) return new FocasResult<IReadOnlyList<int>>(block.Rc, null);
var payload = block.Payload;
var figures = new List<int>(payload.Length / 2);
for (var offset = 0; offset + 2 <= payload.Length; offset += 2)
figures.Add(ReadInt16(payload, offset));
return new FocasResult<IReadOnlyList<int>>(block.Rc, figures);
}
/// <summary>Read per-spindle load percentages via <c>cnc_rdspload</c> (command <c>0x0040</c> with arg1=0).</summary>
/// <param name="spindleSelector">Spindle selector; -1 selects all spindles.</param>
/// <param name="cancellationToken">Cancellation token for the read operation.</param>
@@ -287,14 +287,26 @@ public sealed class WireFocasClient : IFocasClient
/// <summary>Gets the per-axis position decimal-place figures via <c>cnc_getfigure</c>.</summary>
/// <param name="cancellationToken">Cancellation token for the operation.</param>
/// <returns>
/// An empty list — the managed FOCAS/2 Ethernet wire client (<see cref="FocasWireClient"/>)
/// does not currently expose the <c>cnc_getfigure</c> command, so this backend reports no
/// per-axis figures. Per the <see cref="IFocasClient.GetPositionFiguresAsync"/> contract an
/// empty list signals the driver to fall back to the configured <c>PositionDecimalPlaces</c>.
/// Never throws — figure reads degrade to the config knob rather than faulting.
/// The per-axis decimal-place figures read from the CNC via
/// <see cref="FocasWireClient.ReadPositionFiguresAsync"/>, or an empty list when the read
/// fails (non-zero RC — e.g. the series lacks <c>cnc_getfigure</c>) or is not connected.
/// Per the <see cref="IFocasClient.GetPositionFiguresAsync"/> contract an empty list signals
/// the driver to fall back to the configured <c>PositionDecimalPlaces</c>. Never throws —
/// figure reads degrade to the config knob rather than faulting.
/// </returns>
public Task<IReadOnlyList<int>> GetPositionFiguresAsync(CancellationToken cancellationToken) =>
Task.FromResult<IReadOnlyList<int>>(Array.Empty<int>());
public async Task<IReadOnlyList<int>> GetPositionFiguresAsync(CancellationToken cancellationToken)
{
if (!_wire.IsConnected) return [];
try
{
var result = await _wire.ReadPositionFiguresAsync(cancellationToken).ConfigureAwait(false);
return result.IsOk && result.Value is { } figures ? figures : [];
}
catch (FocasWireException)
{
return [];
}
}
private static async Task<IReadOnlyList<int>> ReadSpindleMetricAsync(
Func<short, CancellationToken, Task<FocasResult<IReadOnlyList<WireSpindleMetric>>>> call,
@@ -225,4 +225,8 @@ public sealed class WriteAlarmEventsReply
/// <summary>Per-event success flag, parallel to <see cref="WriteAlarmEventsRequest.Events"/>.</summary>
[Key(3)] public bool[] PerEventOk { get; set; } = Array.Empty<bool>();
/// <summary>Per-event status parallel to the request's Events: 0=Ack, 1=Retry, 2=Permanent.
/// Empty ⇒ an older sidecar that only sent <see cref="PerEventOk"/>; the client falls back to it.</summary>
[Key(4)] public byte[] PerEventStatus { get; set; } = Array.Empty<byte>();
}
@@ -298,21 +298,29 @@ public sealed class WonderwareHistorianClient : IHistorianDataSource, IAlarmHist
/// </summary>
/// <remarks>
/// <para>
/// <b>PermanentFail limitation (finding 002):</b> this writer never returns
/// <see cref="HistorianWriteOutcome.PermanentFail"/>. The sidecar wire contract
/// (<see cref="WriteAlarmEventsReply.PerEventOk"/>) carries only a per-event
/// boolean (succeeded / did-not-succeed) and provides no unrecoverable vs.
/// transient distinction. A poison event that the historian SDK can never persist
/// (e.g. a permanently malformed row) will therefore retry indefinitely inside the
/// store-and-forward drain worker rather than being moved to the dead-letter table.
/// Extending the protocol to add a per-event status enum (Ack / Retry / Permanent)
/// requires a coordinated additive change to the .NET 4.8 sidecar and is tracked as
/// a follow-up. Until then, the drain worker's own retry-count limit is the
/// backstop against an infinite loop.
/// <b>Per-event status:</b> when the sidecar populates the additive
/// <see cref="WriteAlarmEventsReply.PerEventStatus"/> wire field (0=Ack, 1=Retry,
/// 2=Permanent), each slot maps directly to <see cref="HistorianWriteOutcome.Ack"/> /
/// <see cref="HistorianWriteOutcome.RetryPlease"/> / <see cref="HistorianWriteOutcome.PermanentFail"/>.
/// The sidecar emits <c>Permanent</c> for structurally-malformed (poison) events,
/// so the store-and-forward drain worker dead-letters them immediately instead of
/// looping to the retry cap. An older sidecar that sends only the legacy
/// <see cref="WriteAlarmEventsReply.PerEventOk"/> boolean is handled by the
/// fallback path below (true→Ack, false→RetryPlease) for rolling-deploy back-compat.
/// </para>
/// <para>
/// Transport or deserialization failures return <see cref="HistorianWriteOutcome.RetryPlease"/>
/// for every event in the batch; the drain worker's backoff controls recovery.
/// <b>Documented boundary:</b> only <i>structurally</i>-malformed events surface as
/// <see cref="HistorianWriteOutcome.PermanentFail"/>. A structurally-valid event that
/// the AAH historian SDK rejects for a deeper, semantic reason still maps to
/// <see cref="HistorianWriteOutcome.RetryPlease"/> (→ retry cap), because the sidecar's
/// writer returns only a transient/persisted boolean for events it actually attempts.
/// Surfacing richer SDK-semantic permanent rejections requires the infra-gated
/// <c>AahClientManagedAlarmEventWriter</c> to report a status code rather than a bool.
/// </para>
/// <para>
/// Transport or deserialization failures, and any whole-call failure
/// (<c>Success=false</c>), return <see cref="HistorianWriteOutcome.RetryPlease"/> for
/// every event in the batch; the drain worker's backoff controls recovery.
/// </para>
/// </remarks>
/// <param name="batch">The batch of alarm historian events to write.</param>
@@ -347,9 +355,26 @@ public sealed class WonderwareHistorianClient : IHistorianDataSource, IAlarmHist
return fail;
}
// Per-event status: PerEventOk[i] = true → Ack; false → RetryPlease.
// NOTE: PermanentFail is never emitted — see <remarks> for the wire-contract
// limitation and why poison events currently retry rather than dead-letter.
// Prefer the granular per-event status when the sidecar provides it (new wire
// field); fall back to the legacy PerEventOk bool for older sidecars. The sidecar
// emits status 2 (Permanent) for structurally-malformed poison events so they
// dead-letter immediately rather than retrying to the cap.
if (reply.PerEventStatus is { Length: > 0 } status && status.Length == batch.Count)
{
var statusOutcomes = new HistorianWriteOutcome[batch.Count];
for (var i = 0; i < batch.Count; i++)
statusOutcomes[i] = status[i] switch
{
0 => HistorianWriteOutcome.Ack,
2 => HistorianWriteOutcome.PermanentFail,
_ => HistorianWriteOutcome.RetryPlease, // 1 or unknown
};
return statusOutcomes;
}
// Legacy fallback: PerEventOk[i] = true → Ack; false → RetryPlease. An older
// sidecar without PerEventStatus can never signal PermanentFail through this
// path, so a poison event retries to the drain worker's cap.
var outcomes = new HistorianWriteOutcome[batch.Count];
for (var i = 0; i < batch.Count; i++)
{
@@ -361,7 +386,8 @@ public sealed class WonderwareHistorianClient : IHistorianDataSource, IAlarmHist
catch
{
// Transport / deserialization failure — every event is retry-please. The drain
// worker's backoff handles recovery. PermanentFail is never emitted (see <remarks>).
// worker's backoff handles recovery. PermanentFail is only emitted from the
// success path's PerEventStatus mapping, never from a transport failure.
var fail = new HistorianWriteOutcome[batch.Count];
Array.Fill(fail, HistorianWriteOutcome.RetryPlease);
return fail;
@@ -263,4 +263,8 @@ public sealed class WriteAlarmEventsReply
/// <summary>Per-event success flag, parallel to <see cref="WriteAlarmEventsRequest.Events"/>.</summary>
[Key(3)] public bool[] PerEventOk { get; set; } = Array.Empty<bool>();
/// <summary>Per-event status parallel to the request's Events: 0=Ack, 1=Retry, 2=Permanent.
/// Empty ⇒ an older sidecar that only sent <see cref="PerEventOk"/>; the client falls back to it.</summary>
[Key(4)] public byte[] PerEventStatus { get; set; } = Array.Empty<byte>();
}
@@ -16,6 +16,11 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Ipc;
/// </summary>
public sealed class HistorianFrameHandler : IFrameHandler
{
// WriteAlarmEventsReply.PerEventStatus byte semantics: 0=Ack, 1=Retry, 2=Permanent.
private const byte StatusAck = 0;
private const byte StatusRetry = 1;
private const byte StatusPermanent = 2;
private readonly IHistorianDataSource _historian;
private readonly IAlarmEventWriter? _alarmWriter;
private readonly ILogger _logger;
@@ -174,18 +179,51 @@ public sealed class HistorianFrameHandler : IFrameHandler
reply.Success = false;
reply.Error = "Sidecar not configured with an alarm-event writer.";
reply.PerEventOk = new bool[req.Events.Length];
reply.PerEventStatus = AllStatus(req.Events.Length, StatusRetry);
await writer.WriteAsync(MessageKind.WriteAlarmEventsReply, reply, ct).ConfigureAwait(false);
return;
}
try
{
var perEvent = await _alarmWriter.WriteAsync(req.Events, ct).ConfigureAwait(false);
reply.PerEventOk = perEvent;
// Classify each event before touching the writer: structurally-malformed
// (poison) events can never be persisted, so mark them Permanent and exclude
// them from the writer batch. Only the well-formed remainder is handed to the
// writer, whose bool[] result is mapped back onto the original indices.
var status = new byte[req.Events.Length];
var writable = new List<AlarmHistorianEventDto>(req.Events.Length);
var originalIndex = new List<int>(req.Events.Length);
for (var i = 0; i < req.Events.Length; i++)
{
if (IsStructurallyMalformed(req.Events[i]))
{
status[i] = StatusPermanent;
}
else
{
originalIndex.Add(i);
writable.Add(req.Events[i]);
}
}
// Aligned 1:1 to `writable`; empty when every event was poison (writer skipped).
var perEvent = writable.Count == 0
? Array.Empty<bool>()
: await _alarmWriter.WriteAsync(writable.ToArray(), ct).ConfigureAwait(false);
for (var i = 0; i < originalIndex.Count; i++)
{
var ok = i < perEvent.Length && perEvent[i];
status[originalIndex[i]] = ok ? StatusAck : StatusRetry;
}
reply.PerEventStatus = status;
reply.PerEventOk = StatusToOk(status);
reply.Success = true;
// Whole-batch Success stays true even when some events failed — per-event
// PerEventOk slots carry the granular result; the SQLite drain worker treats
// false slots as retry-please candidates.
// PerEventStatus slots carry the granular result (Ack / Retry / Permanent);
// the SQLite drain worker acks 0, retries 1, and dead-letters 2. PerEventOk
// is kept populated for rolling-deploy back-compat with an older client.
}
catch (Exception ex)
{
@@ -193,11 +231,41 @@ public sealed class HistorianFrameHandler : IFrameHandler
reply.Success = false;
reply.Error = ex.Message;
reply.PerEventOk = new bool[req.Events.Length];
reply.PerEventStatus = AllStatus(req.Events.Length, StatusRetry);
}
await writer.WriteAsync(MessageKind.WriteAlarmEventsReply, reply, ct).ConfigureAwait(false);
}
/// <summary>
/// Classifies an alarm event as structurally malformed (poison): an event the historian
/// event store can never persist regardless of retries. Such events are marked Permanent
/// so the store-and-forward sink dead-letters them immediately instead of looping to the
/// retry cap. A blank source name or alarm type, or a non-positive event timestamp, are
/// the structural invariants the historian write requires.
/// </summary>
/// <param name="e">The candidate alarm event.</param>
/// <returns><c>true</c> when the event is structurally malformed; otherwise <c>false</c>.</returns>
internal static bool IsStructurallyMalformed(AlarmHistorianEventDto e) =>
e is null
|| string.IsNullOrWhiteSpace(e.SourceName)
|| string.IsNullOrWhiteSpace(e.AlarmType)
|| e.EventTimeUtcTicks <= 0;
private static byte[] AllStatus(int length, byte value)
{
var status = new byte[length];
for (var i = 0; i < length; i++) status[i] = value;
return status;
}
private static bool[] StatusToOk(byte[] status)
{
var ok = new bool[status.Length];
for (var i = 0; i < status.Length; i++) ok[i] = status[i] == StatusAck;
return ok;
}
private static HistorianSampleDto[] ToWire(List<HistorianSample> samples)
{
var dtos = new HistorianSampleDto[samples.Count];
@@ -0,0 +1,132 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Driver.AbCip;
namespace ZB.MOM.WW.OtOpcUa.Driver.AbCip.IntegrationTests.Emulate;
/// <summary>
/// Live-gate smoke for backlog #6: controller-discovered nested-struct UDT expansion
/// via Template Object (CIP class 0x6C) against Rockwell Studio 5000 Logix Emulate.
/// Closes the gap left by the offline unit suite
/// (<c>AbCipDriverDiscoveryTests.Controller_discovered_UDT_nested_struct_expands_via_nested_template_id_fetch_no_seam</c>
/// and <c>CipTemplateObjectDecoderTests</c>) — those tests proved correctness with
/// golden-box byte buffers, but the Template Object service (class 0x6C) is NOT
/// implemented by the default <c>ab_server</c> Docker simulator. Emulate's firmware
/// speaks production CIP responses so the nested-template-id threading (commits
/// 3d8ce4e8 / d203f31c) gets end-to-end wire-level coverage here.
/// </summary>
/// <remarks>
/// <para><b>Required Emulate project state</b>:</para>
/// <list type="bullet">
/// <item>UDT <c>StatusNested_UDT</c> with members <c>Code : DINT</c>,
/// <c>Running : BOOL</c>.</item>
/// <item>UDT <c>MotorNested_UDT</c> with members <c>Speed : DINT</c>,
/// <c>Status : StatusNested_UDT</c> — <c>Status</c> is the nested struct member
/// whose template instance id the driver must re-fetch via <c>@udt/{id}</c>.</item>
/// <item>Controller-scope tag <c>MotorNested1 : MotorNested_UDT</c>.</item>
/// </list>
/// <para>Runs only when <c>AB_SERVER_PROFILE=emulate</c>. With <c>ab_server</c>
/// (the default tier), skips cleanly — <c>ab_server</c> lacks CIP Template Object
/// (class 0x6C) emulation so the nested-id fetch would time-out regardless.</para>
/// <para>The Emulate tier is hardware-gated (Rockwell per-seat license, Windows-only,
/// conflicts with Docker Desktop's WSL 2 backend) so a permanent skip in CI is expected
/// — see <c>docs/drivers/AbServer-Test-Fixture.md</c> §"Logix Emulate golden-box tier"
/// for the full rationale + the gap matrix this test closes.</para>
/// </remarks>
[Collection("AbServerEmulate")]
[Trait("Category", "Integration")]
[Trait("Tier", "Emulate")]
public sealed class AbCipEmulateNestedUdtTests
{
/// <summary>
/// Verifies that a controller-discovered nested-struct UDT expands into atomic
/// leaves addressable as dot-joined paths, proving the nested template-id threading
/// runs the production <c>@udt/{id}</c> CIP fetch against Emulate's firmware.
/// </summary>
[AbServerFact]
public async Task Nested_struct_member_discovered_and_expanded_via_template_id_fetch()
{
AbServerProfileGate.SkipUnless(AbServerProfileGate.Emulate);
var endpoint = Environment.GetEnvironmentVariable("AB_SERVER_ENDPOINT")
?? throw new InvalidOperationException(
"AB_SERVER_ENDPOINT must be set to the Logix Emulate instance " +
"(e.g. '10.0.0.42:44818') when AB_SERVER_PROFILE=emulate.");
var options = new AbCipDriverOptions
{
Devices = [new AbCipDeviceOptions($"ab://{endpoint}/1,0")],
EnableControllerBrowse = true,
Timeout = TimeSpan.FromSeconds(10),
};
await using var drv = new AbCipDriver(options, driverInstanceId: "emulate-nested-udt-smoke");
await drv.InitializeAsync("{}", TestContext.Current.CancellationToken);
// Drive controller discovery — the driver walks @tags, encounters MotorNested1
// (a Structure symbol), reads its template via @udt/{motorTemplateId}, finds
// the nested Status member (struct flag set, nested template id in low 12 bits),
// then re-fetches @udt/{statusTemplateId} to expand the nested leaves.
var discovered = new DiscoveryRecorder();
await drv.DiscoverAsync(discovered, TestContext.Current.CancellationToken);
// The MotorNested1 UDT sub-folder is materialised under Discovered/.
discovered.FolderNames.ShouldContain("MotorNested1",
"expected a MotorNested1 sub-folder — check that the Emulate project has a " +
"MotorNested1 : MotorNested_UDT controller-scope tag and EnableControllerBrowse is true");
var byName = discovered.Variables.ToDictionary(v => v.FullName, v => v);
// Top-level atomic member — Speed : DINT.
byName.ShouldContainKey("MotorNested1.Speed",
"MotorNested1.Speed not discovered — top-level atomic member expansion failed");
// Nested struct atomic leaves — Status.Code : DINT, Status.Running : BOOL.
// These prove the nested template-id fetch actually ran (ab_server can't reach here).
byName.ShouldContainKey("MotorNested1.Status.Code",
"MotorNested1.Status.Code not discovered — nested template-id fetch + expansion did not run");
byName.ShouldContainKey("MotorNested1.Status.Running",
"MotorNested1.Status.Running not discovered — nested template-id fetch + expansion did not run");
// The nested struct's sub-folder is materialised (lazy, only when a leaf is emitted).
discovered.FolderNames.ShouldContain("MotorNested1.Status",
"expected a MotorNested1.Status sub-folder for the nested StatusNested_UDT expansion");
// The bare MotorNested1 Structure placeholder Variable must NOT be emitted — the
// container is replaced by the member fan-out, not emitted alongside it.
byName.ShouldNotContainKey("MotorNested1",
"MotorNested1 bare Structure placeholder should NOT be emitted when member fan-out succeeds");
}
// ---- minimal recorder wired to IAddressSpaceBuilder ----
private sealed class DiscoveryRecorder : ZB.MOM.WW.OtOpcUa.Core.Abstractions.IAddressSpaceBuilder
{
public List<string> FolderNames { get; } = new();
public List<(string FullName, ZB.MOM.WW.OtOpcUa.Core.Abstractions.DriverDataType DataType)> Variables { get; } = new();
public ZB.MOM.WW.OtOpcUa.Core.Abstractions.IAddressSpaceBuilder Folder(string browseName, string displayName)
{ FolderNames.Add(browseName); return this; }
public ZB.MOM.WW.OtOpcUa.Core.Abstractions.IVariableHandle Variable(
string browseName, string displayName, ZB.MOM.WW.OtOpcUa.Core.Abstractions.DriverAttributeInfo info)
{
Variables.Add((info.FullName, info.DriverDataType));
return new Nop(info.FullName);
}
public void AddProperty(string _, ZB.MOM.WW.OtOpcUa.Core.Abstractions.DriverDataType __, object? ___) { }
private sealed class Nop(string fullRef) : ZB.MOM.WW.OtOpcUa.Core.Abstractions.IVariableHandle
{
public string FullReference => fullRef;
public ZB.MOM.WW.OtOpcUa.Core.Abstractions.IAlarmConditionSink MarkAsAlarmCondition(
ZB.MOM.WW.OtOpcUa.Core.Abstractions.AlarmConditionInfo info) => new NullSink();
}
private sealed class NullSink : ZB.MOM.WW.OtOpcUa.Core.Abstractions.IAlarmConditionSink
{
public void OnTransition(ZB.MOM.WW.OtOpcUa.Core.Abstractions.AlarmEventArgs args) { }
}
}
}
@@ -78,6 +78,10 @@ def make_default_state(profile: Mapping[str, Any]) -> dict[str, Any]:
"acts": 3200,
"acts2": [3200] + [0] * (max_spindles - 1),
"axis_names": axis_names[:max_axis],
# Per-axis position decimal places served by cnc_getfigure (command 0x00d3).
# Default every configured axis to 0 ⇒ 10^0 = 1.0 scale, leaving existing
# position reads unchanged. mock_patch can override individual axes.
"position_figures": {name: 0 for name in axis_names[:max_axis]},
"spindle_names": spindle_names,
"parameters": {
"6711": {"type": "long", "value": 1, "decimal": 0, "description": "example parameter"},
@@ -256,6 +256,8 @@ class FocasMockServer:
return self._wire_spindle_metric(request_block)
if command == 0x56:
return self._wire_servo_meter()
if command == 0xD3:
return self._wire_position_figures()
if command == 0x57:
mode = self.store.snapshot()["operation_mode"]
return self._u16(int(mode.get("mode", 0) if isinstance(mode, dict) else mode))
@@ -381,6 +383,14 @@ class FocasMockServer:
payload += self._name_record(name, 4)
return bytes(payload)
def _wire_position_figures(self) -> bytes:
state = self.store.snapshot()
figures = state.get("position_figures", {})
payload = bytearray()
for name in state["axis_names"]:
payload += self._u16(int(figures.get(name, 0)))
return bytes(payload)
def _wire_spindle_metric(self, request_block: bytes) -> bytes:
metric = self._block_u32(request_block, 8)
spindle = self.store.snapshot()["spindle"]
@@ -237,6 +237,73 @@ public sealed class WireBackendCoverageTests
}
}
/// <summary>
/// Verifies that per-axis position figures fetched via <c>cnc_getfigure</c> (wire command
/// 0x00D3) scale the published <c>AbsolutePosition</c>, and that the auto figure wins over
/// the configured <c>PositionDecimalPlaces</c> fallback knob.
/// Seed: X axis absolute = 12345, figure = 3 → published value = 12.345 (÷ 10^3).
/// Config knob = 1 → fallback would give 1234.5. 12.345 uniquely proves the wire path.
/// </summary>
[Fact]
public async Task Position_figures_scale_axis_via_wire_backend()
{
if (_fx.SkipReason is not null) Assert.Skip(_fx.SkipReason);
var ct = TestContext.Current.CancellationToken;
await _fx.LoadProfileAsync("FWLIB64", ct);
await _fx.PatchStateAsync(new
{
axis_names = new[] { "X" },
dynamic = new
{
alarm = 0, prgnum = 1, prgmnum = 1, seqnum = 1,
actf = 0, acts = 0,
axes = new
{
X = new { absolute = 12345, machine = 12345, relative = 0, distance = 0 },
},
},
// Per-axis decimal-place figures for cnc_getfigure (command 0x00D3).
// The mock's _wire_position_figures() reads state["position_figures"][axisName].
position_figures = new { X = 3 },
}, ct);
// PositionDecimalPlaces = 1 is intentionally different from the auto figure (3)
// so the assertion 12.345 uniquely proves the cnc_getfigure path won.
var driver = new FocasDriver(new FocasDriverOptions
{
Devices = [new FocasDeviceOptions(DeviceHost, PositionDecimalPlaces: 1)],
Tags = [],
Probe = new FocasProbeOptions { Enabled = false },
FixedTree = new FocasFixedTreeOptions
{
Enabled = true,
PollInterval = TimeSpan.FromMilliseconds(100),
ProgramPollInterval = TimeSpan.Zero,
TimerPollInterval = TimeSpan.Zero,
},
}, driverInstanceId: "wire-figures", clientFactory: new WireFocasClientFactory());
await using (driver)
{
await driver.InitializeAsync("{}", ct);
await WaitFor(() =>
driver.GetDeviceState(DeviceHost)?.LastFixedSnapshots
.ContainsKey($"{DeviceHost}/Axes/X/AbsolutePosition") == true,
TimeSpan.FromSeconds(5));
var state = driver.GetDeviceState(DeviceHost);
state.ShouldNotBeNull();
var published = state.LastFixedSnapshots[$"{DeviceHost}/Axes/X/AbsolutePosition"];
// 12345 ÷ 10^3 = 12.345 → auto figure (3) won.
// 12345 ÷ 10^1 = 1234.5 → would mean config knob (1) was used instead.
// 12345 ÷ 10^0 = 12345.0 → would mean no scaling at all.
published.ShouldBe(12.345, tolerance: 0.0001);
}
}
private static async Task WaitFor(Func<bool> pred, TimeSpan timeout)
{
var deadline = DateTime.UtcNow + timeout;
@@ -9,8 +9,8 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests;
/// per-axis position decimal-place figures at init and applies them at the
/// <see cref="FocasDriver"/> publish seam. Precedence: an auto figure for an axis WINS;
/// the configured <c>PositionDecimalPlaces</c> is the per-axis fallback when the CNC did
/// not report a figure for that axis. (The managed wire backend returns no figures today,
/// so the real backend always uses the manual fallback — these tests drive the Fake.)
/// not report a figure for that axis. These tests drive the Fake to exercise the driver's
/// auto-scale-vs-fallback logic independently of the wire path.
/// </summary>
[Trait("Category", "Unit")]
public sealed class FocasPositionAutoScaleTests
@@ -8,8 +8,9 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests;
/// Phase 4 data-type tier — axis-position scaling. <c>cnc_rddynamic2</c> returns
/// positions as scaled integers; the driver applies a <c>10^PositionDecimalPlaces</c>
/// divide at the <see cref="FocasDriver"/> publish seam so positions surface in
/// engineering units on the Float64 axis nodes. DecimalPlaces is config-supplied
/// (auto-fetch via <c>cnc_getfigure</c> is deferred — wire-gated).
/// engineering units on the Float64 axis nodes. The managed wire backend fetches per-axis
/// figures live via <c>cnc_getfigure</c>; the config knob is the per-axis fallback used
/// when the CNC reports no figure for an axis. These tests cover the config-supplied path.
/// </summary>
[Trait("Category", "Unit")]
public sealed class FocasPositionScalingTests
@@ -302,6 +302,162 @@ public sealed class WonderwareHistorianClientTests
outcomes[1].ShouldBe(HistorianWriteOutcome.RetryPlease);
}
/// <summary>
/// The granular PerEventStatus wire field maps directly: 0→Ack, 1→Retry, 2→PermanentFail.
/// A poison event the sidecar marks Permanent (status 2) must dead-letter via
/// <see cref="HistorianWriteOutcome.PermanentFail"/> rather than retrying.
/// </summary>
[Fact]
public async Task WriteBatchAsync_PerEventStatusPermanent_MapsToPermanentFail()
{
await using var server = new FakeSidecarServer(Secret)
{
OnWriteAlarmEvents = _ => new WriteAlarmEventsReply
{
Success = true,
PerEventStatus = [2], // Permanent
},
};
await server.StartAsync();
await using var client = TcpClientFor(server);
var batch = new[]
{
new AlarmHistorianEvent("ev-poison", "Tank/HiHi", "HiHi", "LimitAlarm", AlarmSeverity.High, "Activated", "msg", "u", null, DateTime.UtcNow),
};
var outcomes = await client.WriteBatchAsync(batch, CancellationToken.None);
outcomes.Count.ShouldBe(1);
outcomes[0].ShouldBe(HistorianWriteOutcome.PermanentFail);
}
/// <summary>
/// PerEventStatus = 0 maps to <see cref="HistorianWriteOutcome.Ack"/>; the granular path
/// takes precedence over the legacy PerEventOk bool when both are present.
/// </summary>
[Fact]
public async Task WriteBatchAsync_PerEventStatusAck_MapsToAck()
{
await using var server = new FakeSidecarServer(Secret)
{
OnWriteAlarmEvents = _ => new WriteAlarmEventsReply
{
Success = true,
PerEventStatus = [0], // Ack
},
};
await server.StartAsync();
await using var client = TcpClientFor(server);
var batch = new[]
{
new AlarmHistorianEvent("ev-ok", "Tank/HiHi", "HiHi", "LimitAlarm", AlarmSeverity.High, "Activated", "msg", "u", null, DateTime.UtcNow),
};
var outcomes = await client.WriteBatchAsync(batch, CancellationToken.None);
outcomes.Count.ShouldBe(1);
outcomes[0].ShouldBe(HistorianWriteOutcome.Ack);
}
/// <summary>
/// When <c>PerEventStatus</c> is present but its length does not equal the batch size,
/// the client must ignore it and fall back to the legacy <c>PerEventOk</c> path to
/// avoid mis-indexing into the status array. Here a 2-event batch receives
/// <c>PerEventStatus=[1]</c> (length 1) but <c>PerEventOk=[true, false]</c>; the
/// outcomes must reflect the PerEventOk values ([Ack, RetryPlease]), not the status
/// byte (which would have produced [RetryPlease] had it been used).
/// </summary>
[Fact]
public async Task WriteBatchAsync_PerEventStatusLengthMismatch_FallsBackToPerEventOk()
{
await using var server = new FakeSidecarServer(Secret)
{
OnWriteAlarmEvents = _ => new WriteAlarmEventsReply
{
Success = true,
PerEventStatus = [1], // length 1 ≠ batch count 2 → must be ignored
PerEventOk = [true, false], // legacy fallback: true→Ack, false→RetryPlease
},
};
await server.StartAsync();
await using var client = TcpClientFor(server);
var batch = new[]
{
new AlarmHistorianEvent("ev-1", "Tank/HiHi", "HiHi", "LimitAlarm", AlarmSeverity.High, "Activated", "msg", "u", null, DateTime.UtcNow),
new AlarmHistorianEvent("ev-2", "Tank/HiHi", "HiHi", "LimitAlarm", AlarmSeverity.High, "Acknowledged", "msg", "u", null, DateTime.UtcNow),
};
var outcomes = await client.WriteBatchAsync(batch, CancellationToken.None);
outcomes.Count.ShouldBe(2);
outcomes[0].ShouldBe(HistorianWriteOutcome.Ack); // PerEventOk[0] = true
outcomes[1].ShouldBe(HistorianWriteOutcome.RetryPlease); // PerEventOk[1] = false
}
/// <summary>
/// Status byte 1 (the only value that is neither 0 nor 2) must map to
/// <see cref="HistorianWriteOutcome.RetryPlease"/> via the default arm of the
/// <c>PerEventStatus</c> switch. A single-event batch with <c>PerEventStatus=[1]</c>
/// (length matches batch) must yield <c>[RetryPlease]</c>.
/// </summary>
[Fact]
public async Task WriteBatchAsync_PerEventStatusRetry_MapsToRetryPlease()
{
await using var server = new FakeSidecarServer(Secret)
{
OnWriteAlarmEvents = _ => new WriteAlarmEventsReply
{
Success = true,
PerEventStatus = [1], // status 1 → RetryPlease
},
};
await server.StartAsync();
await using var client = TcpClientFor(server);
var batch = new[]
{
new AlarmHistorianEvent("ev-retry", "Tank/HiHi", "HiHi", "LimitAlarm", AlarmSeverity.High, "Activated", "msg", "u", null, DateTime.UtcNow),
};
var outcomes = await client.WriteBatchAsync(batch, CancellationToken.None);
outcomes.Count.ShouldBe(1);
outcomes[0].ShouldBe(HistorianWriteOutcome.RetryPlease);
}
/// <summary>
/// Rolling-deploy back-compat: an older sidecar that sends an empty PerEventStatus but a
/// populated PerEventOk must still classify via the legacy bool path (false→RetryPlease).
/// </summary>
[Fact]
public async Task WriteBatchAsync_EmptyPerEventStatus_FallsBackToLegacyPerEventOk()
{
await using var server = new FakeSidecarServer(Secret)
{
OnWriteAlarmEvents = _ => new WriteAlarmEventsReply
{
Success = true,
PerEventStatus = [], // older sidecar — no granular status
PerEventOk = [false],
},
};
await server.StartAsync();
await using var client = TcpClientFor(server);
var batch = new[]
{
new AlarmHistorianEvent("ev-legacy", "Tank/HiHi", "HiHi", "LimitAlarm", AlarmSeverity.High, "Activated", "msg", "u", null, DateTime.UtcNow),
};
var outcomes = await client.WriteBatchAsync(batch, CancellationToken.None);
outcomes.Count.ShouldBe(1);
outcomes[0].ShouldBe(HistorianWriteOutcome.RetryPlease);
}
/// <summary>Verifies that Hello handshake throws UnauthorizedAccessException on secret mismatch.</summary>
[Fact]
public async Task Hello_BadSecret_ThrowsUnauthorizedAccess()
@@ -0,0 +1,226 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MessagePack;
using Serilog.Core;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Backend;
using ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Ipc;
namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Tests.Ipc
{
/// <summary>
/// Pins the sidecar's poison-event classifier and the per-event status mapping in
/// <see cref="HistorianFrameHandler"/>. A structurally-malformed alarm event is marked
/// Permanent (status 2) and excluded from the writer batch so the store-and-forward sink
/// dead-letters it immediately rather than looping to the retry cap; well-formed events
/// map to Ack (0) / Retry (1) from the writer's per-event bool result.
/// </summary>
[Trait("Category", "Unit")]
public sealed class HistorianEventClassifierTests
{
/// <summary>Verifies a blank source name is classified structurally malformed.</summary>
[Fact]
public void IsStructurallyMalformed_BlankSourceName_IsTrue()
{
var e = WellFormed();
e.SourceName = " ";
HistorianFrameHandler.IsStructurallyMalformed(e).ShouldBeTrue();
}
/// <summary>Verifies a blank alarm type is classified structurally malformed.</summary>
[Fact]
public void IsStructurallyMalformed_BlankAlarmType_IsTrue()
{
var e = WellFormed();
e.AlarmType = "";
HistorianFrameHandler.IsStructurallyMalformed(e).ShouldBeTrue();
}
/// <summary>Verifies a non-positive event timestamp is classified structurally malformed.</summary>
/// <param name="ticks">The event timestamp in ticks to test.</param>
[Theory]
[InlineData(0L)]
[InlineData(-1L)]
public void IsStructurallyMalformed_NonPositiveTimestamp_IsTrue(long ticks)
{
var e = WellFormed();
e.EventTimeUtcTicks = ticks;
HistorianFrameHandler.IsStructurallyMalformed(e).ShouldBeTrue();
}
/// <summary>Verifies a well-formed event is not classified structurally malformed.</summary>
[Fact]
public void IsStructurallyMalformed_WellFormedEvent_IsFalse()
{
HistorianFrameHandler.IsStructurallyMalformed(WellFormed()).ShouldBeFalse();
}
/// <summary>
/// A mixed batch — one poison event then one well-formed event the writer acks — must
/// yield PerEventStatus = [2, 0]: the poison event is Permanent and excluded from the
/// writer batch, and only the well-formed event reaches the writer.
/// </summary>
[Fact]
public async Task Handler_MixedBatch_MarksPoisonPermanent_AndOnlyWritesWellFormed()
{
var poison = WellFormed();
poison.EventId = "poison";
poison.SourceName = ""; // structurally malformed
var good = WellFormed();
good.EventId = "good";
var fakeWriter = new RecordingAlarmEventWriter(_ => true);
var handler = new HistorianFrameHandler(new StubHistorian(), Logger.None, fakeWriter);
var req = new WriteAlarmEventsRequest { Events = new[] { poison, good }, CorrelationId = "c1" };
var reply = await RoundTripAsync(handler, req);
reply.Success.ShouldBeTrue();
reply.PerEventStatus.ShouldBe(new byte[] { 2, 0 });
reply.PerEventOk.ShouldBe(new[] { false, true });
// The writer only ever saw the well-formed event.
fakeWriter.Received.Count.ShouldBe(1);
fakeWriter.Received[0].EventId.ShouldBe("good");
}
/// <summary>
/// A well-formed event the writer reports as not-persisted maps to Retry (status 1),
/// not Permanent — only structurally-malformed events are Permanent.
/// </summary>
[Fact]
public async Task Handler_WriterReportsNotPersisted_MapsToRetry()
{
var good = WellFormed();
good.EventId = "good";
var fakeWriter = new RecordingAlarmEventWriter(_ => false);
var handler = new HistorianFrameHandler(new StubHistorian(), Logger.None, fakeWriter);
var req = new WriteAlarmEventsRequest { Events = new[] { good }, CorrelationId = "c2" };
var reply = await RoundTripAsync(handler, req);
reply.Success.ShouldBeTrue();
reply.PerEventStatus.ShouldBe(new byte[] { 1 });
reply.PerEventOk.ShouldBe(new[] { false });
}
/// <summary>
/// An all-poison batch must short-circuit the writer entirely (no WriteAsync call)
/// and mark every slot Permanent.
/// </summary>
[Fact]
public async Task Handler_AllPoison_SkipsWriter_AllPermanent()
{
var p1 = WellFormed();
p1.SourceName = "";
var p2 = WellFormed();
p2.AlarmType = "";
var fakeWriter = new RecordingAlarmEventWriter(_ => true);
var handler = new HistorianFrameHandler(new StubHistorian(), Logger.None, fakeWriter);
var req = new WriteAlarmEventsRequest { Events = new[] { p1, p2 }, CorrelationId = "c3" };
var reply = await RoundTripAsync(handler, req);
reply.Success.ShouldBeTrue();
reply.PerEventStatus.ShouldBe(new byte[] { 2, 2 });
fakeWriter.Received.Count.ShouldBe(0);
}
private static AlarmHistorianEventDto WellFormed() => new()
{
EventId = "ev",
SourceName = "Tank.HiHi",
ConditionId = "HiHi",
AlarmType = "LimitAlarm:Activated",
Message = "msg",
Severity = 700,
EventTimeUtcTicks = new DateTime(2026, 6, 18, 12, 0, 0, DateTimeKind.Utc).Ticks,
AckComment = null,
};
/// <summary>
/// Drives a WriteAlarmEvents request through the real frame handler over an in-memory
/// duplex stream pair and deserializes the reply the handler writes back.
/// </summary>
private static async Task<WriteAlarmEventsReply> RoundTripAsync(
HistorianFrameHandler handler, WriteAlarmEventsRequest req)
{
var capture = new MemoryStream();
using var writer = new FrameWriter(capture, leaveOpen: true);
var body = MessagePackSerializer.Serialize(req);
await handler.HandleAsync(MessageKind.WriteAlarmEventsRequest, body, writer, CancellationToken.None);
capture.Position = 0;
using var reader = new FrameReader(capture, leaveOpen: true);
var frame = await reader.ReadFrameAsync(CancellationToken.None);
frame.ShouldNotBeNull();
frame!.Value.Kind.ShouldBe(MessageKind.WriteAlarmEventsReply);
return MessagePackSerializer.Deserialize<WriteAlarmEventsReply>(frame.Value.Body);
}
/// <summary>An <see cref="IAlarmEventWriter"/> that records the batch it received and returns a fixed verdict.</summary>
private sealed class RecordingAlarmEventWriter : IAlarmEventWriter
{
private readonly Func<AlarmHistorianEventDto, bool> _verdict;
/// <summary>Initializes a new instance with the given per-event verdict.</summary>
/// <param name="verdict">Maps each received event to its persisted/not-persisted result.</param>
public RecordingAlarmEventWriter(Func<AlarmHistorianEventDto, bool> verdict) => _verdict = verdict;
/// <summary>The events the writer was handed, in order.</summary>
public List<AlarmHistorianEventDto> Received { get; } = new();
/// <inheritdoc/>
public Task<bool[]> WriteAsync(AlarmHistorianEventDto[] events, CancellationToken cancellationToken)
{
Received.AddRange(events);
return Task.FromResult(events.Select(_verdict).ToArray());
}
}
/// <summary>
/// A read data source the WriteAlarmEvents path never touches — present only to
/// satisfy the <see cref="HistorianFrameHandler"/> ctor's non-null requirement.
/// </summary>
private sealed class StubHistorian : IHistorianDataSource
{
/// <inheritdoc/>
public Task<List<HistorianSample>> ReadRawAsync(
string tagName, DateTime startTime, DateTime endTime, int maxValues, CancellationToken ct = default)
=> throw new NotSupportedException();
/// <inheritdoc/>
public Task<List<HistorianAggregateSample>> ReadAggregateAsync(
string tagName, DateTime startTime, DateTime endTime, double intervalMs, string aggregateColumn, CancellationToken ct = default)
=> throw new NotSupportedException();
/// <inheritdoc/>
public Task<List<HistorianSample>> ReadAtTimeAsync(
string tagName, DateTime[] timestamps, CancellationToken ct = default)
=> throw new NotSupportedException();
/// <inheritdoc/>
public Task<List<global::ZB.MOM.WW.OtOpcUa.Driver.Historian.Wonderware.Backend.HistorianEventDto>> ReadEventsAsync(
string? sourceName, DateTime startTime, DateTime endTime, int maxEvents, CancellationToken ct = default)
=> throw new NotSupportedException();
/// <inheritdoc/>
public HistorianHealthSnapshot GetHealthSnapshot() => throw new NotSupportedException();
/// <inheritdoc/>
public void Dispose() { }
}
}
}