# gRPC data connections Data connections expose current Raw and UNS data between explicitly configured nodes or clusters. The contract supports capabilities, browse, metadata, cached reads, writes and data-change subscriptions. It is independent of the existing mesh command, telemetry, configuration and pair-sync planes. An Akka pair continues to own its local field-device drivers; importing a peer's data does not start another device driver or join the peer's gossip ring. ## Configuration and deployment A connection is directional. Configure each direction separately when both sides need imports. The deployed configuration uses three entities: | Entity | Operator choices | |---|---| | `DataConnection` | Owning cluster, explicit consumer nodes, expected remote cluster/node, Node or Cluster target, endpoint set, consistency, secret reference, operation subset and finite call limits. | | `DataExport` | Origin-owned Raw or UNS root, authenticated peer principal, operation grants and export limits. | | `RemoteNamespaceMapping` | Connection, consumer subset, local parent and branch name, same-realm remote root/address, operations, optional write-through, projection limits and freshness settings. | New connections, exports and mappings are disabled by default; write-through also defaults off. A saved draft is not a live import. Use the existing cluster deployment flow to validate and apply changes, and inspect applied state before enabling dependent consumers. The server-side schema validator remains authoritative: consumers must belong to the owning cluster, mapping consumers must be a subset of the connection's consumers, local parents must be valid containers, and branch collisions, invalid self-routes and unsupported type expectations are rejected. New connections default to a 30-second call timeout. Existing explicitly configured shorter timeouts remain in force. This limit never extends a caller's original deadline; a write without enough remaining time for the driver budget is rejected before dispatch. Raw maps to Raw and UNS maps to UNS. A remote root is a branch, so descendants can be discovered without authoring one import row per leaf. The local mapping owns a distinct view with remote origin provenance. Remote projected branches cannot be re-exported as locally owned data. Stable addresses use cluster, namespace URI, identifier kind and identifier; numeric OPC UA namespace indexes are process-local. ## Listener, credentials and trust Enable the dedicated listener with `DataConnections` host settings; see [Configuration](Configuration.md#dataconnections). Production requires TLS, a dedicated port, explicit allowed hosts and authenticated target identity. The listener certificate must have a current private key and SANs covering every allowed host; server-certificate rotation requires a rolling restart. Outbound trust validates the hostname and configured custom roots. The development cleartext exception is limited to Development on a literal loopback listener. The consuming node must have its target bearer credential provisioned locally under the configured canonical `secret:data/...` reference and scoped to that connection. An origin export names the principal authenticated by that credential. Deployment artifacts carry references and scope, never raw target credentials. `CredentialBundlePath` and `TrustBundlePath` support independently versioned local provisioning. Trust roots are provisioned independently of credentials; rotating one does not implicitly authorize the other. Protect mounted files and replace them atomically. Missing or unreadable mounts are retried rather than treated as credential deletion; explicit versioned deletion/removal and deployed scope retirement revoke authority. Do not reuse the existing mesh PSKs for this data plane. ## Routing and availability Node targets pin the expected node. Cluster targets select an authenticated, ready primary from the configured eligible endpoints; an endpoint's claimed cluster and serving incarnation must match policy. An explicit Node target may allow `ReadyReplica` for reads/subscriptions; writes still require primary authority. A secondary is not a write proxy to its partner. Same-cluster peer connections and cross-cluster connections use the same explicit routing rules. Role changes, deployment changes, metadata lease expiry and credential/trust changes invalidate stale authority. Recovery discovers the current catalog and starts a new subscription epoch with a fresh snapshot. Transitions during a disconnect can be lost. A peer outage must be treated as unavailable/pending remote data rather than a successfully browsed empty branch. Local device data continues independently. [Read/write operations](ReadWriteOperations.md) describes asynchronous projected cache refresh, freshness checks and mutation outcomes. ### Subscription freshness and exact-item renewal Peers negotiate stream freshness challenges and per-item metadata leases as separate capabilities. A Subscribe-authorized active item can receive a bounded, same-stream freshness challenge. The origin captures its age after accepting that challenge and keeps the challenge identifier coupled to the sample through delivery. The consumer bounds age by combining that origin age with elapsed time since its challenge started, then advances the bound through local queueing and publication. An unknown, expired, evicted or unnegotiated challenge cannot establish a finite age bound. Periodic challenge snapshots can renew a quiet item's age evidence without a device poll or an additional Read grant. A newer sample version alone cannot inherit an older challenge's proof. An existing SDK monitored item can renew only its **exact projected node** through a successful `GetMetadata` response with an explicit item lease from a peer advertising that capability. `MaxMetadataLease` is a ceiling, not an implicit grant. The origin still authorizes the service principal for Metadata; the consumer rechecks the original local caller and key for Subscribe. Renewal checks the full prior origin view and subject, serving identity, catalog/authority epochs, mapping scope, node lifetime and compatible metadata shape. Its lease begins at the consumer's monotonic request start and is capped by the mapping and original credential lifetime. A delayed reply cannot lengthen it. Renewal grants no parent or sibling visibility, Browse page, cursor or local Browse privilege. Missing capability, denied Metadata or an invalid lease leaves the item unavailable until valid authority can be established. An authorized logical monitored-item request can survive a physical stream expiry and seek a new pinned binding with bounded retries. The old binding and any queued sample evidence remain tied to their original authority and serving generation. The same item needs a fresh, complete baseline under the new stream epoch before it can publish again; old queued or Republish data cannot borrow the new proof. Withdrawal or expiry of the original local Subscribe authority stops renewal. Consumers can miss intermediate changes during an interruption. ## Rollout and diagnosis 1. Provision TLS trust and connection-scoped target credentials on each consumer; configure the origin export and local mapping grants. 2. Deploy with writes disabled. Confirm applied consumer scope, endpoint identity and role, then expand a remote branch and verify metadata and current-value quality. 3. Verify subscription snapshot recovery and freshness for the intended consumer workload. 4. Enable write-through only where the application can handle confirmed, unconfirmed and unknown outcomes. Never replay an ambiguous write after reconnect or failover. 5. To disable imports, disable the connection/mapping through the existing deployment flow. Retired authority makes imported data unavailable; disabling does not replay pending writes. For an unavailable import, check enabled versus deployed state, consumer membership, endpoint and allowed-host identity, target role/readiness, credential scope/version, trust roots, export/mapping operation intersection, metadata lease and sample age. Inspect stream resets/overflow, admitted retained import views, acknowledged registrations and distinct write outcomes where diagnostics expose them. The age upper bound is measured by the reporting node at the observation, independent of the admin server clock. Coalescing notices and resets have separate counts; unavailable overflow evidence is shown as unavailable. Ready describes the last verified handshake, whose timestamp is shown. Saving configuration is not evidence of a ready connection, and a live transport alone is not evidence of current metadata authority. Listener, connection, export and projection limits bound messages, streams, monitored items, retained bytes, metadata and call lifetimes. Tune them together for measured workload demand; defaults are admission bounds, not a throughput or capacity guarantee. Overload can reject work or reset a stream, requiring a fresh snapshot. Do not interpret that recovery as lossless replay. ### Mixed versions (X0 rollout) The remote history and alarm work (`docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md`) adds new operation bits (`HistoryRead` 32, `AlarmSubscribe` 64, `AlarmAcknowledge` 128, `AlarmConfirm` 256, `AlarmShelve` 512). A node older than X0 rejects the whole data-connection snapshot when a row carries a bit it does not know, taking down every connection on that node. - **Run X0 on every node of both clusters before any of these bits is authored.** Nothing checks this: ConfigDb records no node build, so it is a deploy-checklist step. - An X0 node drops any operation bit it does not implement from that row only, fail closed (an unknown grant is no grant). This applies to connections, exports and mappings alike. - Each drop is logged as a warning naming the row and counted on `otopcua.dataconnection.unknown_operations_dropped` (tag `kind` = connection, export or mapping). - A drop is counted once per row per accepted artifact change. A → B → A counts again, and a restart resets the count. - The dropped bits also show in the node's fleet diagnostics and, since H4, on the cluster's **Data connections** page (per connection, the count of mappings with drops, and per node the exports with drops — named when the AdminUI knows the bit, hex otherwise, with a hint that the node's build is older than the authored feature; #919). - Authoring rejects a bit until the release that implements it. H2 implements `HistoryRead`; the alarm bits stay rejected until A2. - The optional per-call header `x-otopcua-data-features` negotiates features. X0 parsed it and supported none; H2 supports `history` (see "Remote history" above). A call without it gets unchanged v1 behaviour. ## Remote history (runtime consumers) **Status: supported** (H4). Verified end to end (live gate H01–H06) with the origin on the **SqlServer** and **QuestDB** historian backends. The **Gateway** backend (AVEVA Historian via HistorianGateway) is **unverified** pending its live leg, #923 (blocked on the VPN to the historian) — the code path is the same origin history port, but no live read against it has been run. Since H2 a consumer can read the origin's history (HistoryRead Raw, Processed, AtTime) over a data connection. The origin serves it from its own historian backend (`ServerHistorian:Backend`) through the same pipeline its OPC UA clients use, so statuses (info bits included), timestamps and paging come back verbatim. H2 serves **runtime consumers** that hold the connection directly (`IDataHistoryService` on the deployed connection, or `LocalDataConnection` in-process). **Grants (all default off).** The `HistoryRead` operation (bit 32) must be on the consumer's `DataConnection`, on the origin's `DataExport` for the service principal, and — for a later projected read — on the `RemoteNamespaceMapping`. The origin also checks its own node ACL `HistoryRead` on the exported node on every call, whatever `Security:Acl:Enabled` says. A principal with no export granting it HistoryRead gets `PERMISSION_DENIED` for the whole call (as v1 Read does without a Read grant; it reveals nothing per node). Within a granted call, a node the origin ACL denies, an unhistorized node and an unknown node all answer the identical `BadHistoryOperationUnsupported` (`0x80720000`), so a peer cannot tell them apart. Run X0 on every node of both clusters before ticking the bit (see "Mixed versions" below); the AdminUI editor shows a reminder. **Negotiation.** The capabilities probe always asks for `history`; an origin advertises it only when a historian backend is configured. Other calls carry the header only toward an endpoint that advertised it. An origin without a historian, a pre-H2 origin, or a call without the header answers unsupported — the v1 responses are unchanged. **Limits.** | Setting | Default | Effect | |---|---|---| | `DataConnection.HistoryTimeoutMilliseconds` | 30000 | Each call's deadline is the smaller of the caller's remaining budget and this; expiry ⇒ `BadTimeout`. The origin also cancels every unary call at its own `DataConnections:UnaryTimeout` (30 s default), so the effective ceiling is the smaller of the two; that origin cancel is reported `BadTimeout` too, never an endpoint failure | | `DataExport.MaxConcurrentHistoryReads` | 4 | Concurrent history requests per principal; past it ⇒ `BadTooManyOperations` | | `DataExport.MaxHistoryValuesPerPage` | 10000 | Per-node page ceiling; an uncapped Raw read pages at it and returns a continuation. Processed intervals and AtTime times above it are refused `BadTooManyOperations` before any backend read | | `DataExport.MaxHistoryResponseBytes` | 4 MiB (256 KiB–64 MiB) | Larger answers travel in bounded chunks the consumer reassembles. The origin stops reading once a response is full and serves the remaining nodes on the next chunk call; remainders it holds count against a per-principal byte budget (concurrent reads × max(response limit, one page)) — past it a node is `BadTooManyOperations`, never dropped silently | | `RemoteNamespaceMapping.MaxHistoryAssemblyBytesPerRequest` | 16 MiB | Used by projected reads (H3); a direct consumer's budget is its request `MaxBytes` | **Continuations.** Origin continuations are single-use, idle-expire after 60 s and are bound to the principal, the HTTP/2 connection, the serving incarnation and role, the view and the request details. A resumed read goes only to the endpoint that issued its token: an origin restart, a failover or a lost page answers `BadContinuationPointInvalid` (start a fresh read; a fresh read may move endpoint). Release unused continuations with `ReleaseAsync`. **Sharing the history limiter.** Remote reads hold at most N − max(1, N/4) of the origin's N process-wide history batch slots (`ServerHistorian:MaxConcurrentHistoryReadBatches`); past that a remote request is `BadTooManyOperations` unsent, so local OPC UA clients keep at least one slot. At N = 1 there is no reservation: the one slot is shared. **Limit changes.** Deploying a change to a principal's history limits invalidates its outstanding tokens: a change to `MaxConcurrentHistoryReads` or the export's batch size clears its live origin sessions outright, and a change to `MaxHistoryValuesPerPage` or `MaxHistoryResponseBytes` changes the page size a token was bound to. Open reads then answer `BadContinuationPointInvalid` and start fresh. **Consistency.** History follows the connection's consistency. `ReadyReplica` is allowed; the newest seconds can lag on a secondary while its continuous-historization outbox drains. **Not supported yet.** HistoryReadEvents and modified-value reads (deferred); **HistoryUpdate is never forwarded**. ## OPC UA HistoryRead on projected nodes (H3) Since H3 an OPC UA client of the CONSUMER can HistoryRead (Raw, Processed, AtTime) a projected variable in the `https://zb.com/otopcua/mapped/raw|uns` namespaces exactly as it reads a local one; the consumer forwards the read over the mapping's deployed connection (the runtime path above) and returns the origin's Part 11 answer verbatim — statuses, info bits, timestamps (absent stays absent), values typed as the catalog says (a disagreeing value kind is `BadTypeMismatch`). **What a client sees.** A projected variable is `Historizing = true` with the `HistoryRead` access-level bit **only** when the mapping grants `HistoryRead` (masked by the export's) **and** the origin's negotiated metadata says the node is historizing for this principal (`HistoryInfo`, bit 32). Otherwise it carries `CurrentRead` only and the SDK answers `BadHistoryOperationUnsupported` before any remote call. The `HistoryWrite` bit is never set: HistoryUpdate is not forwarded. **Grants** — all default off, and all required **even with `Security:Acl:Enabled=false`**, because mapped nodes always enforce the mapping gate: | Where | What | |---|---| | Consumer `DataConnection.AllowedOperations` | `HistoryRead` (32) | | Consumer `RemoteNamespaceMapping.AllowedOperations` | `HistoryRead` (32) | | Consumer node ACL | `NodePermissions.HistoryRead` for the client's principal on the `RemoteNamespaceMapping` scope (or a scope above it) | | Origin `DataExport.AllowedOperations` + origin node ACL | as for the runtime path above | Without the local grant (or without the mapping bit) the node answers `BadUserAccessDenied` — a local decision, distinct from the origin's `BadHistoryOperationUnsupported`. An origin-side denial, an unhistorized node and an unknown node stay indistinguishable (the origin's metadata does not mark the node historizing, so the consumer refuses it `BadHistoryOperationUnsupported`). **Mixed batches.** One HistoryRead may mix local and projected nodes: local nodes are served by the local historian exactly as before, projected nodes remotely, every result in its own slot. The remote half runs under the same process-wide HistoryRead batch limiter (`ServerHistorian:MaxConcurrentHistoryReadBatches`, N) and never holds the node-manager lock; projected reads and remote peers reading this node hold, TOGETHER (one shared semaphore), at most N − max(1, N/4) of the N slots, so a slow origin cannot starve local HistoryRead/HistoryUpdate — past that the projected half is `BadTooManyOperations`, unsent. A fault or timeout of the remote call (including the connection's capability probe) fails only the projected half, per node (`BadTimeout` when the deadline fired), and releases its continuation points. Remote calls are runs of consecutive request positions that share a connection, details and (for resumes) the issuing endpoint, read in request order and split into sub-batches at the connection's batch size; the gRPC connection splits again at the origin's advertised `MaxBatchItems` from the capabilities each call negotiates (no extra probe) — a large batch is never refused as a whole. **Continuation points.** A projected read's continuation point lives in the client's OPC UA session like a local one (a `Remote` cursor; capped by `MaxHistoryContinuationPoints`, oldest evicted). It wraps the origin's token and binds the caller (principal, key, credential version), the mapping id **and revision**, the deployed connection route, the projection generation, the origin view and the origin serving identity; a resume resends the **original** request details (the origin binds their hash — a client that changes details on resume gets what it first asked for, as locally). Rules: - **A fresh read may move endpoint** within its deadline (a failed SOURCE node ⇒ the next endpoint); **a resumed read never moves**. - A mapping revision change, a connection redeploy / lease expiry, a failover or origin restart (serving node / incarnation / generation / role), a projection rebuild, another caller, or an origin history-epoch bump (an origin address-space removal or rebuild) ⇒ `BadContinuationPointInvalid`; read again from the start. - **Release:** `releaseContinuationPoints`, the session's close, an eviction and a refused save each forward one best-effort `ReleaseHistoryAsync` per connection (releases coalesce for ~25 ms, so a session close sends one call per origin). The origin's 60 s idle expiry is the backstop. - Uncapped Raw (`NumValuesPerNode = 0`) returns the origin's continuation point (Part 11 permits a short page + CP): the origin pages at its `MaxHistoryValuesPerPage` ceiling. **Limits.** | Limit | Effect | |---|---| | `RemoteNamespaceMapping.MaxHistoryAssemblyBytesPerRequest` (16 MiB) | One budget per request, shared across the batch (the tightest mapping in the batch). Nodes are charged in request order (calls run in request order, and at most one node per 256 B of the remaining budget is sent); once a node does not fit, it and every later projected node with data is `BadTooManyOperations` (never a partial answer; its origin cursor is released). | | `ServerHistorian:HistoryReadDeadline` (consumer, 60 s) | ONE deadline per request, covering the local half too: the local nodes of a mixed batch are served first, so a slow local historian leaves the projected nodes less (or no) time — they answer `BadTimeout`. Each remote call is capped by the remaining deadline and `DataConnection.HistoryTimeoutMilliseconds` ⇒ `BadTimeout`. A cancelled request is never counted as an origin fault; a cancel that is neither the caller's nor the deadline (a connection redeployed mid-read) is `BadNoCommunication` / `BadContinuationPointInvalid`. | | Aggregates | An aggregate the consumer cannot name is `BadAggregateNotSupported` unsent; one the origin's backend refuses (unknown to it, or not valid for the node's type — #897) comes back `BadAggregateNotSupported` from the origin. The consumer's `HistoryServerCapabilities/AggregateFunctions` does not describe remote backends. | Modified-value reads (`IsReadModified`) and HistoryReadEvents on projected nodes are refused `BadHistoryOperationUnsupported`. **Client CLI.** Resolve projected NodeIds by browsing from the mapping anchor (never construct `p1.` ids), then `otopcua-cli historyread -n "" …`; `--page-size`, `--pause-after-page` and `--abandon-after-page` exercise the continuation lifecycle (`Client.CLI.md`). Live gate: `scripts/validation/grpc-data/history_gate.py` (H01–H06, README). ## Remote history diagnostics and metrics (H4) The cluster's **Data connections** page (`/clusters/{id}/data-connections`) shows, per consumer node and connection: - **Negotiated features** — what the last capability handshake negotiated for the data calls (`History`, or "none (v1 behaviour)" against an origin without a historian backend or older than H2), and the **origin history** it advertised to this caller: the variants (`raw`, `processed`, `attime`) and the aggregate count, or "not advertised". - **Projected history reads** by status class (good / uncertain / bad) — one per projected node per local OPC UA HistoryRead, with the status the client got, since process start (a node that no longer resolves to a connection is counted in the metric only). - **Open remote continuations (local sessions)** — projected-history continuation points held in local OPC UA sessions: issued, not yet resumed or released (a release, a session close or an eviction settles them). - **Dropped unknown operation bits** — the X0 drops for that connection and how many of its mappings had bits dropped. And per node, under **Origin evidence by node**: whether the node serves remote history (has a historian backend), the live peer history sessions, the **open origin continuations** (page cursors and chunk remainders held for peers), the history items it answered by status class (per wire call: a chunked page's follow-up calls count again), and its exports with dropped unknown operation bits. All counts are since process start and reset on restart. "Unavailable" means the node did not report the measure (built before H4, or no data-connection services) — never zero activity. The origin's data services are created on the first peer call, so until a peer has called, a node's origin line shows its backend availability with zero sessions, continuations and answers and "no peer has called since start". Metrics, on the `ZB.MOM.WW.OtOpcUa` meter (exported on `/metrics` and OTLP like every OtOpcUa instrument), never carry a connection, node or principal id in a label: | Instrument | Type | Labels | Meaning | |---|---|---|---| | `otopcua.dataconn.history.reads` | counter `{item}` | `variant` = raw \| processed \| attime (\| modified, consumer only), `status_class` = good \| uncertain \| bad, `side` = origin \| consumer | Origin: one per item **per wire call** answered to a peer (refusals included) — a chunked answer's follow-up calls for the same page count again, so this measures served item-calls, not logical reads. Consumer: one per projected node per OPC UA HistoryRead, with the status the client got (refusals before any remote call included; a request that faults counts every projected node Bad). A node can be both, so `side` keeps them apart. | | `otopcua.dataconn.history.continuations.active` | gauge `{continuation}` | `side` = origin \| consumer | Origin: cursors held for peers. Consumer: cursors held in local sessions. | | `otopcua.dataconnection.unknown_operations_dropped` | counter `{row}` | `kind` = connection \| export \| mapping | The plan's `…operations.unknown_bits_dropped`: the X0 counter is reused rather than duplicated (see "Mixed versions"). | Before H4 the origin's `otopcua.dataconn.history.reads` sat on a private meter the host did not export; it is now on the OtOpcUa meter and carries `side`. ## Feature boundary Alarm/event forwarding and relay operations are future work; remote history is above. Authorized imported current values can feed local derived engines, including calculations, scripts, historization and alarm evaluation. Such local processing does not add a remote history/alarm API or permit re-export of an imported branch.