Search and contents

Node Runtime: Ingestion Producer & Trigger Dispatch Consumer

This guide covers how engine/node_runtime.py implements the Node Runtime, the piece that makes a Node instance actually run continuously.

It repeatedly calls the mechanisms between a System Connector and a dispatched Task (TransformationRegistry, IdentityResolver, MesIngestion.ingest(), TriggerQueue.claim() and dispatch_claimed_entry()) in a long-running process. It does so as two composable pieces that are independently testable:

  • a Trigger Dispatch consumer loop (sections 1 to 3);
  • per-Node-Type ingestion producers and pollers (sections 4 to 6).

1. Trigger Dispatch consumer loop

from engine.activity_log import ActivityLog
from engine.node_runtime import TriggerHandler, TriggerHandlerRegistry, run_trigger_dispatch_loop
from engine.trigger_queue import TriggerQueue
from engine.try_catch import RetryPolicy

queue = TriggerQueue()
activity_log = ActivityLog()

handlers = TriggerHandlerRegistry()
handlers.register(
    "order_release",
    TriggerHandler(
        step=process_order_release,  # (payload: dict, entry: TriggerQueueEntry) -> Any
        task_type="ingestion-time classification",
        retry=RetryPolicy(max_attempts=3),
    ),
)

run_trigger_dispatch_loop(
    queue,
    activity_log,
    handlers,
    node_type="MES",
    node_instance_id="mes-line-3",
)  # blocks forever - run this as the node process's own main loop

TriggerHandlerRegistry maps trigger_type to TriggerHandler. It is the same keyed-registry dispatch shape that ConnectorRegistry and TransformationRegistry use (engine/registry.py), for the same reason: trigger_type was designed as a column, not a per-type queue, so registering a new one needs no change to the loop itself.

What the loop does

Each pass claims at most one pending row and dispatches it through dispatch_claimed_entry (see trigger-dispatch-queue.md), using its registered handler's step, retry and repair.

  • No pending row. claim() returning None makes the loop sleep for claim_poll_interval (default 0.5 s) rather than busy-polling Postgres.
  • Scheduled tasks (below) each run on their own independent background thread, not inline in this loop. A slow or blocking scheduled task can therefore never delay claiming and dispatching an already-pending row.

TriggerHandler.step takes two arguments

step receives the claimed row's payload dict (dispatch_claimed_entry's own contract) and the genuine claimed TriggerQueueEntry itself.

  • A handler that only needs payload can ignore the second argument (lambda payload, _entry: ...).
  • One composing an already-built, self-logging Task class that expects a real TriggerQueueEntry needs the genuine row, not a fabricated stand-in. CaseTriage.process in engine/case_triage.py is an example: it reads entry.id and entry.trigger_type directly for its Activity Log reference_ids.
  • dispatch_claimed_entry itself is never touched to make this work. run_trigger_dispatch_loop adapts a two-argument step into the one-argument shape dispatch_claimed_entry calls, closing over the claimed entry it already has in scope (_bind_entry, private).

An unrouted trigger_type

A claimed row with no registered handler is dead-lettered through the normal dispatch path. That path uses a step that always raises PromptCausedFailure, with retry=RetryPolicy(max_attempts=1). It does not crash the loop or leave the row claimed forever. This is the same fail-safe-and-report stance the Conformance Suite established for an unregistered source_type (engine/conformance.py).

2. Crash recovery: reclaim_orphaned_claims

run_trigger_dispatch_loop calls queue.reclaim_orphaned_claims() once at startup, before its first claim(). It resets every row still claimed back to pending.

This is what keeps a crash mid-dispatch from orphaning a row. Exactly one consumer loop runs per node instance, so any row already claimed when a loop starts can only be a previous, crashed run's leftover, never a row a concurrently running claimer legitimately holds. Restart requeues it through claim() and dispatch_claimed_entry() like any other pending row, still bounded by that dispatch's own Try/Catch retry policy.

3. Scheduled checks (and polling producers)

from engine.node_runtime import ScheduledTask

task = ScheduledTask(
    name="spc-deviation-check",
    interval_seconds=30.0,
    run=lambda: deviation_flagging.check_batch(fetch_latest_points()),
)
run_trigger_dispatch_loop(
    queue, activity_log, handlers, node_type=..., node_instance_id=..., scheduled_tasks=[task]
)

