Search and contents

MES Node Type (OPC UA): sidecar, protocol, and mapping paths

This guide covers how the MES Node Type is built on top of open62541, the OPC UA library that is this system's own System Connector.

SectionTopic
Site variance Why OPC UA is only one of three MES source types, and what each check does beside which.
1 Sidecar provisioning.
2 The sidecar's wire protocol.
3 The client-server and PubSub protocol against a live target.
4 The explicit and inferred mapping paths onto canonical events.
5 Encrypted and authenticated connections (OPC-UA Transport Security).

Site variance: OPC UA is one of three MES source types, not a requirement of the Node Type

This guide describes the OPC UA source because the example config uses OPC UA to connect to a PLC/SCADA layer. It isn't a claim that MES sources are OPC UA in the field. The Node Type Identity Test is explicit that MES identity comes from the events emitted (OrderRelease and OrderCompletion), not the software or protocol underneath.

  • Some MES vendors do expose OPC UA directly.
  • More commonly, a MES's own transaction or audit log is the source of truth, which needs a Database Log Scanning connector. That connector is built (engine/database_log_connector.py; see database-log-scanning.md).
  • An MQTT source is built too (see mqtt-system-connector.md).

An MES config has exactly one of the opcua, mqtt and database_log sections.

What is allowed beside which source

deviation_flagging, costing_variance, material_consumption and instruction_bindings each have two forms, chosen by the Node's source. Beside opcua a check reads one node on the OPC UA server on a poll. Beside mqtt or database_log there is no node to poll and no current value to ask for: the check reads a field of each record, and the order is the record's own. The schema declares the keys of both forms; the offline check reports a key that does not belong with the Node's source, and the Node refuses to start with one. Each message names the section and the key and never repeats a value.

SectionBeside opcuaBeside mqtt or database_log
deviation_flagging Needs node_id. Reads the node every poll_interval_seconds and flags a reading outside the limit. Needs field, which names a field of the mapping. Refuses node_id. A record's value is judged when it differs from the one last judged for that order; poll_interval_seconds and evaluate_first_poll have no effect.
costing_variance Needs node_id and order_id: one order for the Node. The reading is cycle time in seconds. Needs cycle_time_field, in seconds. Refuses node_id and order_id. A cycle time that differs from the last one judged for that order is priced against the ERP peer's standard cost, and an ERP that cannot be reached is asked again every 30 seconds.
material_consumption Needs node_id and order_id: one order for the Node. Needs material_field. Refuses node_id and order_id. A material is linked to the record's order once, however many records carry it.
instruction_bindings Each binding names node_id and condition.node_id, and is polled every poll_interval_seconds. Each binding names field, condition.field and time_field, which must be fields the mapping produces, and is judged as each record arrives. Refuses node_id, condition.node_id and poll_interval_seconds.

What does not change with the source: deviation_flagging needs inference, costing_variance needs inference, communication_interface and a declared ERP peer, and instruction_bindings needs document_intake. Beside a record source, a value that is not a usable number (or, for a material, text) is logged and skipped, and the order's own status goes through. The limits of the record forms are in Instruction bindings, and a worked database log is in The MES as a database log.

REST is a middle ground already proven in this codebase. RestPollingConnector (engine/connector.py) already backs the ERP Node Type (see erp-node-type.md) against its own REST_CONFIG_SCHEMA (engine/erp_config.py). It is registry-pluggable the same way OpcuaConnector is here. A REST-based MES source would be a new config_schema.rest fragment and transform registrations on the MES Node Type, not a new connector type.

1. Provision open62541 and the sidecar

deployment/install_open62541_build_tools.sh   # cmake, build-essential, git (once)
deployment/install_open62541.sh               # clones, builds, installs open62541 itself
deployment/build_opcua_sidecar.sh              # builds sidecar/opcua/ against that install

