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

144 lines
16 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.
# H2 evidence — wire, ingress, client, schema (first deployable increment)
Phase H2 of `docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md`, 2026-11-23.
## What changed
- **Contract (§4.2, field numbers as planned).** `rpc HistoryRead`, `HistoryReadRequest/Item/Result/Response`,
`HistorySample`, `RawDetails/ProcessedDetails/AtTimeDetails`, `AggregateConfiguration`,
`CapabilitiesResponse.history = 16` (`HistoryCapabilities`), `Metadata.history = 14` (`HistoryInfo`). §4.2 left
`HistoryReadItem`, `HistoryReadResponse`, the `HistoryCapabilities` field numbers and `AggregateConfiguration` unnumbered;
they are `HistoryReadItem{correlation_id=1, view=2, optional bytes continuation=3}`,
`HistoryReadResponse{items=1, serving=2}`, `HistoryCapabilities{raw=1, processed=2, at_time=3, aggregates=4,
timestamp_resolution_ticks=5, max_values_per_page=6, max_concurrent_reads=7, continuation_idle_ticks=8}`,
`AggregateConfiguration{use_server_capabilities_defaults=1, treat_uncertain_as_bad=2, percent_data_bad=3,
percent_data_good=4, use_sloped_extrapolation=5}`. Aggregate names are the `HistoryAggregateType` names; the name ↔ ns=0
id table (`DataHistoryAggregates`) is pinned to the server's `AggregateFunctionMap` by `OriginHistoryPortTests`.
`DataHistoryAtTimeDetails` gained `UseSimpleBounds` (carried verbatim; the origin's AtTime evaluator applies its own rules).
- **Negotiation (coordinator decision, recorded in plan §4.1).** The `GetCapabilities` probe always carries the features
the consumer supports (`history`). The server advertises field 16 and bit 32 only when the probe asked for `history` AND
the origin has a historian backend. Every other call carries the negotiated set (consumer ∩ what that endpoint
advertised). The server's effective set = header ∩ `SupportedFeatures` (History) ∩ origin-servable. Without it:
capabilities, Browse and GetMetadata responses are stripped to the v1 shape (no field 16/14, no bit 32), and
`HistoryRead` is `FAILED_PRECONDITION("feature not negotiated")`. The decoder drops bit 32 when field 16 is absent.
- **Origin ingress** (`LocalDataServices.History.cs`). Order: target ready and role allowed (ReadyReplica allowed), the
RPC-level `Ready(…, HistoryRead)`, then per item: view resolves to an exported value node → export grant + origin ACL
`HistoryRead` (`Allowed`, which always walks the origin ACL) → tagname (`IOriginHistoryPort.IsHistorized`). Every
refusal is the same `Bad_HistoryOperationUnsupported` with no diagnostic and no backend call (byte-identical on the wire,
`Denied_and_unhistorized_and_unknown_are_byte_identical…`). Authority is re-checked after the backend answers.
Metadata `historizing` = historized AND granted, so metadata does not separate them either.
- **Limits** (bounded per request and per principal since review fix 1, below). Per-principal admission (`MaxConcurrentHistoryReads` ⇒ every item `BadTooManyOperations`); Raw pages at
`MaxHistoryValuesPerPage` (0 or more ⇒ the ceiling, with a continuation); answers above
min(`MaxHistoryResponseBytes`, listener max) − 64 KiB are split into chunks (`chunk_continues`) held as single-use
remainders in the session; a remainder the session cannot hold is `BadTooManyOperations`, never a truncation.
- **Facade, not InternalsVisibleTo.** `OpcUaServer/OriginHistoryPort.cs` (`IOriginHistoryPort`, `OriginHistoryCursors`)
keeps SDK types inside OpcUaServer; exposed through `SdkAddressSpaceSink`, resolved by `DeferredOriginHistoryPort` once
the SDK server is up. `ReadAsync` runs the synchronous `ReadHistory` on `Task.Run`.
- **Store/scope lifecycle.** One `OriginHistorySession` (H1 `PeerHistoryContinuationStore` + chunk remainders) per
(principal, API key, credential version, transport channel). The gRPC channel is the HTTP/2 connection
(`HttpContext.Connection.Id`), cleared when Kestrel's `IConnectionLifetimeFeature.ConnectionClosed` fires (idle expiry
60 s is the backstop; the hook is proven on a real Kestrel HTTP/2 host); a direct `LocalDataConnection` is its own
channel, cleared on `DisposeAsync`. Bounded at 64 sessions per principal and 4096 overall (review fix 5). ONE `PeerHistoryContinuationScope` per request; the serving incarnation it
snapshots is `incarnation/serving-generation/role`, so a restart, failover or role change invalidates tokens. A miswired
scope ⇒ `BadInternalError` + "Origin history continuation wiring fault." + an error log — never unsupported/denied.
- **Consumer** (`GrpcDataConnection.History.cs`). `IDataHistoryService` implemented explicitly (`ReadHistoryAsync` /
`ReleaseHistoryAsync` are the public names — an implicit `ReadAsync(DataHistoryReadRequest)` made every
`ReadAsync(new(...))` call site ambiguous). Deadline per call = min(remaining, `HistoryTimeoutMilliseconds`);
`FAILED_PRECONDITION`/`UNIMPLEMENTED` ⇒ `Bad_HistoryOperationUnsupported`; chunks assembled within the request
`MaxBytes` (past it ⇒ `BadTooManyOperations`). Page tokens are wrapped with the issuing endpoint index + serving
incarnation: a resumed read never moves endpoint and is `BadContinuationPointInvalid` without a call when that endpoint's
incarnation changed; a fresh read may move. `DataConnectionDeploymentLease` gates history on the row's `HistoryRead`.
- **Grow sites.** `DataOperationSets.Understood`, `DataConnectionValidator` known set, `LocalDataServices.Implemented(target)`
(only while a historian backend is configured) all gain `HistoryRead`; `DataOperationPolicy` maps OPC UA HistoryRead →
the mapping's `HistoryRead` bit. `ProjectedDataAccess.cs:157` is untouched (H3).
- **Schema.** `20261124013651_AddDataConnectionHistory`: `DataConnection.HistoryTimeoutMilliseconds` (30000),
`DataExport.MaxConcurrentHistoryReads` (4), `MaxHistoryValuesPerPage` (10000), `MaxHistoryResponseBytes` (4194304),
`RemoteNamespaceMapping.MaxHistoryAssemblyBytesPerRequest` (16777216); NOT NULL with those SQL defaults, check
constraints widened (`> 0`). Artifact rows are entity JSON, so the fields project with no code change (a pre-H2 artifact
parses with the defaults); `DataConnectionScopeRevision` includes `HistoryTimeoutMilliseconds`.
- **AdminUI.** HistoryRead checkbox + the five limit fields on the connection/export/mapping editors
(`DataOperationAuthoring`), and the banner "Every node of both clusters must run X0+ before authoring this…" whenever a
post-v1 bit is ticked. `<PageErrorBoundary>` kept.
- **Found on the way:** `DataConnectionEndpoints.Methods` (the listener's method allowlist) did not include the new RPC, so
the auth middleware rejected every HistoryRead before the service saw it.
## Review fixes (Fable, approve-with-changes)
| # | Finding | Resolution |
|---|---|---|
| 1 | Origin memory unbounded | Nodes are read in sub-batches sized so one sub-batch at the per-page ceiling fits the response budget; once the budget is spent no further sub-batch starts. Unread nodes get a **deferred** chunk token (transport; on resume the node is read from its original continuation — any variant, not only Raw) or `BadTooManyOperations` (direct consumer). Processed intervals and AtTime times above `MaxHistoryValuesPerPage` are `BadTooManyOperations` unsent. Remainder bytes (encoded `CalculateSize`) are charged to a per-principal budget across sessions = concurrent reads × max(response budget, page × 64 B); past it a node is `BadTooManyOperations`. Proven by `Origin_memory_is_bounded…` (100 nodes × uncapped Raw: ≤ 10 nodes materialised per response, retained bytes ≤ budget at every step, every value delivered exactly once); a mutation removing the stop makes it fail |
| 2 | Not-ready origin ⇒ "unsupported" | `CapabilitiesResponse.history` is present whenever the origin has a historian; `Ready(…, HistoryRead)` answers Unavailable (not ready / demoted) or PermissionDenied (no export grant), so the client fails over like v1 Read |
| 3 | Client exceptions escape | Malformed/undecodable answers are endpoint failures (a fresh read moves on); resumed items ⇒ `BadContinuationPointInvalid`, fresh items of the same batch ⇒ `BadNoCommunication`; caller cancel throws; the deployment lease maps inner/scope faults to `BadNoCommunication` |
| 4 | HistoryTimeout capped by the origin's UnaryTimeout | Origin `Cancelled` without a caller cancel ⇒ `BadTimeout`, no endpoint failure recorded; the cap is documented next to the AdminUI field and in `DataConnections.md` |
| 5 | One principal can evict others | 64 sessions per principal (its own LRU evicted first); at the global 4096 the principal holding the most pays; a release never creates a session |
| 6 | Per-node rebuilds | `Implemented(target)` once per node, ACL before tagname; `OriginHistoryPort.Serving` cached per historian source instance (`A_v1_metadata_call_does_not_rebuild…`) |
| 7 | Mapped HistoryRead authorisable | Pinned: a real SDK HistoryRead on a projected variable with the mapping bit and a local HistoryRead grant is `Bad_HistoryOperationUnsupported`, no data, no continuation (projected nodes carry no HistoryRead access-level bit until H3) |
| 8 | Scope fingerprint | Limits ride the artifact's entity JSON like `TimeoutMilliseconds`; `HistoryTimeoutMilliseconds` removed from `DataConnectionScopeRevision` (no upgrade scope bump); plan §6 corrected |
| 9 | Nits | Upper bounds (timeout 1 h, reads 64, values/page 1,000,000, response 64 MiB, assembly 1 GiB; validator + AdminUI `max`); encoded sizes; a single oversized value is a per-item `BadTooManyOperations`; discovery backoff on the history path; a fresh read tries the next endpoint when one lacks history; channel-close registrations unregistered; remote reads hold at most N − max(1, N/4) of the node manager's N history batch slots (`OriginHistoryLimiterTests`). `UseSimpleBounds` is **kept on the wire** (it is in the §4.2 contract) but not plumbed: the H1 port's AtTime variant has no such flag and the evaluator applies its own bounds rule — documented as carried and ignored |
| 10 | Kestrel close hook | Proven with a real in-process Kestrel HTTP/2 (h2c loopback) host: `IConnectionLifetimeFeature.ConnectionClosed` is exposed on the stream context and disposing the client connection clears the session |
**Flake check (coordinator request).** `GrpcDataConfiguredDiscoveryWireTests` ×10 on this branch: 6 clean runs;
`Failed_sdk_item_construction_releases_candidate_and_fanout_ownership` failed 2/10, `New_primary_renews_same_monitored_item_after_a_prior_mapped_read(warmByRead: True)`
1/10, `Two_sdk_cadences_renew_before_expiry_without_reviving_old_notification_evidence` 1/10. Master (coordinator, 14 runs)
failed `Bad_null_sdk_notification_cannot_borrow_unproven_sample_evidence` 2/8. The `Failed_sdk_item…` path uses an origin
fixture without a history port and a direct (non-gRPC) peer connection, so no H2 history code, probe header or capability
change is on it; the only H2 delta it sees is the extra (null) `DataMetadata.History` field. Its assertion compares the
shared projected candidate budget's `RetainedEntries` before and after a failed second item while the first item stays live;
a candidate the live item holds between sampling ticks (`WarmStandby.AddCandidate`) makes it 1 at the second read — a race
in the test, not an H2 cause. Not changed here (the class flakiness is the coordinator's issue).
## Recorded-v1-client gate
Both gates extended per X0.md §2 BEFORE asserting, goldens untouched (`git diff master -- …Goldens.cs` is empty):
- `GrpcDataV1CompatibilityTests` (fake origin): the origin now grants HistoryRead, advertises `HistoryCapabilities`
and marks its scalar `HistoryInfo(true)`. Header-less ⇒ golden bytes on all six RPCs. With `history` on a
history-capable origin ⇒ field 16, bit 32 and `Metadata.history` appear (`H2_a_history_capable_origin…`); with
`history,conditions` on an origin without history, or `conditions` alone ⇒ golden bytes.
- `GrpcDataV1RealOriginCompatibilityTests` (#918, real `LocalDataServices`/`LocalExportCatalog`): every export also grants
HistoryRead and the origin has a historian (`FakeHistoryPort`: Flow + FlowRate historized). Header-less ⇒ golden bytes on
all seven scenarios; the history shapes are present with the header (`GrpcDataHistoryWireTests`).
## Gates (after the review fixes)
| Gate | Result |
|---|---|
| `dotnet build ZB.MOM.WW.OtOpcUa.slnx` | 0 warnings, 0 errors |
| `run-unit-phase.py` H2, X0, H1, P01–P09 | all passed (H2 includes both recorded-v1-client gates) |
| Full unit suites (`Category!=E2E&Category!=LiveIntegration`) | Commons 505, Configuration 323, Core 385 (+1 skip), OpcUaServer 1407 (+1 skip), Runtime 1856 (+3 skips), Host 476, AdminUI 2693 — all green; Core.Abstractions 853 (unchanged since the first run) |
| Migration up/down/up on SQL Server (`10.100.0.35,14330`, scratch DB, then dropped) | passed; the five SQL defaults verified in `sys.default_constraints` |
**Earlier Runtime failure (first full run).** `Failed_sdk_item_construction_releases_candidate_and_fanout_ownership` fails about 1 in 3
runs of its collection (`projected candidate budget RetainedEntries should be 0 but was 1`) and passes alone and in the
P-phase gates. Its origin (`LocalDataFixture`) has no history port, so no H2 history shape is emitted on its path; the
only H2 change it sees is the capabilities probe carrying `x-otopcua-data-features: history` (answered v1-identically).
Not reproduced on master here (no second checkout from this worktree) — coordinator to confirm it is pre-existing.
## Docker-dev smoke recipe (direct runtime-consumer read; run by the coordinator)
1. Origin cluster: a historian backend (`OTOPCUA_HISTORIAN_BACKEND=SqlServer` + `docker-compose.questdb.yml` or the SQL
recipe in `docs/Historian.md`), `DataConnections__Enabled=true` on both clusters, a historized raw tag
(`"isHistorized": true`) with some recorded history.
2. AdminUI `/clusters/{origin}/data-connections`: an export (Raw, the tag's ancestor) for the consumer's service principal
with Browse/Metadata/Read/**HistoryRead** — the banner appears. On the consumer: a connection with **HistoryRead**
(keep `HistoryTimeoutMilliseconds` 30000). Deploy both.
3. Probe the origin listener directly (the harness probe `scripts/validation/grpc-data/probe` or grpcurl with
`src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/data_connection.proto`), headers `authorization: Bearer <service key>`,
`x-data-target-mode`, `x-data-consistency`, `x-data-cluster-id`, `x-data-node-id`:
- `GetCapabilities` with `x-otopcua-data-features: history` ⇒ `history` present, `operations` has 32; without the header ⇒ neither.
- `HistoryRead` with the header, `raw{end=<now>, num_values_per_node=5}` on the tag's view ⇒ Good, ≤ 5 newest values
newest-first plus a `continuation`; resume it once ⇒ the next page; resume the same token again ⇒ `0x804A0000`.
- The same on an unhistorized tag, and with the export's HistoryRead unticked on a second key ⇒ identical
`0x80720000` results; without the header ⇒ `FAILED_PRECONDITION`.
4. Consumer side: a runtime consumer holding the deployed connection (`IDataConnectionDeploymentSource` lease) calls
`IDataHistoryService.ReadAsync` with the same window ⇒ the same rows/statuses as step 3 / an OPC UA historyread on the
origin node.
## Not verified
- The docker-dev smoke above (coordinator-run).
- The real `OriginHistoryPort` behind the gRPC service end to end: the wire suite fakes the port; the port facade is
tested against a real node manager separately (`OriginHistoryPortTests`).
- A consumer projection (H3) receiving negotiated metadata with bit 32/`HistoryInfo` from an H2 origin: covered only by
the decoder tests; the projection still ignores both until H3.