Files
lmxopcua/docs/DataConnections.md
T

736 lines
66 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.
# 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.
**A lapsed lease is not an access denial (#922).** A projected node idle longer than its mapping's
`MetadataLeaseMilliseconds` keeps its retained proof; the lease is only *lapsed* when its time ran
out or its route was replaced while the local catalog authority, mapping binding and cache
generation are all still current and nothing revoked it. On a refused value Read / attribute Read /
HistoryRead of such a node, the consumer first authorizes the caller against the lapsed subject
(local grant + mapping bit, everything but the lease). A caller without the grant is still
`BadUserAccessDenied` and nothing is sent to the origin. A granted caller gets the same exact
`GetMetadata` renewal as above, for the operation it is performing (Read / HistoryRead bit, not
Subscribe), one per node and operation at a time, with a 250 ms back-off after a failure. On-demand
renewals never touch the unary budget (cold reads, writes) or the browse/subscription-renewal fetch
slots: they queue (at most 64) for their own pool of `max(1, maxConcurrentFetches / 2)` origin calls,
reserve 256 KiB each, and have 3 s end to end, so a batch of N lapsed nodes renews all N:
- **Value Read** answers `BadWaitingForInitialData` (as a cold read does) while the renewal runs off
the request thread; once it commits, a read is scheduled so the client's retry is served from the
fresh sample. `BadResourceUnavailable` while a renewal cannot be started (capacity, back-off).
A non-Value attribute of a lapsed node answers `BadResourceUnavailable` while it renews.
- **HistoryRead** renews within the request and is then served. The wait (one per batch, at most 4 s
and never past `HistoryReadDeadline`, no node-manager `Lock` held, the request's cancellation
honoured) takes one of the non-local history batch slots first. A batch that finds none free does
not wait. A renewal that cannot complete (origin unreachable or silent, no slot) answers
`BadResourceUnavailable`. A renewal that succeeded while the node manager's ACL veto still refuses
answers `BadUserAccessDenied`.
- **Browse:** a cached page past half its lease is served as is *and* refreshed in the background
(one refresh per page key), so a re-browse renews the leases of the nodes it lists.
An origin that stopped granting the operation fails the renewal; the consumer then keeps answering
the retryable status (it cannot tell that from an unreachable origin).
Not covered yet: a **Write** or **CreateMonitoredItems** on a lapsed node is still refused
`BadUserAccessDenied` (neither starts a renewal; a re-browse, a Read or a HistoryRead of the node
renews it, after which they succeed). A lease that was revoked (`Invalidate`), a removed mapping and a
retired node are refusals, not lapses, and are never renewed.
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`; A2
implements `AlarmSubscribe`, `AlarmAcknowledge` and `AlarmConfirm`; `AlarmShelve` (512) stays reserved.
- The optional per-call header `x-otopcua-data-features` negotiates features. X0 parsed it and
supported none; H2 supports `history` and A2 `conditions` (see "Feature negotiation" above). A call without it gets
unchanged v1 behaviour.
## Feature negotiation (`x-otopcua-data-features`)
Remote history and condition forwarding add no protocol minor version. Each feature has a `CapabilitiesResponse`
advertisement and a per-call request header, `x-otopcua-data-features`, whose value is a comma list of `history` and/or
`conditions` (summed length ≤ 256 characters; `DataConnectionProtoContract.FeaturesHeader`).
- **The capabilities probe always asks for every feature the consumer supports.** The origin advertises a feature only
when the probe asked for it **and** it can serve it:
- `history` needs a historian backend (`CapabilitiesResponse.history`, field 16, and bit 32);
- `conditions` needs a provisioned `DataConnections:ConditionKeySecret` and a running node manager
(`CapabilitiesResponse.conditions`, field 17, and bits 64/128/256).
- **Every other RPC carries the negotiated set**: the consumer's features ∩ what the *selected endpoint* advertised. It is
re-derived per endpoint, so after a failover it follows the new endpoint's capabilities. On the origin, the effective set is
header ∩ server-supported ∩ origin-servable.
- **A call without the header gets byte-identical v1 behaviour.**
- Browse and GetMetadata keep the v1 shapes: no `Metadata.history`, no bit 32 or condition bits in `allowed_operations`.
Conditions never appear in the catalog for anyone; they are discovered only through a root-scoped condition item.
- Subscribe never emits the `condition_states` arm (9). A v1 client faults on an unknown frame arm, so the header gate is
mandatory, not a courtesy.
- The new RPCs (`HistoryRead`, `CallConditionMethod`) answer `FailedPrecondition("feature not negotiated")`. A
history-only call is also refused `CallConditionMethod`.
- Header-less goldens (`*Goldens.cs`) and the recorded-v1-client gates (`GrpcDataV1CompatibilityTests`,
`GrpcDataV1RealOriginCompatibilityTests`) pin the v1 bytes. Every phase ran them with an empty goldens diff. The two
pre-deploy corrections below are the only deliberate differences. The real-origin gate applies them to the recorded
goldens in `GrpcDataV1RealOriginCorrections`; the goldens are never re-recorded.
### What an origin exports (v1 corrections #916, #917)
v1 was merged but not deployed (#915), so two defects were fixed in v1 itself. Header-less callers get the fix too.
Neither change alters the wire shape: one drops an optional field, the other drops a page item. Evidence: `docs/plans/evidence/grpc-data-ext/V1-916-917.md`.
- **No `Metadata.stable_source_id` (#916).** The origin never sends field 10. It used to carry the internal acquisition key,
which for a driver tag is `<len>:<driverInstanceId><RawPath>`. That disclosed driver ids and RawPaths to peers holding
only a UNS export.
- No consumer used the field except for byte accounting, so it was dropped rather than replaced by an opaque id. A
stable opaque id would only let a peer correlate Raw and UNS nodes.
- The field is `optional`. Old consumers decode its absence as null, so every version mix works.
- Conditions dedupe on the keyed `condition_key` instead.
- Internally the origin still keys acquisition on the unchanged `BackingSourceKey`.
- **Alarm-bearing raw tags are not exported as values (#917).** A tag with an alarm config never gets a value: the driver
host keeps it out of the value fan-out, and #896 gives it no UNS variable.
- The origin compiles it as an unsupported value node. GetMetadata, Read, Subscribe and HistoryRead on it answer
`Unsupported`, and writes are refused.
- **Browse does not list it**, and the same holds for any unsupported value node, such as a data type v1 cannot carry.
Every consumer build applies a browse page all or nothing and cannot materialise an `UnsupportedVariable`. Listing one
made the whole folder unbrowsable on the consumer (`BadNoCommunication`); the live gate found this.
- The node stays in the catalog, so an export rooted at it still compiles. Such a root grants nothing: the values are unsupported, and the condition sits under the tag's folder, not under the tag.
- The alarm itself is forwarded as a **condition** (A1–A4, see "Condition forwarding end to end"). Condition placements
do not depend on the value node.
G0, the v1 deploy and soak (#915), is still open; see the plan's §1.1.
## 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.
Live-gated against a real pre-H2 origin (#921, `docs/plans/evidence/grpc-data-ext/H05-v1-origin.md`): a pre-H2 origin
ignores the probe's header (capabilities byte-identical with and without it), so the consumer's projected variables have
`Historizing` False, HistoryRead answers `BadHistoryOperationUnsupported` locally, and no HistoryRead or feature-headed data
call is sent. (Sent anyway, a HistoryRead is refused `PERMISSION_DENIED` by the old data listener's v1 method allowlist.)
**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 "<printed NodeId>" …`; `--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`.
## Condition streams (origin side)
An origin streams its alarm condition state to a peer that negotiated `conditions` (`x-otopcua-data-features`). Plan:
`docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md` §5.1/§5.5; evidence `docs/plans/evidence/grpc-data-ext/A2.md`.
- **Served only when** `DataConnections:ConditionKeySecret` is provisioned (≥ 32 UTF-8 bytes, identical on both pair
members) and the node manager is up. Otherwise `CapabilitiesResponse.conditions` (field 17) and the `AlarmSubscribe` bit
(64) are absent and condition items are `Unsupported`.
- **Grant.** `AlarmSubscribe` on the export (and the connection/mapping, authored like the other bits), plus the origin
ACL `Subscribe` (`CreateMonitoredItems`) on each placement's scope for the connection's service principal. A stream with
only `AlarmSubscribe` (no `Subscribe`) is admitted when the call negotiated `conditions`.
- **The item.** `SubscriptionItem.condition_scope` on the mapping's remote root (an export root) = every condition placed
under that root in the root's realm (Raw: native, at the RawPath; UNS: native at the reserved reference id and scripted
at the ScriptedAlarmId; a UNS listing never carries a RawPath). One handle; it counts as one monitored item. Primary only
(`Unavailable` on a Secondary or Warm standby).
- **Frames** (`condition_states`, arm 9, never on a call without the header):
- snapshot begin: `is_snapshot`, `total`, no records. `total` above the export's `MaxConditions` ⇒ that is the only
frame for the item (nothing is copied); a later deploy that changes the listing re-admits it;
- record chunks (≤ 128 records, `info` on every snapshot record and on a condition's first delta);
- the last snapshot chunk carries `snapshot_complete` only when every node-manager hold saw a completed apply of one
generation and the node is Primary; otherwise the snapshot is retaken (at most once a second) when the origin is ready;
- then delta records, in order. A `removed` record can still arrive within one serving identity (a hub removal, or a
listing change without a catalog attempt).
- **A deploy ends the stream.** Every origin deploy begins a catalog attempt, which changes the serving identity, and a
condition item cannot outlive the identity it was admitted under. Conditions that a deploy adds or removes therefore never
arrive as delta records. The consumer reconnects and takes a complete snapshot of the new catalog. (Corrected in the A2
review, S1. Earlier text here said a deploy's adds/removes arrive as deltas; only a fixture could do that.)
- **A consumer deploy holds its imported conditions.** The consumer's own deploy publishes an empty mapping set while its
catalog attempt is in progress; that set is undecided, not a removal. Conditions are held and handed to the next runner
(same nodes, same EventIds); only the settled set decides a removal (A4 F1–F3). A4 review round 2 bounds and settles it:
- The runtime publishes the placements and the "undecided" flag as one value (`ProjectedMappingSet`), so no reader pairs
a settled flag with the attempt's empty list.
- **Any** completion settles the set. A failed or degraded apply leaves the catalog unactivated, so the settled set is
empty and the held conditions are removed. (Browse anchors still stay retained until a successful activation.)
- An attempt that never completes is bounded. The held conditions go `BadNoCommunication` on the connection's stale
timeout, as for any stream gap, and are removed past `ProjectedConditionOptions.MaxHold` (5 min, 2.5× the deploy apply
deadline). Until then they stay charged to the host caps and diagnostics show the connection as `held`.
- The runner that takes a held set over sends **RefreshRequired once** at its first barrier. While the set was held
nothing imported was visible, so an event queued then was dropped and a ConditionRefresh replayed nothing. RefreshRequired
is a Server-object event, not a condition event: EventIds are kept and no condition event is added.
- **Priority and overflow.** A control or ack at the head of the stream goes first, then condition frames, then queued
values. Condition production is pull-based: a slow consumer leaves records in the bounded condition-state hub. The item
notices an eviction of records it has not read the next time it reads the hub. If its previous snapshot's last chunk is
still undelivered at that moment, the stream is `Reset` ("Condition stream overflow; retry later."). Otherwise the item
takes a fresh snapshot on the same stream (a new snapshot begin, counted as a resync). Which of the two happens for an
eviction during a long snapshot delivery depends on scheduling. Both are correct and neither loses a change: the consumer
replaces its set with the next complete snapshot, either on a reconnect or by swapping the buffered re-snapshot at
`snapshot_complete` (#928).
- **Revocation** (grant, catalog or authority change) ends the stream like a revoked v1 value item; no further condition
frame is delivered.
- **Limits** (`AddDataConnectionConditions`): `DataExport.MaxConditions` (1000, ≤ 5000) and `RemoteNamespaceMapping.MaxConditions`.
The consumer-side timeouts are under "Limits and defaults" below. Metrics: see "Diagnostics and troubleshooting".
## Condition forwarding end to end (A1–A3)
**Status: implemented and live-smoked on the grpc-data rig** (`conditions_a3_smoke.py`, runs `a3b-cond-3`, `a3r1-cond-1`,
`a3br1-cond-1`, `a3r2-cond-1`, `a3v2-cond-1`). The A4 scenario gate A01–A08 (plan §9, phase A4) is the exit gate. Until it
passes, treat condition forwarding as pre-release. The OPC UA side of an imported condition (namespace, ids, notifiers,
refresh, EventIds) is documented in [Alarm tracking § Imported conditions](AlarmTracking.md#imported-conditions-grpc-data-connections).
1. **Origin state.** The origin node manager keeps a per-condition `state_known` flag and feeds every condition change into
a bounded condition-state hub. A snapshot is taken under short `Lock` holds of at most `MaxConditions` each, with a
watermark. Deltas raised between holds are neither lost nor duplicated. Each condition is either:
- native, at its RawPath in the Raw realm; or
- scripted, at its `ScriptedAlarmId` in the UNS realm.
Which conditions are *known* is described in [Scripted alarms § Forwarding over a data connection](ScriptedAlarms.md#forwarding-over-a-data-connection)
and, for native drivers, under "Known state" below.
2. **Origin stream.** See "Condition streams" above: one root-scoped item per mapping, a snapshot then deltas. Each record
carries an opaque `condition_key`, a per-key version, `state_known`, `removed` and an activation marker. It also carries
`info` (name, type, source kind, placements, `supported_methods`).
3. **Consumer demand.** The consumer opens condition streams only on demand. The first admitted event item opens them; that
item is on the Server object (`i=2253`) or on a projected folder of a condition-bearing mapping.
- One stream is opened per condition-bearing connection, under that connection's service principal. A mapping is
condition-bearing when it is enabled and its operations (∩ the connection's) include `Subscribe` and `AlarmSubscribe`.
- The stream carries one item per mapping, Raw mappings first, then by mapping id.
- Demand is node-wide, not per caller: one admitted item opens every condition-bearing connection. The per-event gate
still decides what each session sees.
- All of a connection's items close together 30 s after the last event item goes (the linger). The linger also removes
what they materialised.
4. **Primary only, both ends.**
- The origin serves condition items and methods only while it is **Primary**; a Secondary or Warm standby answers
`Unavailable`.
- The consumer subscribes condition items to the Primary endpoint explicitly (`IDataPrimarySubscriptionSource`). It also
drops any condition stream whose provenance role is not Primary.
- Every consumer node in the mapping's `ConsumerNodeIds` mirrors state independently. Both pair members show the same
`ConditionId`, whatever principal each authenticates as.
5. **Snapshot barrier.** Nothing is materialised until every mapping of the connection has completed its snapshot, or until
`ConditionSnapshotTimeoutMilliseconds` has passed.
- A mapping that is incomplete at the barrier is `Unavailable`. The others proceed, and clients get `RefreshRequired`.
- A mapping that completes late is merged in.
- An `Unavailable` mapping (item refused, root metadata failed, snapshot timed out) or a `ConditionCapacity` mapping is
**retried on the open stream** (#930). Its root is re-resolved if it never resolved, any item it still holds is removed,
and a new item is added. The root re-resolve (metadata, 10 s budget) runs off the stream's frame loop (#934): frames of
the other mappings keep flowing meanwhile, the mapping stays `Unavailable` until the answer is applied on the loop, and
its item is re-added then. The stream is not ended for it, so the healthy mappings are never re-snapshotted and their
methods are never answered `BadNoCommunication` because of it.
- Retry delay, per mapping. A **definitive** refusal (`Denied`, `NotFound` or `Unsupported`, for the item or the root
metadata) or `ConditionCapacity` waits `LongRetryDelay` (5 min) × 2ⁿ, capped at 4× (20 min). Any other refusal or a
snapshot timeout waits `ConditionSnapshotTimeoutMilliseconds` × 2ⁿ, capped at 8×. A retry whose snapshot has not
completed by its deadline goes back to `Unavailable` but keeps its buffer and claim, exactly like a mapping that missed
the first barrier: a late completion is still swapped in, until the next retry removes that item and starts over. A
completed snapshot resets the count. While a retry runs the mapping is `Pending` (unknown), so nothing it might list is
removed or marked known-inactive (T2).
- Every command on the stream has a unique id (the transport refuses a reused one and the stream would end).
- An item ack that arrives after its retry was already replaced (a slow origin) is not ignored: a Good one means the
origin opened an item the consumer no longer tracks, so it is removed at once — otherwise every later re-add would be
refused `InvalidArgument` ("Duplicate client item id"). As a backstop, 3 consecutive `InvalidArgument` refusals of a
mapping's in-stream re-adds end the stream (a new stream clears the origin's items).
- `ConditionCapacity` therefore recovers in-stream: after the origin's listing shrinks (or the limit is raised) the next
retry's snapshot is admitted and swapped in.
- `RefreshRequired` is sent at an incomplete barrier only when its set of incomplete mappings differs from the previous
barrier's. A mapping that stays refused across stream restarts does not cause a refresh storm. A mapping that completes
leaves the set, so a later relapse is announced again.
- A stream that ends before its barrier (every root failing, no Primary) reconnects after `ReconnectDelay` (1 s) × 2ⁿ⁻¹,
capped at `MaxReconnectDelay` (60 s). The count resets when a barrier passes. Repeated ends log at Debug after the first.
`LongRetryDelay`, `ReconnectDelay` and `MaxReconnectDelay` are fixed `ProjectedConditionOptions` defaults, not host
configuration.
6. **Lifetime rule.** The end of a stream means "re-snapshot", never "removed".
- During a disconnect, imported conditions keep their last state. After `ConditionStaleTimeoutMilliseconds` their
`Quality` becomes `BadNoCommunication`: one event per condition, with Active/Acked unchanged.
- An in-stream re-snapshot is buffered. The live set and the nodes stay untouched until `snapshot_complete`.
- A condition is removed only when a **complete** snapshot no longer lists it (and no other mapping lists it), or when a
`removed` record arrives. An incomplete snapshot removes nothing. It marks the unlisted keys stale (`BadNoCommunication`).
- That hold is bounded per key (#933). A key no known mapping lists, kept stale because another mapping of the connection
is unknown (`Unavailable`, `Denied`, retrying), is removed after `ProjectedConditionOptions.MaxUnknownHold` (20 min,
fixed): a removal with `RefreshRequired`, never "known inactive". If the unknown mapping later lists it, it is re-created
(new EventIds). The hold cannot be narrowed to "mappings whose scope could list the key": an origin deploy can move a
condition's placements into the unknown mapping's root, so the consumer cannot prove it. 20 min outlasts the transient
retry cycle (snapshot timeout × 8) and the first two re-checks of a definitive refusal (`LongRetryDelay` 5 min, then 10).
- **A mapping's own keys are not bounded while it is only transiently unknown** (review r1 S1). A key the unknown mapping
itself listed when it was last known (its previous stream, or before a capacity reset) is held with no bound while that
mapping is `Pending` / `Unavailable` / retrying — its origin may well still list it, exactly as when the connection's
stream never opens at all (held stale indefinitely). Its clock starts only when that mapping's refusal is
**definitive** (`Denied` / `NotFound` / `Unsupported` / `ConditionCapacity`); that verdict is remembered across its
retries and stream ends until it completes a snapshot, so a durably denied mapping's retries do not restart the bound.
- **The clock runs only while a stream is past its barrier** (review r1 S2): it pauses when that stream ends and resumes
at the next barrier, so a connection outage never counts and a merely slow snapshot after one removes nothing.
- `MaxUnknownHold` must be positive (the access refuses zero or negative at construction).
7. **Known state (T2 invariant).** *The consumer never retires or clears an alarm that is active at the origin.*
- A record with `state_known = false` never changes the consumer's last state.
- A condition first seen unknown is materialised with `Quality = UncertainInitialValue` until a known record arrives.
- Native drivers become known through a per-device "standing alarms delivered" signal (`IAlarmInitialStateSignal`).
`DataConnections:ConditionKnownSignalTimeout:<DriverType>` is the origin's wait for that signal (default 120 s). On
expiry the conditions **stay unknown**, the `otopcua.dataconn.conditions.unsignalled` counter moves, and a diagnostic
is raised on the hub.
- `DataConnections:ConditionKnownSettle:OpcUaClient` (default 60 s) is the only backstop timer. It exists for upstreams
without ConditionRefresh.
- Open gaps: #924 (L4 latency for Galaxy, Heidenhain and real Logix ALMD) and #925 (Galaxy deploy-added conditions stay
unknown).
- An OpcUaClient RefreshEnd signals only for a lossless refresh bracket (#926). Loss inside the bracket — queue
overflow, RefreshRequired, a skipped publish gap, or a missing RefreshStart — suppresses the signal and re-runs
ConditionRefresh, at most 3 times per episode. If every retry is lossy, the conditions stay unknown and the timeout
diagnostic reports them. A loss after the signal **withdraws** "known" for that subscription's conditions
(`AlarmInitialStateEventArgs.Withdrawn` ⇒ `MarkConditionsKnown(Known: false)`, F5 re-armed, no backstop) until a
clean refresh signals again. See `docs/drivers/OpcUaClient.md`.
### Condition key (`DataConnections:ConditionKeySecret`)
```
condition_key = base64url(HMAC-SHA256(K, upper(originClusterId) ‖ 0x00 ‖ realm ‖ ConditionId))
K = HKDF-SHA256(ConditionKeySecret, info = "otopcua/condition-key/v1") realm: 1 = Raw, 2 = Uns
```
- **Per origin cluster, identical on both pair members**, supplied as a `${secret:…}` reference or the
`DataConnections__ConditionKeySecret` environment variable. Never a committed literal.
- **Missing ⇒ the feature is off, not an error.** The origin logs one Information line (`… is not provisioned; this origin
does not advertise the conditions capability`). It advertises no `conditions` capability and no bits 64/128/256, and
condition items are `Unsupported`. Everything else is unaffected.
- **Present but weak ⇒ a startup error** (`DataConnectionOptionsValidator`, only while `DataConnections:Enabled`). These
count as weak: shorter than 32 UTF-8 bytes, blank, containing control characters, or still holding an unexpanded
`${secret:`. The message never echoes the value.
- The key is stable across restarts, failover and redeploys, and is the same for every principal and listing. It lets a
consumer dedupe one condition's Raw and UNS placements. Because it is keyed, it cannot be dictionary-reversed from
guessable RawPaths, and it carries no RawPath or driver id.
- **Rotation is a planned operation that changes every imported `ConditionId`** on every consumer. After a rolling restart of
the origin pair, the next complete snapshot carries new keys. Consumers remove the old conditions, materialise new ones and
send `RefreshRequired`. Clients that key on `ConditionId` see every alarm as removed and re-added. Rotate both pair members
in one change: if they differ, a failover changes every id.
### Operation bits
| Bit | Name | Where it is authored | What it grants |
|---|---|---|---|
| 64 | `AlarmSubscribe` | connection, export, mapping | the root-scoped condition item; with `Subscribe` on the mapping it makes the mapping condition-bearing |
| 128 | `AlarmAcknowledge` | connection, export, mapping | remote Acknowledge and AddComment |
| 256 | `AlarmConfirm` | connection, export, mapping | remote Confirm (scripted conditions only; see below) |
| 512 | `AlarmShelve` | reserved, not authorable | — (Shelve/Unshelve/Enable/Disable are not forwarded, plan §7) |
The mapping's bits must be a subset of the connection's. An effective grant is the intersection of the connection, the
mapping and the origin export, plus the origin ACL for the connection's service principal and the local caller's grants
(see [security § Imported conditions](security.md#imported-conditions-over-data-connections)). A node older than X0 must
not see these bits; see "Mixed versions" above.
**`DataExport.AllowGalaxyServiceAck`** (default `false`; valid only with `AlarmAcknowledge`, validator code
`DataExportGalaxyAckInvalid`).
- Without it, the origin lists Galaxy-sourced native conditions with `supported_methods = 0`. The consumer then refuses
Acknowledge/AddComment on them with `BadNotSupported`, unsent. If a call does reach the origin, it is refused
`BadUserAccessDenied`, unapplied.
- With it, the ack runs under the Galaxy ack identity of the connection's service key. Provision
`otopcua/apikeys/<serviceKeyId>/galaxy-ack-user` and `…/galaxy-ack-password` in the **origin's** secrets store; without
them the #765 preflight refuses `BadUserAccessDenied`.
### Condition methods (`CallConditionMethod`)
An OPC UA client calls Acknowledge, AddComment or Confirm on an imported condition (the type method or the condition's
instance child). The consumer node manager **claims** the call before the SDK's synchronous `Call` runs. It does the checks
below without I/O and without the node manager `Lock`, then awaits the origin with no request thread held. The L3 gate
measured Read, Browse and Publish unaffected during a 5 s origin stall.
- **Nothing is applied locally.** The imported node changes only when the origin's record arrives on the condition stream,
so a `Good` answer can precede the confirming event.
- **Budget** = min(the request's deadline − 250 ms grace, the mapping's `ConditionMethodTimeoutMilliseconds`). A dispatch with
less than 250 ms left is refused `BadTimeout`, unsent.
- **Slots:** 8 in-flight dispatches per consumer node and 4 per connection inside them, so one stalled origin cannot starve
another. Waiting for a slot counts against the budget.
- **Joins:** an identical call already in flight joins it and gets the same answer. Identical means the same principal,
condition, EventId, method and comment. Each dispatch has a fresh operation id; the origin's operation registry joins
duplicates of an id.
- **Never retried**, not even after a reconnect or failover.
The origin runs the call through the same wrapped SDK handler a local client uses, under a bounded `Lock` wait (5 s, then
`BadTimeout`, unapplied). So a remote ack produces exactly one origin event and keeps the native Confirmed/Retain re-assert.
It also routes once to the driver (`AlarmCommand` unchanged) and keeps the #760 revert contract. `ClientUserId` and the
`AlarmCommand` user are the connection's service principal.
| Answer on the consumer | Meaning | Sent to the origin? |
|---|---|---|
| `Good` | Scripted: the origin applied it (`DriverConfirmedSuccess`). Native: the origin accepted it and routed it to the driver (`AcceptedUnconfirmed`). The state change arrives on the stream. | yes, applied/accepted |
| `BadNodeIdUnknown` | not an imported condition this node holds | no |
| `BadNotSupported` | Shelve / Unshelve / Enable / Disable / unknown method; **native Confirm**; method not in the origin's `supported_methods` (e.g. Galaxy without the opt-in) | no |
| `BadUserAccessDenied` | the local caller fails the mapping method gate, or the deployed connection lacks the bit | no |
| `BadArgumentsMissing` / `BadTooManyArguments` / `BadTypeMismatch` / `BadInvalidArgument` | argument shape; comment over 4,096 characters | no |
| `BadEventIdUnknown` | EventId not minted by this consumer for this condition under the current activation marker (stale, superseded or pre-failover; see AlarmTracking) | no |
| `BadInvalidState` | this consumer node is the Warm standby | no |
| `BadNoCommunication` | no open condition stream for the connection (down or never opened) | no |
| `BadTooManyOperations` | no method slot free within the budget | no |
| `BadTimeout` (no "OutcomeUnknown" in the diagnostic) | budget below the 250 ms dispatch floor | no |
| `BadRequestCancelledByClient` | cancelled while waiting for a slot | no |
| `BadInternalError` | a fault before dispatch (logged) | no |
| origin's status (e.g. `BadUserAccessDenied`, `BadNodeIdUnknown`, `BadEventIdUnknown`, `BadInvalidState`, `BadTooManyOperations`, `BadTimeout`) | `RejectedBeforeDispatch` / `DriverConfirmedFailure` at the origin. Causes include an ACL or export refusal, an unresolved placement (existence is not disclosed), a marker mismatch (a new occurrence not yet streamed), non-Primary, a full operation registry, or a busy node manager. | sent, **not applied** |
| `BadTimeout` / `BadCommunicationError` with **"OutcomeUnknown: …"** in the diagnostic | sent, and no answer arrived in time, or the transport failed after send. **It may have been applied.** Watch the condition's events; do not replay. Logged as a Warning. | sent, outcome unknown |
`OutcomeUnknown` is reported as a Bad code on purpose: Part 4 gives a Call result no "maybe applied" Uncertain meaning, and
most clients read an Uncertain status as success.
### Limits and defaults
| Setting | Where | Default | Notes |
|---|---|---|---|
| `DataExport.MaxConditions` | ConfigDb, origin | 1,000 (≤ 5,000) | the listing of one root-scoped item above this ⇒ snapshot begin carries only `total`; the item is `ConditionCapacity` |
| `RemoteNamespaceMapping.MaxConditions` | ConfigDb, consumer | 1,000 (≤ 5,000) | the consumer's admission; `total` above it ⇒ `Unavailable(ConditionCapacity)` before anything is materialised; other mappings are unaffected. Imported conditions never consume `MaxProjectionNodes` |
| `RemoteNamespaceMapping.ConditionSnapshotTimeoutMilliseconds` | ConfigDb | 30,000 (≤ 1 h) | snapshot barrier |
| `RemoteNamespaceMapping.ConditionStaleTimeoutMilliseconds` | ConfigDb | 30,000 (≤ 1 h) | disconnect ⇒ `BadNoCommunication` |
| `RemoteNamespaceMapping.ConditionMethodTimeoutMilliseconds` | ConfigDb | 5,000 (≤ 1 h) | per-call method budget ceiling |
| `DataConnections:MaxImportedConditionNodes` | host, consumer | 122,500 (2,500 × 49 worst-case nodes) | node-wide across connections, order-independent |
| `DataConnections:MaxImportedConditionBytes` | host, consumer | 400,000,000 B (≈ 381 MiB = 160,000 B × 2,500, measured by L2) | node-wide |
| `DataConnections:MaxConditionMethodOperations` | host, origin | 4,096 | duplicate-protection registry, all principals; completed ids kept 5 min |
| `DataConnections:MaxConditionMethodOperationsPerPrincipal` | host, origin | 256 | the same per principal; full ⇒ `BadTooManyOperations`, unapplied |
| `DataConnections:ConditionKnownSignalTimeout:<DriverType>` | host, origin | 120 s | see "Known state" |
| `DataConnections:ConditionKnownSettle:OpcUaClient` | host, origin | 60 s | backstop; ignored for other driver types |
| `DataConnections:ConditionKeySecret` | host, origin (secret) | absent ⇒ feature off | see "Condition key" |
| Consumer method slots | fixed | 8 per node, 4 per connection | not configurable |
| Retained EventIds | fixed | 8 per condition | see AlarmTracking |
| Demand linger | fixed | 30 s | `ProjectedConditionOptions.Linger` |
Two charges are made against the host caps: a snapshotting mapping is charged its admitted `total`, and a completed mapping
its record count. Growth is charged as it happens. Records beyond `total`, live records beyond `MaxConditions`, or growth past
a host cap make that mapping `ConditionCapacity`. Its item is removed, its conditions are removed (except keys another
mapping lists) and clients get `RefreshRequired`.
Held keys that no contributing mapping lists (an `Unavailable` mapping's stale conditions, kept as `BadNoCommunication`)
are charged too, beside every new claim. The one allowance: a mapping with no complete set yet on this stream may be
re-listing keys **it** listed when it was last known, so those held keys are not charged twice. A mapping that never listed
them gets no allowance, so another mapping's held keys cannot make room for it. The remaining overshoot is narrow: a mapping
whose origin retired its old keys and lists new ones, while another mapping is unknown so the old ones stay held, can
exceed the caps by at most its own previous count until that mapping is known. It is logged ("over its host condition
caps") and visible as the node budget line in the AdminUI. The deploy gate also logs a non-blocking `DataConditionCapacityWarning`
when Σ `MaxConditions` × 49 of a consumer node's mappings exceeds `MaxImportedConditionNodes`.
### Diagnostics and troubleshooting
Metrics, on the `ZB.MOM.WW.OtOpcUa` meter, never carry a connection, node, mapping or principal id in a label. The shared
ones carry `side` = origin | consumer, because a node can be both:
| Instrument | Type | Labels | Meaning |
|---|---|---|---|
| `otopcua.dataconn.conditions.items` | up/down counter `{item}` | `side` | Origin: root-scoped condition items open for peers. Consumer: the items its condition streams hold open (one per acked mapping item). |
| `otopcua.dataconn.conditions.resyncs` | counter `{resync}` | `side` | Origin: an item re-snapshotted after a hub reader reset. Consumer: a condition stream that opened and ended (the next one re-snapshots); a connect attempt that never opened a stream is not counted. |
| `otopcua.dataconn.conditions.capacity_rejections` | counter `{item}` | `side` | Origin: an item snapshot over its `MaxConditions` (or refused by the snapshot memory budget). Consumer: a mapping reset to `ConditionCapacity` (over its `MaxConditions` or the host caps). |
| `otopcua.dataconn.condition_methods` | counter `{call}` | `method`, `outcome` (the `DataWriteState`), `side` | Origin: calls served. Consumer: calls forwarded (a call the local node manager refuses before forwarding is not counted). |
| `otopcua.dataconn.conditions.refresh_required` | counter `{request}` | `side` = consumer | RefreshRequired requests the consumer runtime made: an incomplete barrier with a changed incomplete set, a capacity reset that removed nothing, each removal batch. Not per client item. |
| `otopcua.dataconn.conditions.unsignalled` | counter `{condition}` | — | Origin: native conditions whose initial state was not signalled within the signal timeout. |
| `otopcua.dataconn.conditions.partition_overflows` | counter `{overflow}` | — | Origin: condition-state hub partition overflows. |
| `otopcua.dataconn.conditions.marks_discarded` | counter `{mark}` | — | Origin: deferred condition-known marks discarded after their alarm projection was dropped. |
The AdminUI **Data connections** page (`/clusters/{id}/data-connections`) shows, per connection on a consumer node, an
"Imported conditions" line. It reads "no condition-bearing mapping (or evidence unavailable)" when there is none, or when the
node is older than A4. Otherwise it shows:
- `stream` state (idle, connecting, snapshotting, live, or held — kept across an undecided deploy, see the condition stream lifetime) and `last snapshot` (UTC, or "none since start");
- `conditions` materialised, with the `state unknown` count (`state_known = false`);
- `node budget` charged against the host condition limit;
- `RefreshRequired`, `resyncs` and `capacity rejections` counts;
- `methods`, as succeeded / rejected / failed / unknown. Succeeded is DriverConfirmedSuccess, rejected is
RejectedBeforeDispatch, failed is DriverConfirmedFailure, and unknown is AcceptedUnconfirmed or OutcomeUnknown;
- `mappings`, one entry per mapping: id, status, observed count against its `MaxConditions`, and the refusal when refused.
The line takes the notice style when a mapping is `Unavailable` or `ConditionCapacity`, or when a mapping's count or the node
budget reaches 80 % of its limit ("≥ 80% of MaxConditions" / "≥ 80% of the host caps"). Each node's origin panel adds a
served-conditions segment: `condition items open`, `largest listing` against its limit (with the same 80 % note), `last
snapshot`, `resyncs`, `capacity rejections`, `state unknown (unsignalled)` and `methods served`.
Consumer logs (Information unless noted) record each condition stream it opens, each item the origin refuses (Warning, with
status and diagnostic), and each snapshot barrier (per-mapping status, record count, whether it timed out).
| Symptom | Check |
|---|---|
| No imported conditions at all | Is `ConditionKeySecret` provisioned on the origin? The origin logs "not provisioned" once at start. Are bit 64 and `Subscribe` on the connection, mapping and export? Does the service principal have the origin ACL `Subscribe` on the placements? Is a client subscribed to events (`i=2253` or a projected folder)? Streams open only on demand. Does the consumer log show a barrier? |
| A mapping refused `Denied` / `Unavailable` | Origin export grant and ACL for the service principal. The origin is not Primary. Metadata for the remote root failed (logged). |
| `ConditionCapacity` | The listing's `total` against the mapping's or export's `MaxConditions`, and the host caps. Narrow the remote root or raise the limits. |
| Conditions `Uncertain` | The origin has not established their state: a scripted alarm has not completed an evaluation; a native driver has not signalled (see `…conditions.unsignalled`). |
| Conditions `BadNoCommunication` | Stream down longer than `ConditionStaleTimeoutMilliseconds`, or the mapping was incomplete at the last barrier. |
| A retired condition stays `BadNoCommunication` while another mapping of the connection is `Unavailable` / `Denied` | Expected for up to `MaxUnknownHold` (20 min, #933) of live-stream time (an outage does not count): the unknown mapping might still list it, so it is held (T2). A key the unknown mapping listed itself is held with no bound until that mapping is refused definitively (Denied / NotFound / Unsupported / capacity). After that it is removed with `RefreshRequired` (logged Warning "held past MaxUnknownHold", naming the unknown mappings). Fix the unknown mapping (its refusal is on the AdminUI mappings line) to settle it sooner. |
| Ack answers `BadEventIdUnknown` | The client holds an old EventId (superseded occurrence, or an origin restart that re-announced a different time). ConditionRefresh and ack with the new EventId. |
| Ack answers "OutcomeUnknown" | Check the origin's audit log (`ZB.MOM.WW.OtOpcUa.DataConnections.Audit`) for the operation and watch the condition's events. Never replay blindly. |
| All `ConditionId`s changed | `ConditionKeySecret` was rotated or differs between the origin pair members, or the connection was re-created under a new id. |
Open follow-ups: #927 (live-gate the driver-failure ack revert) and #929 (re-measure the per-condition memory figures in
the plan). #928 (overflow test timing), #930 (refresh storm, in-stream `ConditionCapacity` recovery) and #931 (review nits)
are addressed in A4.
## Feature boundary
Remote history (above) and condition forwarding (Acknowledge, AddComment, Confirm) are supported. Still deferred (plan §7):
remote Shelve/Unshelve/Enable/Disable (bit 512 reserved), HistoryReadEvents on mapped notifiers, modified-value history
reads and HistoryUpdate. Relay operations are a separate design (plan §8). Imported conditions are not republished to the
consumer's `alerts` topic and are not written to its alarm history. Authorized imported current values can feed local derived
engines, including calculations, scripts, historization and alarm evaluation. Such local processing does not permit
re-export of an imported branch.