install_open62541.sh is idempotent: it skips its own build if the target prefix already has one. See the Decisions section of deployment/README.md for why open62541 is built on the appliance itself, rather than shipped as a prebuilt artifact from a separate pipeline. That section also covers the two build-flag decisions baked into the script, UA_ENABLE_PUBSUB=ON and UA_ENABLE_ENCRYPTION=MBEDTLS. The latter is what section 5 (OPC-UA Transport Security) builds on.

build_opcua_sidecar.sh installs kindred-opcua-sidecar onto PATH (default prefix /usr/local). Settings.opcua_sidecar_path (engine/config.py) points at it by executable name. It is the same process-wide tier that mqtt_host and mqtt_port use, not a per-node Configuration Schema value, since every Node instance on a given appliance shares the same sidecar binary.

2. The sidecar's wire protocol

sidecar/opcua/ (linking open62541 directly) and SidecarProcess in engine/opcua_sidecar.py are the two ends of one protocol:

  • one JSON object per line on the sidecar's stdin (a request);
  • one JSON object per line on its stdout (a response, correlated by request id);
  • plus unsolicited {"event": ...} lines that a live subscription pushes at arbitrary times.
from engine.opcua_sidecar import SidecarProcess

with SidecarProcess() as sidecar:  # spawns kindred-opcua-sidecar
    sidecar.send("ping")  # -> {}
    sidecar.send("connect", endpoint="opc.tcp://plc:4840")  # -> {"connected": true}
    sidecar.send("disconnect")  # -> {"connected": false}

send() raises SidecarError for anything the sidecar itself reports as a failure ({"ok": false, "error": ...}) or a process-level problem (the process exited, or its stdout hit EOF, before responding). It never returns a response you have to check separately for success. This is the same fail-safe-and-report shape SystemConnector.test_connection() (engine/connector.py) uses on the Python side.

process_factory= on SidecarProcess.__init__ swaps in a fake process for tests (see _FakeProcess in tests/test_opcua_sidecar.py). It is the same constructor-injection shape as RestPollingConnector's client= argument.

3. Client-server subscribe and PubSub subscribe, and the OpcuaConnector

from engine.connector import (
    ConnectorRegistry,
    OpcuaConnector,
    OpcuaConnectorProfile,
    build_opcua_connector,
)

# One-shot poll/health-check, via the registry - build_opcua_connector()
# never asks for on_event, since there's nothing to subscribe to here.
registry = ConnectorRegistry()
registry.register("opcua", build_opcua_connector)
connector = registry.build("opcua", {"endpoint": "opc.tcp://plc:4840", "node_id": "ns=1;i=5000"})
result = connector.test_connection()  # connects + reads node_id once, never raises

# A live subscription needs on_event, supplied when constructing
# OpcuaConnector directly - on_event receives, e.g.:
#   {"event": "data_change", "subscription_id": 1, "monitored_item_id": 1, "value": 42,
#    "source_timestamp": 134380448721849500}
#   {"event": "pubsub_data", "value": 42}
profile = OpcuaConnectorProfile(endpoint="opc.tcp://plc:4840", node_id="ns=1;i=5000")
with OpcuaConnector(profile, on_event=handle_event) as connector:
    connector.subscribe()  # client-server - node_id from the profile
    # events now arrive on handle_event from a background thread, at arbitrary times

What OpcuaConnector is

OpcuaConnector (engine/connector.py) is the System Connector Registry's OPC UA entry. It plays the same non-special-case role that RestPollingConnector plays for the REST-polling connector type, and it is the only supported way to reach the sidecar. Nothing needs to construct a SidecarProcess directly.

MethodWhat it does
poll() and test_connection() One-shot reads.
subscribe() Client-server subscription.
pubsub_subscribe() Part 14 PubSub, using the profile's pubsub_connection_url, pubsub_publisher_id, pubsub_writer_group_id and pubsub_dataset_writer_id fields.

