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

204 lines
22 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# H4 evidence — remote-history diagnostics, metrics, docs (capability "supported")
Phase H4 of `docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md` (revision 7), 2026-11-24. History part only;
the alarm diagnostics are A4.
## What changed
- **`Runtime/DataConnections/DataConnectionHistoryDiagnostics.cs`** (new, DI singleton, no dependencies): shared by the origin
services (`LocalDataServices`), the consumer gateway (`ProjectedHistoryAccess`) and the diagnostics readers
(`DataConnectionDeploymentRuntime`, `DriverHostActor`), so none of them depends on another (the origin composition is resolved
lazily after the driver host exists; a direct dependency would be a cycle).
- **Metrics** on `OtOpcUaTelemetry.Meter` (`ZB.MOM.WW.OtOpcUa`, already in the host's exported-meter allowlist), no ids in labels:
- `otopcua.dataconn.history.reads{variant,status_class,side}` — origin: one per item per wire call served to a peer (review 3);
consumer: one per projected node per local HistoryRead, with the status the client got (review 1).
- `otopcua.dataconn.history.continuations.active{side}` — observable gauge over the live diagnostics instances (weak table).
- `…operations.unknown_bits_dropped`: **reused, not added.** X0's `otopcua.dataconnection.unknown_operations_dropped{kind}`
counts exactly that (one per row per accepted artifact change); a second instrument would double-count. Pinned by
`The_plan_unknown_bit_counter_is_the_existing_X0_instrument_not_a_second_one`.
- **Defect found: the H2 origin counter was never exported.** `otopcua.dataconn.history.reads` sat on a private
`Meter("ZB.MOM.WW.OtOpcUa.DataConnections.History")` that is not in `ObservabilityExtensions.ObservedMeters` (a strict
allowlist), so it was absent from `/metrics` and OTLP. It now lives on the OtOpcUa meter (verified on the live rig's `/metrics`).
- **Consumer evidence per connection** (`ProjectedHistoryAccess`): answers by status class, attributed to the connection the
node resolved to; open consumer continuations — a `RemoteCursor` counts from creation until it is claimed for a resume (new
`ProjectedHistoryContinuation.OnClaimed` hook) or its origin token is released, whichever first, once.
- **Origin evidence per node** (`LocalDataServices.HistoryDiagnostics` init property): backend present, live peer history sessions,
open origin continuations, answers by status class.
- **Negotiated features** (`GrpcDataConnection.RecordSelected`): `RequestedFeatures(capabilities)` and the advertised history
variants + aggregate count.
- **Contracts** (Commons, additive optional members — older senders give null = "unavailable"):
`DataConnectionDiagnosticsSnapshot` + `NegotiatedFeatures, HistoryVariants, HistoryAggregateCount, HistoryReads{Good,Uncertain,Bad},
OpenRemoteContinuations`; new `OriginHistoryDiagnostics`; `NodeDiagnosticsSnapshot.OriginHistory`.
- **AdminUI** (`ClusterDataConnections.razor`, already inside `<PageErrorBoundary>`; helpers in `DataConnectionDiagnostics`): per
connection a history line (negotiated features, origin history advertised, projected reads by class, open remote continuations)
and a dropped-unknown-bits line; a new **Origin evidence by node** panel (remote history served, peer sessions, open origin
continuations, answers by class, exports with dropped bits). Dropped bits are named when the AdminUI knows the bit, hex otherwise,
and carry a "node build is older than the authored feature" hint when non-empty.
- **#919 closed by this work:** the X0 fields (`DroppedUnknownOperations`, `MappingsWithDroppedOperations`,
`DroppedExportOperations`) are now rendered on the data-connections page.
- **Docs:** `DataConnections.md` (remote history **supported**, SqlServer/QuestDB verified, Gateway unverified pending #923;
new §"Remote history diagnostics and metrics"; #919 note under Mixed versions), `Historian.md` (§"Remote history over data
connections"), `Client.CLI.md` (projected-history note: opaque `p1.` ids resolved by browse, re-browse after deploy/idle, paging
flags, what is refused).
## Tests (H4 manifest key)
| Suite | What |
|---|---|
| R `GrpcDataHistoryMetricsTests` (5, new) | counter on the exported meter with exactly `variant,status_class,side` (no id); gauge reports both sides; per-connection counts case-insensitive, settle never negative; origin evidence null until attached / when its probe throws; unknown-bit counter is X0's |
| R `GrpcDataConfiguredDiscoveryWireTests` H4 (2) | real consumer SDK session + real projection + real origin: page 1 ⇒ consumer `(1,0,0,open 1)` and origin open 1; resume ⇒ `(2,0,0,open 1)`; `releaseContinuationPoints` ⇒ consumer open 0, origin 0 after the coalesced release; an origin-refused aggregate ⇒ one Bad each side; session close ⇒ consumer open 0 |
| R `GrpcDataDeploymentActivationTests` H4 (1) | runtime diagnostics carry per-connection counts (zeros, not null, without traffic; null when no diagnostics wired) |
| AdminUI `GrpcDataHistoryDiagnosticsDisplayTests` (5, new) | features / history-served / counts / dropped-bit rendering (#919) and the older-build hint |
| plus existing | `GrpcDataProjectedHistoryCursorTests`, `GrpcDataOriginHistorySessionTests`, OpcUaServer `ProjectedHistoryReadTests` (base class gained `OnClaimed`), AdminUI `GrpcDataDiagnosticsTests` |
Red/green: with `RemoteCursor.OnClaimed => Settle()` reverted, the wire test fails at the resume step (consumer open 2, not 1).
## Gates
| Gate | Result |
|---|---|
| `dotnet build ZB.MOM.WW.OtOpcUa.slnx` | 0 warnings, 0 errors |
| `run-unit-phase.py H4` (new key: Runtime 25, OpcUaServer 11, AdminUI 9) | passed |
| `run-unit-phase.py H3` / `H2` / `H1` / `X0` | all passed (H3 107 + 144; H2 44/36/7/40/96/25; H1 578 + 17; X0 25/14/5/72/11) |
| AdminUI.Tests (`Category!=E2E&Category!=LiveIntegration`) | 2698 passed |
| Runtime.Tests (same filter) | 1911 passed, 3 skipped |
| OpcUaServer.Tests (same filter) | 1419 passed, 1 skipped |
## Live gate — H3 scenarios on SqlServer with the metrics and the page
Fresh run `h4a-sqlserver` (OrbStack, macOS, normal build-hash checks, 2026-11-24, between ~13:01 and ~13:14 UTC):
`rig.py up --history --history-backend sqlserver --timeout 900`, `seed`, ~80 s, `deploy --timeout 300`, `history_gate.py`, `down`.
- **H01–H06 all PASS** (47 / 34 / 35 / 71 / 58 / 238 assertions, every scenario restored).
- **`/metrics` before traffic:** both continuation gauges 0 on every node; no reads series.
- **`/metrics` after the gate:** consumer-1 `reads{side=consumer}` raw good 31, raw bad 2, processed good 1, processed bad 1,
attime good 2; source-2 (primary after H04's failover) `reads{side=origin}` raw good 7, raw bad 2. (The CLI's comparison reads on
the SOURCE primary are local OPC UA reads and are not counted, as designed; source-1 restarted in H04, so its counts restart.)
- **AdminUI page** (`http://<control-1 admin>/clusters/CONSUMER/data-connections`, login disabled on the rig, prerendered HTML via
`urllib`): consumer-1 `Ready · endpoint https://source-2:4057 · serving source-2 · role Primary`, "Negotiated features History ·
origin history raw, processed, attime (19 aggregates) · projected history reads good 34 · uncertain 0 · bad 3 · open remote
continuations (local sessions) 0" — equal to the sum of consumer-1's metric series; "Dropped unknown operation bits: connection
none · mappings with dropped bits 0". The SOURCE page's origin panel: source-2 "remote history served · peer history sessions 0 ·
open origin continuations 0 · history items answered good 7 · uncertain 0 · bad 2" — equal to source-2's metric.
- **Held continuation probe** (a scratch script driving the gate's own `HistoryGate.held` on the projected raw `counter`, page size 3,
pause after page 1): while held — consumer-1 gauge `consumer=1`, source-2 gauge `origin=1`, the CONSUMER page "open remote
continuations (local sessions) 1", the SOURCE page "peer history sessions 1"; after resume to completion — both gauges 0, page 0,
projected good 35 ⇒ 54 (19 pages).
- Mid-gate the page showed the connection `Connecting` with features "unavailable" — taken during a scenario's redeploy/failover;
after the gate it read `Ready` with features `History`.
- `down` ⇒ 0 run containers, 0 run volumes.
## Gateway leg (#923) — PASSED 2026-11-28
First run 2026-11-24 was blocked (VPN down; the docs were scoped to SqlServer/QuestDB pending #923). Run 2026-11-28 with the VPN
up (`wonder-sql-vd03` :32565 and :1433 reachable).
**Posture — read-only end to end.**
- **Gateway:** a separate, local HistorianGateway instance (`historiangw` `main` at `6a74f1e`, freshly published), compose project
`zb-historiangw-923`, ports bound to the host **loopback only** (`127.0.0.1:5231` gRPC h2c, `:5230` health), its own fresh volume.
`ApiKeys:Mode=Disabled` (the issue's posture — no key minted, no key store touched), `Historian:LiveWritesEnabled=false`,
`RuntimeDb:Enabled=false` / `EventReadsEnabled=false` (no SQL write or event path), Redundancy/StoreForward off. Historian
credentials from the existing gitignored `histgw.secrets.env`; the long-running `zb-historiangw` container was left untouched, and
nothing in the HistorianGateway repo changed (published into a scratch build context).
- **Origin (SOURCE pair):** `ServerHistorian:Backend=Gateway` → `http://host.docker.internal:5231` (`UseTls=false`),
`ProvisionTags=Off`, `ContinuousHistorization:Enabled=false`, a placeholder key (the client refuses an empty one; a Disabled
gateway never checks it). The fixture's historized tags are bound **`historianReadOnly`** (#899) to existing AVEVA system tags:
`counter` (UInt16) → `SysTimeSec` (UInt2, 1 Hz), `flt` (Float32) → `SysDataAcqOverallItemsPerSec` (Float, 10 s), `text` (String)
→ `SysString`.
- **Evidence it stayed read-only:** the strict-ceiling gateway's log (it logs each RPC) shows only `HistorianRead/ReadRaw` (180) and
`HistorianStatus/Probe` (16) — no `WriteLiveValues`, `EnsureTags`, `SendEvent(s)` or `AddHistoricalValues`; the SOURCE logs carry
no provisioning or recorder line. (The first gateway container's log was dropped when it was recreated for the ceiling leg.)
**Rig support** (commits `a6ae08146`, `6ab7050c3`, `7d9818cf1`): `rig.py up --history --history-backend gateway` layers the new
`compose.history.gateway.yml`; the endpoint allowlist admits `http://host.docker.internal:<port>` **only** under
`ServerHistorian__Endpoint` on a gateway run (`HostGatewayEndpointTests`, with a positive control); `up` fails before any build when
nothing listens on the loopback port; the seeder takes `GRPC_DATA_HISTORY_GATEWAY_TAGS` (`name=historianTag,…`). `history_gate.py`
on the gateway uses a fixed past window (120 s ending 15 s ago — nothing is accumulated), adds **H07** (reverse + end-only,
gateway-only) and **H08** (strict ceiling, run alone with `--gateway-ceiling C`), and stores the unconstrained answers in
`H-gateway-baseline.json` for H08 to compare with.
**Run `h923b-gateway`** (OrbStack, normal build-hash checks, window `16:38:04Z–16:40:04Z`):
| ID | Result |
|---|---|
| H01 Raw paging, Raw + UNS | PASS (75): page size 3 ⇒ 40 pages, **120 rows per realm** (SysTimeSec 4…3), last page no CP, row-for-row = origin; single read = origin; Float32 12 Good Singles (42.527664, 64.76546, …) = origin |
| H02 Processed | PASS (34): Average on String `text` ⇒ `BadAggregateNotSupported` both sides (refused unsent, #897); Average 10 s on `counter` 12 intervals = origin (raw-evaluated on the Gateway, #681) |
| H03 AtTime | PASS (35): `counter` 7/11/15 `UInt16` = origin; Float32 at +2 s / +20 s 42.527664 / 59.027344 (interpolated) Good `Single` = origin |
| H04 failover | PASS (71): page 1 held, `source-1` stopped ⇒ `source-2` primary, resumed page `BadContinuationPointInvalid`, fresh read Good |
| H05 not advertised | PASS (58) |
| H06 | PASS (238): unhistorized vs origin-denied identical `0x80720000`; local deny `BadUserAccessDenied`; origin continuations 1 held ⇒ 0 after session close; rebuild mid-page ⇒ invalid, fresh Good |
| H07 reverse / end-only | PASS (43): reverse (`start = W1 > end = W0`) paged by 7 (18 pages) and whole: 120 rows **(W0, W1]** newest first (16:40:04 … 16:38:05) = origin = an independent forward read reversed; end-only (`StartTime` unspecified, `EndTime = W1`, page 5, max 20): 4 Good pages, the latest 20 rows at/before W1 (16:40:04 … 16:39:45) = origin = the forward reference |
| H08 strict ceiling | PASS (41), gateway recreated with `MaxValuesCeiling=40`, `AllowStreamingBeyondCeiling=false` (⇒ page limit L = 24): one read capped at 1000 returns all 120 baseline rows on the origin and through the projection; 100-row pages come back **23, 22, 22, …** (6 pages, = L − 1 then L − k − 1, #694) and equal the baseline; reverse 100-row pages likewise ceiling-sized and = baseline; end-only = baseline; AtTime = baseline; raw-evaluated Average over the 120-row window ⇒ `BadTooManyOperations` on **both** origin and projection (the documented #691.3 rule: a ceiling-bounded stream not provably complete is refused, never truncated) |
Teardown: `rig.py down`, `docker compose down -v` for the gateway; 0 run containers / volumes left; lock released.
**Gate corrections found by the run (harness, not product):**
- The first H07 draft compared a reverse read with the forward `[W0, W1)` rows reversed. Part 11: a reverse read's StartTime (the
later bound) is inclusive and EndTime exclusive, so the answer is `(W0, W1]` — the projection and the origin agreed; the reference
was wrong. Now built from an independent forward read past W1.
- H01's UNS leg was refused `BadUserAccessDenied` on one run: the UNS node sat idle past its 15 s metadata lease during the longer
(40-page) raw leg — **#922** exactly. The gate now renews before the UNS leg (deploy + re-browse, the documented workaround).
**Seen once, not reproduced (control plane, backend-independent — reported, not fixed here):** in one full run H06's rebuild deploy
got HTTP 500 from CONTROL's `/api/deployments` — `AskTimeoutException` after 10 s in `AdminOperationsClient.StartDeploymentAsync`.
The deployment WAS composed (row `CreatedAtUtc` 16:35:49.954, request at 16:35:39.48, applied and sealed right after), i.e. the
compose itself (Serializable transaction + snapshot + `DraftValidator`) took ~10.5 s where the other ~30 deploys of the run took
60–630 ms. No SQL autogrow in the default trace and nothing in `system_health`; the cause is not established. The caller sees a
500 for a deployment that then goes ahead. Proposed follow-up below (coordinator to file).
## Review (Fable, approve-with-changes) — fixes
One focused commit per item (5 and 6 share one AdminUI commit). Red/green by reverting the fix and re-running its test, unless noted.
| # | Finding | Resolution | Red/green |
|---|---|---|---|
| 1 should-fix | Consumer reads were counted from the gateway's outcomes: the non-local and batch limiter `BadTooManyOperations`, the pre-call `BadTimeout` and the count-mismatch `BadInternalError` were never counted, and a serve-time throw after the gateway returned counted Good | The node manager counts where each projected status is set (`Refuse` + the served path) and hands the request's answers to `IProjectedHistoryAccess.RecordAnswered` (default no-op) in a `finally`; a fault escaping to the SDK (the service fails) counts every projected node of the request Bad. Attribution to a connection via `ProjectedDataAccess.ConnectionOf` (best effort, no authorization). Variant gains `modified`. `2f11a9c60` | O `Every_projected_answer_is_recorded_once_with_the_status_the_client_sees` (served, unknown aggregate, modified, non-local limiter saturated, batch limiter saturated, spent deadline, count mismatch, serve-time throw) — red with the non-local limiter refusal routed back to the uncounted path |
| 2 should-fix | `CaptureOrigin` null until the first peer call composes the origin services ⇒ a fresh H4 origin read like a pre-H4 build | Eager resolution is not clean: `LocalDataRuntimeComposition` needs the driver host actor registered and is composed by the first peer call through `DeferredFactory`. Instead the DI singleton gets a provisional probe of the same `DeferredOriginHistoryPort` (backend availability) and reports zeros with `NoPeerTrafficYet = true`; the page adds "no peer has called since start". Docs updated. `005720bd0` (+ rename in `7498f1ce8`) | R `Before_any_peer_call_a_provisional_origin_reports_no_peer_traffic_yet_not_unavailable`; live (below) |
| 3 nit | Origin reads count wire calls (chunk-token follow-ups count again) | Kept per call; docs, the class remarks and this file say "per item per wire call". `b5509dfc4` | — (doc) |
| 4 nit | `OpenContinuations = Cursors.Count + ChunkCount` double-counted a chunk holding its page cursor | `OriginHistorySession.OpenContinuations` counts chunks + cursors − cursors referenced by a live chunk (`OriginHistoryCursors.Contains`). `79cf50d50` | R `Open_continuations_count_a_chunk_holding_its_page_cursor_once` (3, was 4) — red on revert |
| 5 nit | `HistoryServed` said "not advertised" with no handshake evidence | "unavailable" when both `NegotiatedFeatures` and `HistoryVariants` are null. `2fba03617` | AdminUI display test (new assertion fails against the previous helper by inspection) |
| 6 nit | `Features()` hid unknown bits beside a known one; `DroppedBits` scanned bits 0–30 | Both render every set bit of all 32, named when known, hex otherwise. `2fba03617` | AdminUI display tests: `History, 0x8`, `0x80000000`, `HistoryRead, 0x80000000` (fail against the previous helpers by inspection) |
| 7 nit (tests) | No unit round-trip of the snapshot on the cluster serializer; no mixed-version payload | `GrpcDataDiagnosticsSerializationTests` round-trips a `NodeDiagnosticsSnapshot` with every H4 member through `Sys.Serialization.FindSerializerFor` (Akka's default JSON serializer — the fleet-diagnostics Ask has no custom binding), and decodes payloads stripped of the H4 members (null = "unavailable"). **Found by it:** Newtonsoft fills a missing constructor argument with the CLR default, not the C# default — the item-2 flag, first named `PeerServicesStarted = true`, would have decoded `false` from a sender without it; renamed `NoPeerTrafficYet` (default false) with a test. Also: a C# collection expression typed `IReadOnlyList<T>` is a synthesized type Newtonsoft cannot construct — production builds arrays (checked), the test fixture uses arrays. `7498f1ce8` | new tests |
Left as notes (no code change, per the review):
- `OriginHistoryPort._serving` caches an unsynchronised nullable tuple — a pre-existing benign race (two callers may both compute
it); H4 adds the metrics scrape thread as a caller through `HistoryServing`.
- `DataConnectionHistoryDiagnostics._consumer` is never pruned; bounded by the deployed connection ids a process has seen.
**Gates after the review fixes** (HEAD `7498f1ce8`), run one at a time: build 0 warnings / 0 errors; `run-unit-phase.py` H4
(9 + 12 + 29), H3 (107 + 145), H2, H1, X0 all passed; AdminUI.Tests 2698; Runtime.Tests 1915 (+3 skips); OpcUaServer.Tests 1420
(+1 skip) (`Category!=E2E&Category!=LiveIntegration`); no `GrpcDataConfiguredDiscoveryWireTests` (#920) failure.
**Live re-run** (fresh `h4b-sqlserver`, 2026-11-24): items 1 and 2 changed runtime behaviour (the consumer count moved into the node
manager; a new DI-built provisional origin state), so the SqlServer leg was re-run.
- Right after deploy, before any history traffic, the CONSUMER page's origin panel showed consumer-1/2 "remote history no historian
backend · peer history sessions 0 · open origin continuations 0 · … · no peer has called since start", and source-2 (no peer
call yet) "remote history served · … · no peer has called since start" — where `h4a` had shown "remote history evidence
unavailable" (item 2).
- H01–H06 **all PASS** (47 / 34 / 35 / 71 / 58 / 238, all restored).
- After the gate: consumer-1 page "projected history reads good 36 · uncertain 0 · bad 3" = its `reads{side=consumer}` series
(raw good 33, processed good 1, attime good 2; raw bad 2, processed bad 1); source-2 page "good 7 · bad 2" = its origin series.
- Held probe: while held, consumer gauge 1, source-2 origin gauge 1, page "open remote continuations (local sessions) 1" and
source-2 "peer history sessions 1"; after resume to completion all 0, projected good 37 ⇒ 56.
- `down` ⇒ 0 run containers, 0 run volumes.
## Not verified / notes
- **Gateway backend** remotely: verified 2026-11-28 (#923, above). Not covered there: tie clusters (the bound AVEVA tags store one
value per timestamp and the leg cannot write one), Gateway events history (never served remotely), the native TimeAverage/Total
modes through a projection (H02 reads Average only).
- **QuestDB** was not re-run for H4: the H4 change is backend-independent (counting around the same port), and the H3 rounds
passed H01–H06 on QuestDB at `713cbfb21`. The brief asked for one SqlServer leg.
- **Browser-rendered** page not driven (no Chrome session used); verified from the server-prerendered HTML, which runs the same
`OnInitializedAsync` + render as the interactive circuit.
- **Akka serialization**: now unit-tested (review 7) as well as exercised live.
- **Deviation:** the reads counter carries a third label `side` (origin | consumer) beyond the plan's `{variant,status_class}` —
a node can be both, and without it the two populations would be summed into one series. The gauge carries `side` too.
- Consumer counts cover every projected node that reaches the projected half (review 1). A node the SDK or the node manager's
authorization refuses before the split (no local HistoryRead grant ⇒ `BadUserAccessDenied`; not Historizing ⇒
`BadHistoryOperationUnsupported` from the SDK's access-level check) is not counted: it never reaches the projected half.
- Counts are since process start (no persistence), as the docs say.
- `GrpcDataConfiguredDiscoveryWireTests` (#920 flaky class): no failure in any run this phase (H4 manifest, H3 manifest, full Runtime suite).
- Umbrella history entry (plan exit gate): **not done here** — it is a commit on `scadaproj` `main` plus a push, and this worktree brief forbids pushing; left to the orchestrator (append to `../scadaproj/.claude/skills/sister-project-history/otopcua.md`). The Gitea close of #919 likewise belongs with the merge.