The "scheduled check" vocabulary (Deviation Flagging's check_batch, for example) and a polling Ingestion Producer's poll cadence are the same primitive: "run this callable every interval_seconds". Both share ScheduledTask rather than each feature inventing its own timer.

Each ScheduledTask runs on its own background thread, started by run_trigger_dispatch_loop itself and joined in its own finally block. It is not called inline from the claim/dispatch loop.

  • task.run() fires immediately, then again every interval_seconds. The wait between firings is stop_event.wait(interval), so a shutdown mid-wait is noticed immediately rather than only once the full interval elapses.
  • Why a thread. A ScheduledTask's run may do real I/O that can block for longer than a heartbeat, such as a poll against a flaky OPC UA sidecar. Inline execution would stall claiming and dispatching an already-pending row that has nothing to do with that poll.
  • Isolation. A genuine bug in one task's run kills only that task's own thread (Python's default threading.excepthook), not the whole dispatch loop.

4. Per-Node-Type Ingestion Producer: MES

from engine.connector import OpcuaConnectorProfile
from engine.node_runtime import MesIngestionProducer

producer = MesIngestionProducer(
    OpcuaConnectorProfile(endpoint="opc.tcp://plc.line3:4840", node_id="ns=1;i=5000"),
    mes_ingestion,  # an already-built engine.mes_ingestion.MesIngestion
    source_type="mes-opcua-explicit",
    trigger_type="order_release",
)
producer.run()  # starts the subscription and returns - events keep arriving after this

How run() behaves

  • Subscribing. run() calls OpcuaConnector.subscribe() (or pubsub_subscribe() if built with pubsub=True) and returns once subscribed. It doesn't loop itself for delivery, since that already happens on the sidecar's background reader thread (engine/opcua_sidecar.py) once subscribed.
  • Retrying the first subscribe. It does retry its own initial subscribe attempt, up to INGESTION_STARTUP_RETRY_ATTEMPTS times (INGESTION_STARTUP_RETRY_DELAY_SECONDS apart) on SidecarError. See the last Pitfalls entry for why this matters.
  • One ingest per event. Each delivered event turns into exactly one MesIngestion.ingest() call, with a fresh uuid4() trigger_id per event. OPC UA's data_change and pubsub_data events carry no sequence number to derive a redelivery-stable id from.

The producer owns its connector

The producer owns its OpcuaConnector. The connector must be built with on_event pointing back at the producer's own handler, so construction order requires the producer to build the connector itself, not accept a pre-built one.

Test injection uses process_factory, the same SidecarProcess-level hook the tests in test_connector_opcua.py use, not sidecar=. See MesIngestionProducer.__init__'s docstring for why.

Other producers

The other producers in engine/node_runtime.py follow the same convention: a run()- or poll_once()-shaped entrypoint per source, reusing ScheduledTask for a poll cadence rather than new machinery.

ProducerSourceBehavior
MqttIngestionProducer MES on a plant MQTT broker (mqtt section) A message is already a whole record, so nothing is buffered across messages and no first value is suppressed. The connector's handler only puts the record on a bounded in-memory queue. One worker thread runs ingest() in arrival order and then acknowledges the message. Redelivery is caught by the record's trigger_id.
DatabaseLogIngestionProducer MES on a target's database log (database_log section) poll_once() runs one DatabaseLogScan per poll_interval_seconds, reading rows past the stored watermark. A row the Trigger Dispatch Queue or the dead-letter table already holds is not offered to ingest() again. A run of max_consecutive_rejections dead-lettered rows stops the scan for the life of the process (one Activity Log entry, the watermark left where it was). A failing poll writes one poll failed: entry when the failure first appears or its message changes, and one poll recovered: when a later poll works. poll_interval_seconds is at least 1.
ErpIngestionProducer ERP, ScheduledTask-shaped over REST polling (poll_interval_seconds in engine/erp_config.py) An unchanged poll result is deduped. The last changed poll is published as one immutable LastPoll (raw record plus the material_id that ErpIngestion.ingest resolved for it).
ScheduleIngestionProducer Production Scheduling The same shape as the ERP producer. A changed record with the same schedule_id is a Schedule Revision that ProductionSchedulingIngestion.ingest reconciles.
OpcuaMaterialConsumptionPoller MES's material_consumption poll Reports each new material_id string observed on one OPC UA node, which node_main.py binds to a GenealogyLinkTask.run call.

Shared helpers and constants

  • poll_or_log wraps a scheduled poll so any exception is logged and retried on the next tick.
  • observed_only_handler() is a TriggerHandler that records an observation without further work (task type trigger-dispatch: observation recorded).
  • Constants: DEFAULT_CLAIM_POLL_INTERVAL 0.5 s, SCHEDULED_TASK_SHUTDOWN_JOIN_TIMEOUT 5.0 s, INGESTION_STARTUP_RETRY_ATTEMPTS 5 and INGESTION_STARTUP_RETRY_DELAY_SECONDS 3.0 s.

5. Scalar-value poller feeding a threshold check: OpcuaScalarDeviationPoller

from engine.connector import OpcuaConnector, OpcuaConnectorProfile
from engine.deviation_flagging import (
    DeviationFlagging,
    DeviationRule,
    DeviationRuleRegistry,
    ThresholdOperator,
)
from engine.node_runtime import OpcuaScalarDeviationPoller, ScheduledTask

rules = DeviationRuleRegistry()
rules.register(
    "mes-weld-strength",
    DeviationRule(field="weld_strength_n", op=ThresholdOperator.LT, threshold=8.5),
)
deviation_flagging = DeviationFlagging(rules, queue)

connector = OpcuaConnector(
    OpcuaConnectorProfile(endpoint="opc.tcp://plc.line3:4840", node_id="ns=2;s=LotA.WeldStrengthN")
)
poller = OpcuaScalarDeviationPoller(
    connector, deviation_flagging, data_source="mes-weld-strength", values_field="weld_strength_n"
)
task = ScheduledTask(name="weld-strength-check", interval_seconds=5.0, run=poller.poll_once)

This is a concrete instance of section 3's "scheduled check" primitive. It is built for a numeric telemetry point with no push subscription of its own, driving a threshold check (Deviation Flagging's weld-strength SPC check). It is the glue between OpcuaConnector.poll() and DeviationFlagging.check_batch, the same role MesIngestionProducer plays for the ingestion path.

Two distinct field names

  • poll_value_key (default "value") is OpcuaConnector.poll()'s fixed result-dict key. It is the sidecar RPC's "read" response shape, not a Node Type author's choice.
  • values_field is the DataPoint.values key the resulting point carries. It must match whatever DeviationRule.field the caller registered.

Deduplication

A repeated identical poll is deduped the same way MesIngestionProducer's data_change dedup guard does it. A poll cadence shorter than how often the underlying reading changes must not enqueue a fresh "deviation" row (and re-draft a disposition) on every poll of a value that hasn't moved.

A genuinely new reading always gets its own fresh uuid4() id and its own Trigger. It is deliberately not a value-derived deterministic id, since a real physical reading recurring at the same value at a later, unrelated time is still a fresh observation, not a redelivery of the earlier one.

The very first poll

An instance's very first poll is a third case, not just "changed" or "unchanged". By default it silently seeds the dedup baseline and returns, never reaching check_batch (or build_point, for OpcuaDerivedDeviationPoller below) at all. This is the same first-time suppression MesIngestionProducer._on_event applies to a subscription's initial-value announcement (section 4), applied to a poll cadence instead.

The reason: an OPC UA node has no "current state" distinct from whatever value it happens to hold the moment this poller's connector first reads it. A freshly reset target (a simulator's unset-value default, for example WeldStrengthN=0.0) would otherwise look exactly like a genuine reading on that first poll. That would be a spurious deviation on every MES startup, before any real event.