How it behaves:

  • Lazy start. Both the sidecar process itself and the OPC UA connect call are deferred to first use, not __init__. pubsub_subscribe() skips connect entirely, since PubSub delivery never touches the client-server connection, mirroring the sidecar's own independent handling.
  • on_event is required for subscriptions. subscribe() and pubsub_subscribe() both raise ValueError immediately, before touching the sidecar at all, if no on_event was supplied at construction. A subscription with nowhere for its events to go is always a caller mistake.
  • Self-healing. If the sidecar process itself dies (crashes, gets killed), as opposed to reporting an {"ok": false} failure while still alive, poll(), subscribe() and pubsub_subscribe() each transparently rebuild it and retry the whole call once before giving up. This holds as long as the connector owns its sidecar (no sidecar= supplied at construction). See A dead sidecar process for why the distinction between SidecarProcessExited and a plain SidecarError matters.

Event timestamps

A data_change event's source_timestamp is the time the OPC UA server gave the value, as the raw OPC UA DateTime: an integer count of 100 ns ticks since 1601-01-01 UTC.

  • It is left out of the event when the server sent none. An event from a sidecar built before the field existed has none either, so a reader must not require it.
  • A subscription's first data_change for a node announces the node's current value with the timestamp the server holds for it. For a value that has not changed, that is the one it had before. Whether a server keeps that timestamp, or stamps each read with the time of the read, is the server's own behavior.

Reader thread and event loops

The reader thread. A single background reader thread inside SidecarProcess (which the connector owns internally) reads every stdout line and routes it. A line carrying "id" resolves that request's waiter, and a line carrying "event" goes to on_event. This is required, not an optimization: once a subscription is active, event lines can arrive interleaved with the response to any later request (for example a subsequent disconnect call). send() can therefore no longer assume that "the next stdout line" is its own response.

On the C side, subscribe and pubsub_subscribe each start their own background pthread iterating open62541's event loop (UA_Client_run_iterate and UA_Server_run_iterate). Both are required for either subsystem to ever receive anything after the initial setup call returns, since OPC UA subscription and PubSub delivery are inherently asynchronous.

