Search and contents

MES runtime

How build_mes_runtime in engine/node_main.py wires the standalone, independently tested Task modules (FirstArticleInspectionTask, CaseTriage, ShiftHandoffTask and others) into a running node process. It provides two chains:

  • real ingestion-time classification on the order_release Trigger;
  • the weld-strength poll, then Deviation Flagging, then Case Triage.

What the runtime does

order_release dispatches to real First Article Inspection

_qualification_observation builds a Qualification IdentityObservation from the Trigger's own event_fields. The fields it reads are vendor and vendor_lot, when a Node instance's own field_map is configured to report them.

  • reference_id follows the "{vendor}:{vendor_lot}" convention that tests/test_first_article_inspection.py already established.
  • It is None when either field is absent, which FirstArticleInspectionTask's no-reference-id branch already handles.

FirstArticleInspectionTask.run is called directly, and still writes its own inner ActivityLogEntry (task_type="ingestion-time classification"). That sits on top of the outer, generic dispatch entry written by dispatch_claimed_entry (task_type="mes-order-event-ingestion-time-classification"). Two entries per event is deliberate. It is the same nested-Task logging shape that the InventoryShortageExplainerTask docstring in engine/inventory_shortage.py already documents.

A weld-strength ScheduledTask feeds Deviation Flagging

OpcuaScalarDeviationPoller (engine/node_runtime.py, see docs/operations/node-runtime.md) polls the configured OPC UA node on its own cadence and calls DeviationFlagging.check_batch.

"deviation" dispatches to CaseTriage.process

CaseTriage.process needs the real claimed TriggerQueueEntry, because it reads entry.id and entry.trigger_type for its own Activity Log reference_ids. That is why TriggerHandler.step has a two-argument (payload, entry) contract (docs/operations/node-runtime.md).

A drafted disposition is submitted to SignoffStore the same way every other drafted case summary already is.

Two Configuration Schema fragments

Both are optional at the top level, the same convention that communication_interface established. A Node instance's config only needs to declare what it actually uses.

"config": {
  "opcua": { "...": "..." },
  "inference": {
    "endpoint": "http://ollama.example.local:11434",
    "model": "example-llm",
    "context_window_tokens": 8192,
    "reserved_output_tokens": 400
  },
  "deviation_flagging": {
    "node_id": "ns=2;s=LotA.WeldStrengthN",
    "data_source": "mes-weld-strength",
    "field": "weld_strength_n",
    "op": "lt",
    "threshold": 8.5,
    "poll_interval_seconds": 5.0
  }
}

inference is the INFERENCE_CONFIG_SCHEMA fragment (engine/inference_config.py). build_inference_profile builds the InferenceClient that CaseTriage needs.

deviation_flagging is the fragment in engine/deviation_flagging_config.py:

  • field, op and threshold build a DeviationRule (engine/deviation_flagging.py, unchanged).
  • Beside opcua, node_id, data_source and poll_interval_seconds build a DeviationPollTarget that feeds OpcuaScalarDeviationPoller. Beside mqtt or database_log there is no poller (see the record forms).
  • Two keys are optional: description, which is carried on the DeviationRule and into a flagged deviation's payload as rule_description, and evaluate_first_poll (default false; see node-runtime.md).

There is a single rule per Node instance, not a list, since one configured poll-driven deviation check is all a Node instance carries. The Costing Milestone variance check computes its own DataPoint from a live peer query instead of an OPC UA poll, so it doesn't reuse this fragment's node_id and poll shape either way.

deviation_flagging requires inference alongside it. The opcua section is needed only for its OPC UA form.

  • The pairing with inference is enforced by the dependentRequired constraint in the MES Node Type's config_schema (node-types/mes/node_type.json): "dependentRequired": {"deviation_flagging": ["inference"]} on the top-level config object. Which form of the fragment a Node may use is decided by its source, not by that constraint: beside opcua it names a node_id, and beside mqtt or database_log it names the field of each record and refuses node_id (see what is allowed beside which source). That rule is in engine/mes_check_forms.py, reported by the offline check and enforced when the Node is built. This expresses the pairing without coupling either fragment's own schema to the other.
  • It fails in load_node_config's schema-validation pass, before build_mes_runtime constructs a single collaborator. It is not a hand-written Python check partway through the function.
  • Without it, a "deviation" Trigger that the poller enqueues, with no CaseTriage handler registered to dispatch it, would dead-letter forever. The constraint turns that into a clear, immediate, load-time error.