evaluate_first_poll=True opts a caller out of that suppression, so the first poll is evaluated exactly like every later one. It is a constructor keyword on both classes, plumbed from DeviationPollTarget.evaluate_first_poll (engine/deviation_flagging_config.py).

  • It is correct for a real PLC/SCADA. The value already sitting there is a genuine physical reading, not a reset artifact, and a Node restart shouldn't blind a quality check to an already in-progress real deviation.
  • It is safe for a simulated target once its own idle default is itself in-spec.
  • The weld-strength SPC check (engine/node_main.py) is wired this way, so the target's idle WeldStrengthN value must be in-spec (for example 9.5, not 0.0). Verifying that is the caller's job, not this class's. Passing evaluate_first_poll=True against a target whose idle default is genuinely out-of-spec reintroduces the exact spurious-deviation-on-startup failure this suppression exists to prevent.

6. A poller whose point needs deriving, not just renaming: OpcuaDerivedDeviationPoller

from engine.node_runtime import OpcuaDerivedDeviationPoller, ScheduledTask
from engine.exceptions import KindredError


def build_point(actual_hours_per_unit):
    return build_variance_data_point(  # engine/costing_variance.py - a live ERP query
        peer_client,
        data_point_id=uuid.uuid4(),
        order_id="ORD-1001",
        milestone_type="final",
        actual_cost=actual_hours_per_unit * 42.0,
        data_source="costing_milestone_variance",
        node_instance_id=node_instance_id,
    )