PubSub's embedded server. pubsub_subscribe embeds its own UA_Server. open62541 implements PubSub's reader side on UA_Server, even for a subscribe-only role with no classic OPC UA session ever served. It is bound to an OS-assigned ephemeral port (PUBSUB_HOST_PORT = 0) rather than a fixed one. This server is never dialed by anything, and a fixed port would break the moment a second kindred-opcua-sidecar process runs on the same appliance (a single MES Node instance's config can point at more than one OPC UA source, with one sidecar per source), since the second process's bind would collide with the first's.

The live test target

tests/live_targets/opcua_test_server/ is this codebase's own live OPC UA target: a minimal open62541 server, built only for tests (build.sh, never installed through deployment/). It also serves as the live target for the PLC/Generic Device Node Type's own protocol test, since node-types/plc-generic-device/ declares that Node Type against exactly this fixture, not a separate one.

It exposes one Int32 variable (ns=1;i=5000, incremented by a background thread every 200 ms) over both protocols:

  • as a classic server node (subscribe);
  • as a PubSub publisher of that same value (pubsub_subscribe, publisherId=4242, writerGroupId=100, dataSetWriterId=1). The constants match on both ends and are documented in the server's main.c.

4. Explicit- and Inferred-mapping paths, and MesIngestion

from engine.identity_resolution import IdentityResolver, IdentityStore
from engine.mes_ingestion import MesIngestion
from engine.transformation import (
    MappingRule,
    TransformationRegistry,
    build_petl_transform,
    build_rule_based_transform,
)
from engine.trigger_queue import TriggerQueue

registry = TransformationRegistry()
# Explicit-mapping path: the source exposes a direct order/job identifier.
registry.register(
    "mes-opcua-explicit", build_petl_transform({"order_id": "job_id", "status": "state"})
)
# Inferred-mapping path: the source only reports machine state - no order_id anywhere.
registry.register(
    "mes-opcua-inferred",
    build_rule_based_transform(
        [MappingRule(when={"state": "RUNNING"}, literals={"status": "in-progress"})]
    ),
)

resolver = IdentityResolver(IdentityStore(), activity_log, "MES", node_instance_id)
ingestion = MesIngestion(
    transformation_registry=registry,
    identity_resolver=resolver,
    trigger_queue=TriggerQueue(),
    node_instance_id=node_instance_id,
)
envelope = ingestion.ingest(
    "mes-opcua-explicit",
    raw_record,
    trigger_type="order_release",
    trigger_id=stable_id,
)

Where the choice of path lives

The config_schema.opcua fragment of node-types/mes/node_type.json carries field_map (Explicit path) and state_transition_rules (Inferred path) as Configuration Schema values. It is kept in sync with OPCUA_CONFIG_SCHEMA in engine/opcua_config.py by hand, the same two-representations shape the inference configuration schema uses.

build_field_map and build_state_transition_rules turn an already validated opcua config object into the build_petl_transform and build_rule_based_transform inputs above. Which path a given source_type uses is therefore the integrator's configured choice, never hardcoded Python.

How ingest() routes

MesIngestion.ingest() (engine/mes_ingestion.py) needs no explicit/inferred branch of its own. Whichever transform a source_type is registered against runs, and ingest() reads whatever the canonical result carries for ORDER_IDENTITY_FIELD ("order_id"):

  • Present: it routes through IdentityResolver's explicit branch.
  • Absent: it routes through the inferred branch, which never auto-resolves regardless of match confidence. A canonical event with no direct identifier always lands Pending, for the Mandatory-Human Sign-off Mechanism to eventually confirm.

ingest() writes no ActivityLogEntry of its own. IdentityResolver.resolve already logs itself, and TriggerQueue.enqueue is deliberately unlogged on the producer side, like every other Trigger producer. It is dispatch_claimed_entry, the consumer side (see trigger-dispatch-queue.md), that logs a claimed row's run.

5. OPC-UA Transport Security

Scoping Kindred's MES Node to read-only access on a real PLC needs a certificate identity for that scoping to bind to, which needs a crypto backend. The fields below are additions to the opcua connector type. A site with none of them configured connects at Security Policy None.

Five optional config.opcua fields (OPCUA_CONFIG_SCHEMA in engine/opcua_config.py, and OpcuaConnectorProfile in engine/connector.py) travel together:

FieldShapeMeaning
certificate_path file path (PEM) Kindred's own client application-instance certificate.
private_key_path file path (PEM) The private key matching certificate_path.
trusted_certificates_path file path (PEM, may concatenate several certs) The target server certificate(s) this connector trusts.
security_mode "sign" | "sign_and_encrypt" Defaults to "sign_and_encrypt" once a certificate is configured.
security_policy "basic256sha256" | "aes128sha256rsaoaep" Defaults to "basic256sha256" once a certificate is configured.

All three file paths are plain paths on the appliance's own filesystem. They are never inlined into the (optionally SOPS-encrypted) config file. The certificate, key and trust-list content stays local to the appliance under OS file permissions, the same model the age keypair in deployment/README.md uses. handle_connect in sidecar/opcua/main.c reads them directly. Kindred's Python engine never links OPC UA crypto itself (see OpcuaConnector's docstring).

Fail-closed by design

OpcuaConnectorProfile's validators reject, at config-validation time:

  • a lone certificate_path or private_key_path;
  • security_mode or security_policy with no certificate configured;
  • a certificate configured with no trusted_certificates_path. This is the one genuinely new requirement beyond presenting Kindred's own identity.

Without an explicit trust list, open62541 either rejects the target's certificate outright or, if some other trust configuration happened to be in place, silently accepts one. Neither is allowed to slide by unconfigured under this codebase's fail-closed convention (LicenseManager, Communication Interface, Retrieval Quality Gate).

The sidecar re-checks the same "all five together" contract on its own side (handle_connect in sidecar/opcua/main.c). This is defense in depth against a malformed or hand-crafted request bypassing the Python-level validators.

Supported security policies

Only two security_policy values are supported:

  • basic256sha256, the established industrial baseline;
  • aes128sha256rsaoaep, a newer OPC UA 1.04-profile policy some newer PLC firmware defaults to.

This is a deliberately small, closed enum, not because the crypto backend is limited. UA_ClientConfig_setDefaultEncryption makes every open62541-supported policy available at build time in one call. A third value (Basic256, Aes256Sha256RsaPss) would be a one-line addition to the security_policy_uri lookup table in sidecar/opcua/main.c, not new crypto work or a new dependency.

That table's URI strings match open62541's internally registered policyUri values exactly, confirmed against its source rather than the OPC Foundation spec's camelCase naming. The Aes128 policy's real URI is underscore-separated (.../SecurityPolicy#Aes128_Sha256_RsaOaep). A mismatch there doesn't error. It silently fails connect() with "No suitable endpoint found."

Not addressed by this feature

  • Configuring a target PLC's own UserAccessLevel and Role mapping to restrict Kindred's certificate to read-only happens on that site's own OPC-UA server, by that site's own OT team. It is outside this codebase entirely. This feature only makes Kindred capable of presenting a verifiable, encrypted identity that a site could scope that way.
  • There is no certificate revocation checking.
  • The trust list is one PEM file, not a directory of individually managed certs.

Tests

tests/live_targets/opcua_test_server/main.c accepts two optional arguments (server certificate and key PEM paths) so it can also offer Basic256Sha256 and Aes128Sha256RsaOaep endpoints for the live encrypted-connect tests in tests/test_opcua_sidecar.py. The certificate and key set is throwaway and self-signed, generated fresh per test session through openssl req, and never committed.

The one exception is the SOPS fixture tests/fixtures/secret_config.enc.json. Its private key is committed because it is test-only and guards only dummy values (see CONTRIBUTING.md).

Pitfalls

Defaults and builds

  • Security Policy None is still the default. Encryption is opt-in per site. install_open62541.sh builds with UA_ENABLE_ENCRYPTION=MBEDTLS (see section 5), but a site's opcua config that carries no certificate_path, private_key_path or trusted_certificates_path still connects at Security Policy None. None remains unsuitable for an untrusted network regardless.
  • A CI-green sidecar build isn't proof of the exact appliance binary. CI does not run on the appliance's operating system (Ubuntu 24.04 LTS Noble). A green pipeline validates the build script and the sidecar's own protocol contract, not that this exact binary is what a real appliance would produce. That is low-risk for the apt-installed tools elsewhere in CI (age, mosquitto, sops). It is worth naming here because a compiled C library is a bigger gap than an apt package pin.

The C sidecar

  • open62541's own logging is redirected at the file-descriptor level, not just its config->logging pointer. open62541's default logger writes to the C library's stdout, and several internal subsystems (EventLoop, ConnectionManager, SecureChannel) each pick up their own logger reference at different points during setup. Overriding just UA_ClientConfig.logging left some of them still writing to stdout in testing, which is fatal here because stdout is the protocol channel. sidecar/opcua/main.c instead duplicates the process's real stdout to a separate fd before redirecting fd 1 itself to /dev/null, and the send_* functions in protocol.c write to that duplicate. This guarantees isolation whichever internal subsystem is logging, rather than chasing every logger reference individually.
  • A UA_FieldTargetVariable needs its whole struct zeroed, not just its nested .targetVariable.
    • UA_Server_DataSetReader_createTargetVariables's target struct carries an externalDataValue sibling field (open62541's RT fast path: write directly into caller-owned memory instead of going through the normal Write service). It is read as "RT-path enabled" whenever it is non-NULL.
    • Initializing only the nested .targetVariable through UA_FieldTargetDataType_init leaves externalDataValue holding garbage stack memory in a stack-allocated UA_FieldTargetVariable. open62541's own tutorial_pubsub_subscribe.c gets away with it because its target_var array comes from UA_calloc, already zeroed.
    • The non-NULL garbage is dereferenced as a real pointer on the very first message received, segfaulting deep inside UA_DataSetReader_process.
    • The sidecar does an explicit memset(&target_var, 0, sizeof(target_var)) before setting any field.
  • subscribe and pubsub_subscribe each need their own mutex, held only for the duration of one iteration, not the whole background loop. A naive "iterate forever while holding the lock" thread would starve a later command on the same subsystem (for example disconnect after subscribe) from ever acquiring the lock. client_iterate_loop and pubsub_iterate_loop (sidecar/opcua/main.c) lock, run exactly one UA_Client_run_iterate or UA_Server_run_iterate call, unlock, and only then loop back. That gives the stdin-reading thread a real window to get in between iterations.
  • pubsub_subscribe's embedded UA_Server binds port 0, never a fixed port. A single MES Node instance's config.opcua can point at more than one OPC UA source, which needs one sidecar process per source. A second concurrent pubsub_subscribe on the same appliance would collide with a fixed port the first already holds. Binding port 0 (PUBSUB_HOST_PORT in sidecar/opcua/main.c) lets the OS assign an ephemeral one. That is safe because this server is never dialed by anything: it only hosts the PubSub ReaderGroup and DataSetReader machinery, never a reachable session. Two sidecar processes can run pubsub_subscribe against the same publisher concurrently and both receive data.
  • subscribe creates one OPC UA Subscription per client, and each call adds a MonitoredItem.
    • handle_subscribe (sidecar/opcua/main.c) tracks g_has_subscription, which only stops a second Subscription from being created (each would run its own publish cycle for no benefit).
    • Every later subscribe reuses g_subscription_id and registers one more MonitoredItem on it, which is how several node_ids are watched.
    • It does not reject a repeat, unlike pubsub_subscribe (g_pubsub_server != NULL). Subscribing the same node_id twice gives two MonitoredItems and every data_change event for it is delivered twice, silently. Avoiding that is the caller's responsibility.
    • g_has_subscription is reset on disconnect, so subscribing again after a disconnect and reconnect cycle starts a fresh Subscription.

Process failure handling (Python side)

  • The System Connector abstraction covers subscriptions, not just one-shot reads. OpcuaConnector wraps connect and read (poll() and test_connection()) and also subscribe() and pubsub_subscribe(). Both subscription methods require on_event at construction rather than per call. SidecarProcess only accepts its on_event once, at its own construction, and a connector holds at most one sidecar for its whole lifetime. There is nowhere to plug in a later-supplied callback without a second layer of indirection. pubsub_subscribe() also needs its own pubsub_connection_url, pubsub_publisher_id, pubsub_writer_group_id and pubsub_dataset_writer_id profile fields, optional on OpcuaConnectorProfile, since a connector that only polls or does a client-server subscribe doesn't need them.

A dead sidecar process is distinguishable from a protocol-level failure

SidecarProcess.send() raises two different exceptions:

  • SidecarError when the sidecar reports {"ok": false}. It is alive, functioning, and correctly rejecting something, a bad node_id say.
  • The subclass SidecarProcessExited(SidecarError) when the process itself has exited.

A caller wanting to self-heal (rebuild and retry once, rather than fail forever) needs to tell these apart. Retrying against a freshly spawned process helps only in the second case, and would reproduce the identical error in the first.

OpcuaConnector._call() catches specifically SidecarProcessExited:

  1. It rebuilds the sidecar through sidecar_factory (_sidecar = None, _connected = False).
  2. It re-runs the whole ensure-a-ready-sidecar-then-send sequence, since the process could have died during the connect call inside _ensure_connected() just as easily as during the caller's own command.
  3. It retries exactly once. A second consecutive death propagates rather than looping.

Self-healing is scoped to a connector-owned sidecar only (sidecar= never supplied at construction). A caller-supplied sidecar's lifecycle is that caller's own responsibility, the same split close() uses. sidecar_factory= (distinct from sidecar=) exists so tests can inject a sequence of fake processes, one per (re)build, without disabling self-healing by accidentally marking the sidecar caller-owned.

A spawn failure has its own exception

test_connection()'s "never raises" promise needs this. A missing or non-executable sidecar_path (a plain misconfiguration, not a live or network condition) would otherwise raise a bare FileNotFoundError or OSError from subprocess.Popen. That would go straight through _ensure_sidecar(), poll() and test_connection()'s except SidecarError handler, which a raw OSError doesn't match. SidecarSpawnError(SidecarError) wraps it, so that handler catches it.

It is deliberately not self-healable (OpcuaConnector._call() only rebuilds on SidecarProcessExited). A missing binary is a configuration problem that retrying identically won't fix, unlike a process that started fine and later died.

A signal-killed sidecar breaks the write side before the read side sees EOF

send() catches OSError around self._process.stdin.write(...) and the flush, and raises SidecarProcessExited from it. That is the same exception a graceful EOF raises, because a killed process and an exited one are the same underlying condition and need the same handling.

Without it, a raw BrokenPipeError would escape test_connection()'s "never raises" promise and be invisible to OpcuaConnector._call()'s except SidecarProcessExited, so self-healing never triggered. It would also leave the dead process in place as a Z <defunct> zombie, since nothing would ever call .wait() on it.

With the detection in place, self-healing rebuilds the sidecar. Spawning the replacement runs Python's internal subprocess bookkeeping, which opportunistically reaps any of its tracked children that have already exited, so the old zombie is reaped as well.

_read_loop's readline() treats any OSError or ValueError as a clean EOF

An exception there would otherwise kill the background reader thread and skip the pending-waiter cleanup that only the loop's normal exit reaches. An example is UnicodeDecodeError, itself a ValueError subclass, raised when the sidecar writes bytes that aren't valid text over a pipe opened in text=True mode.

The consequence would be that send() hangs for its entire timeout and raises a bare queue.Empty, not a SidecarError. That is invisible to OpcuaConnector._call()'s self-healing, on every subsequent call against the same sidecar. So the loop breaks on those errors into the same cleanup path as EOF, and the same SidecarProcessExited.

Independently, send() checks self._reader_thread.is_alive() before doing anything else. A call against an already dead sidecar then fails immediately, rather than registering a waiter nothing will ever fill and sitting out the full timeout.

Design and testing

  • MesIngestion has no explicit-versus-inferred branch of its own, and should not grow one. A branch in ingest() on whether the record has a direct identifier field would duplicate IdentityResolver's Gate and drift from it. The seam is one level up, at Data Transformation Layer registration (which source_type a Node instance's config wires to which transform). ingest() itself stays a single, unbranching pipeline for both paths.
  • A fake SidecarProcess's readline() must be gated on a matching write(), not pre-loaded. SidecarProcess's background reader thread starts consuming its process's stdout immediately in __init__, because it has to in order to never miss a real async event line. A fake stdout backed by a plain pre-loaded list lets that thread race ahead of send()'s pending-waiter registration. It then silently drops a response meant for a request that hasn't been sent (and hence hasn't registered its waiter) yet. The _FakeProcess classes in tests/test_opcua_sidecar.py and tests/test_connector_opcua.py instead release exactly one queued line per write() call (a threading.Semaphore), reproducing the causality a real pipe has for free. An unsolicited= count pre-releases lines with no write behind them at all, for tests that need to simulate a genuinely async event push.

Release: v0.11.0