Drift-check tests. Both fragments are hand-authored copies embedded in node-types/mes/node_type.json. Two tests guard against the embedded JSON silently drifting from the Python constant:

  • test_mes_node_type_fragment_matches_python_constant in tests/test_inference_config.py;
  • the copy guard in tests/test_deviation_flagging_config.py.

This is the same pattern that test_opcua_config.py established for MES's own "opcua" fragment.

The record forms, beside mqtt or database_log

Beside mqtt or database_log, deviation_flagging, costing_variance, material_consumption and instruction_bindings open no second OPC UA connection and have no poller. build_mes_runtime builds one object for each section that is present (RecordDeviationCheck, CostingVarianceCheck with RecordCostingCheck, RecordMaterialLink, RecordBindingEvaluation), and the order_release dispatch step hands each its record's mapped fields before it reconciles the order. None of them raises into the step: a value that cannot be used is logged and skipped, and the order's status goes through. The choice of form is the source: engine/mes_check_forms.py and instruction_binding_problems refuse a key that belongs to the other form, at build and in the offline check, and what is allowed beside which source has the table.

  • A reading is judged when it differs from the last one judged for its order, a marker kept on the order's identity record so it survives a restart (deviation_flagging, costing_variance). A material is linked once for each order, found by looking in the Activity Log first. A binding judges every record, and keeps its state in memory.
  • A costing check is queued as its own Trigger and priced by its own handler; an ERP that cannot be reached puts the check in a retry queue of its own that a scheduled task works through every 30 seconds, so an ERP outage never holds up an order's status.
  • A binding's task, instruction-bindings-records, runs every 5 seconds because nothing ticks when no record arrives; it starts the bindings, re-checks claims and settles waiting alerts.
  • The limits: a crossing with no further record is never confirmed, a binding remembers at most 4 096 orders and 8 192 readings, and a restart begins every binding's runs again. Instruction bindings says the rest.

Testing without a live simulator

tests/test_node_main.py drives the real production wiring throughout (build_mes_runtime and run_trigger_dispatch_loop, unmodified). It replaces only the two genuinely external boundaries:

  • InferenceClient's HTTP transport: an httpx.MockTransport, patched onto engine.node_main.InferenceClient for the duration of one build_mes_runtime call. Every other Task-level test in this suite uses the same convention.
  • One live OPC UA event, injected at MesIngestionProducer._on_event and OpcuaConnector.poll. This is the same private seam that the producer tests in tests/test_node_runtime.py use.

The suite therefore needs no compiled sidecar or simulator binary to run.

Pitfalls

  • First Article Inspection's own Mandatory-Human flag is still IdentityStore's PENDING status, not SignoffStore. See the Pitfalls of docs/operations/ai-narrative-drafting-task-wiring.md. The Trigger dispatch doesn't change which mechanism First Article Inspection flags through.
  • OpcuaScalarDeviationPoller's connector is a second, independent OpcuaConnector from the ingestion producer's own. A real MES Node instance opens two sidecar-backed connections against its OPC UA endpoint, one per subscribed or polled node.
    • It is built from build_opcua_connector_profile(opcua_config).model_copy(update={"node_id": poll_target.node_id}), not from a bare OpcuaConnectorProfile(endpoint=..., node_id=...). It needs the same username, password, sidecar_path and pubsub_* fields as the ingestion connector's profile, and only node_id differs.
    • main()'s finally block closes this connector and inference_client, both tracked fields of MesRuntime. A caller that builds MesRuntime by hand must close every collaborator it tracks: the producer, the deviation connector and the inference client, and also costing_variance_connector, peer_registry, peer_client and the rest the dataclass holds.

Release: v0.11.0