poller = OpcuaDerivedDeviationPoller(
    connector,
    deviation_flagging,
    build_point=build_point,
    exceptions=(KindredError,),
    context="costing-variance-poller:costing_milestone_variance",
)
task = ScheduledTask(
    name="costing-variance:costing_milestone_variance", interval_seconds=5.0, run=poller.poll_once
)

This has the same poll-cadence and dedup shape as section 5's OpcuaScalarDeviationPoller. It is for a check whose DataPoint can't be built from the raw reading alone: Costing Milestone variance needs a live ERP standard-cost figure layered on top of the raw actual-cycle-time reading first.

  • build_point is that layering step, supplied by the caller (engine/node_main.py). The class itself stays Node-Type and use-case agnostic. Nothing in engine/node_runtime.py imports engine.communication_interface or engine.costing_variance to make this work.
  • exceptions= names what build_point can raise as a recoverable, log-and-retry-next-tick failure (for example engine.exceptions.KindredError, covering an unreachable ERP peer or a non-positive standard cost). It follows the poll_or_log contract every other poll-cadence caller in this module follows, applied to the point-builder step rather than just the raw connector poll. An exception not named in exceptions= still propagates uncaught, as any other genuine bug does.
  • Dedup runs before build_point. The dedup guard runs before build_point is ever called, not after. An unchanged reading must not spend a second live peer query re-deriving the same DataPoint it already derived, not just avoid re-enqueueing a duplicate Trigger.

Pitfalls

The dispatch loop and scheduled tasks

  • A genuine bug in a handler's step propagates uncaught, the same as dispatch_claimed_entry itself (see the Pitfalls in trigger-dispatch-queue.md). This kills the whole run_trigger_dispatch_loop thread, leaving that one row claimed. A process supervisor restarting the node process is what resolves it: the next run_trigger_dispatch_loop call reclaims the row through reclaim_orphaned_claims() at its startup. A deterministically buggy step will crash the loop again on that same row. That is a real bug needing a code fix, not something retried away.
  • reclaim_orphaned_claims() assumes a single consumer per node instance. It unconditionally resets every claimed row, with no claimed_at age check. That is safe only because exactly one run_trigger_dispatch_loop is ever meant to run against one node instance's queue at a time. A second, concurrently running loop against the same table would have its own in-flight claims reset out from under it.
  • ScheduledTask.run exceptions are not caught by its own background thread.
    • Unlike a claimed row's step (wrapped in Try/Catch through dispatch_claimed_entry), a scheduled task's run is called directly. The same "any other exception is a genuine bug" stance applies, but there is no retry or dead-letter wrapping around it.
    • Since each ScheduledTask runs on its own thread, an uncaught exception there kills only that one task's own cadence. From the loop's perspective that is silent: Python's default threading.excepthook prints it to stderr, nothing more. The rest of the dispatch loop and every other scheduled task keep running unaffected.
    • A scheduled task that itself needs Try/Catch semantics (for example a polling producer whose connector can be transiently unreachable) should wrap its own run accordingly. run_fault_tolerant_ingestion in engine/conformance.py is the existing fetch-plus-ingest-under-Try/Catch shape for exactly that case. Don't rely on thread isolation alone to keep a real, recurring failure from going unnoticed.

The pollers

  • OpcuaScalarDeviationPoller.poll_once fails silently on a wrong node_id or field mismatch. A poll_value_key that doesn't exist in OpcuaConnector.poll()'s result (a misconfigured node_id reading the wrong kind of node), or a non-numeric value, both just skip that poll with no error and no Trigger enqueued. This is the same "not every gap is a failure" stance DeviationFlagging.check_batch takes for a point missing its rule's field. A genuinely misconfigured deviation_flagging fragment therefore degrades to silent do-nothing, not a startup-time or first-poll error. It is worth a periodic sanity check against a known-good reading during commissioning. This module does not surface it on its own.
  • A transient SidecarError during poll_once is caught and logged (logger.warning), not raised. run_trigger_dispatch_loop calls ScheduledTask.run with no Try/Catch wrapping of its own (see the pitfall above). An uncaught poll() failure would permanently kill this poller's scheduled-task thread on the very first transient hiccup, silently ending the SPC check's cadence for the rest of the process's life. The main dispatch loop and every other scheduled task are unaffected either way, since each runs on its own thread, but losing this one check's cadence to a single transient failure would still be a real, silent gap. The next scheduled tick tries again instead. This method has no Activity-Log-backed retry budget of its own to exhaust the way a claimed row's step does.
  • The dedup baseline (_last_value) is only ever updated once a poll's value is confirmed numeric. A single bad or non-numeric reading between two identical valid ones is skipped without touching _last_value. It must not corrupt the baseline a later, still-identical valid reading needs to dedup correctly against. Otherwise the same ongoing excursion would spuriously re-fire a second Trigger the moment a transient bad reading interrupts an otherwise unchanged value.
  • A poll cadence coarser than the underlying reading's real-world reset window can miss a transient excursion entirely. poll_once only ever sees whatever value is current at the moment it polls, never a history of readings between polls (unlike a client-server data_change subscription, which observes every transition). poll_interval_seconds is a per-Node-instance config value precisely so an operator can tune it against how fast the monitored process actually changes.
  • A same-value poll is skipped, and logged at DEBUG.
    • OpcuaDerivedDeviationPoller.poll_once (and OpcuaScalarDeviationPoller and OpcuaMaterialConsumptionPoller, which delegate to it or share its shape) does not re-fire a check on an unchanged reading.
    • The skip logs at DEBUG ("same-value poll skipped (value=...) - poller is running, reading just hasn't changed since the last tick"). OpcuaMaterialConsumptionPoller logs the same with material_id. A same-value skip can therefore be told from a poller that never started, an unreachable sidecar or a wrong config.
    • Re-sending an identical value therefore produces no trigger_queue row and no activity_log entry, because the poller's in-memory _last_value already holds it. Restarting the database or a driver process does not clear a running node's in-memory baseline.
  • A test or driver script that calls poll_once or ScheduledTask.run exactly once and expects an immediate fire must seed the baseline first, unless its poller was built with evaluate_first_poll=True.
    • With the default False, an instance's very first poll never reaches check_batch at all (see "The very first poll" in section 5). Call poll_once once to seed, then poll again for the reading a test actually wants evaluated.
    • A Node instance's own run_trigger_dispatch_loop does this correctly with no caller action. _run_scheduled_task_loop runs task.run() once immediately and then every interval_seconds, so the immediate call becomes the seed and the next scheduled tick is real. The gap only bites a hand-driven test that never lets that natural second call happen.
    • A poller built with evaluate_first_poll=True has no such gap: its first poll_once evaluates immediately, with no seed call needed in a test or in the field.

The MES ingestion producer

  • MesIngestionProducer._on_event's first-event suppression survives a mid-session OPC UA reconnect.
    • The suppression's accepted tradeoff is that a MES process that restarts mid-shift won't pick up a real in-flight order, and Reconciliation recovers state after a restart. That is deliberate for an actual restart, where self._last_data_change_value is empty because the whole object was rebuilt.
    • A reconnect must not re-arm it. OpcuaConnector's self-healing resubscribe reissues a fresh monitored_item_id for every item, so a dedup baseline keyed by monitored_item_id would see first_time true again for every affected item and silently absorb the next event.
    • The baseline is therefore keyed by node_id, which never changes across a resubscribe. self._item_node_id maps each reissued monitored_item_id back to its node_id, populated by run().
    • run() logs an INFO line when it subscribes a node_id it already holds ("monitored_item_id reissued as ... this is a mid-session OPC UA reconnect, not a process restart; dedup baseline for this node_id is preserved").
    • A genuine process restart still starts with an empty baseline, as designed.
  • MesIngestionProducer.run() retries its own initial subscribe attempt, bounded.
    • deviation_flagging, costing_variance and material_consumption all run through poll_or_log, which catches any exception and retries on the next tick, unbounded. But run() is called directly in node_main.py's main() (runtime.producer.run()), with nothing between it and an uncaught exception killing the whole process.
    • The ingestion producer is the one connector whose failure means this Node instance can't ingest anything, not just lose one data source. A target OPC UA server still settling from its own restart can reject the very first subscribe attempt with SidecarError: BadConnectionRejected.
    • So run() retries its subscribe attempt up to INGESTION_STARTUP_RETRY_ATTEMPTS times (INGESTION_STARTUP_RETRY_DELAY_SECONDS apart) on SidecarError. It re-runs the whole attempt from the top each time rather than tracking which node_id failed. That is safe, since a node_id already subscribed from an earlier partial attempt just logs as a resubscribe (section 4's behavior).
    • It is deliberately bounded, not unbounded like the pollers. A genuinely broken config (wrong endpoint, wrong node_id) still surfaces as a clear failure within a bounded window (5 attempts, about 12 s by default), rather than hanging forever against a target that will never come up. This is the same blind-retry-then-give-up tradeoff poll_or_log accepts. It does not try to distinguish "target unreachable" from "bad config" SidecarError subtypes first.

Release: v0.11.0