Search and contents

Cross-node query and narrative wiring

This guide covers how engine/node_main.py and engine/erp_main.py wire three Tasks into a running node process:

  • Order status query (engine/order_status_query.py)
  • Inventory shortage/at-risk-order explainer (engine/inventory_shortage.py)
  • Order-trail/genealogy narrative (engine/order_narrative.py)

See ai-narrative-drafting-task-wiring.md for the Tasks themselves. Nothing in ERP or MES runtime startup depends on this wiring.

Which side queries, which side answers

Neither OrderStatusQueryTask nor InventoryShortageExplainerTask cares which Node Type instantiates it. Both take a peer_client and peer_node_type at construction or call time and work in either direction. The direction for each follows which Node Type's own local data answers the question.

QueryAnswered byQueried by
order_status_query MES (_answer_order_status, engine/node_main.py) ERP (order_status_query_task, engine/erp_main.py)
in_progress_wip_for_material MES (_in_progress_orders_for_material, engine/node_main.py) ERP (inventory_shortage_task, engine/erp_main.py)
Order-trail/genealogy narrative MES (order_narrative_task) No peer query. Local only.

Why each direction

  • order_status_query. An order's current floor status (in-progress, blocked, completed, flagged or at-risk) is what MES's own OrderRelease and OrderCompletion ingestion already resolves onto the order's IdentityRecord.attributes["status"]. That happens in ingest_and_enqueue in engine/ingestion_pipeline.py, and Reconciliation's merge_attributes keeps it current. MES already knows this without a live poll of anything.
  • in_progress_wip_for_material. This matches the module docstring of engine/inventory_shortage.py: the shortage is "correlated against a peer node's current in-progress work-in-process". InventoryShortageExplainerTask's peer_node_type default is already "MES". The query itself is described in ai-narrative-drafting-task-wiring.md, and MES is its live answering side.
  • Order-trail/genealogy narrative. OrderNarrativeTask never queries a peer. It takes an already-assembled OrderTrail or Genealogy as its input.
    • assemble_order_trail (engine/order_trail.py) reads this Node's own Activity Log and IdentityStore. Given a peers client, it asks each declared peer for its own entries and record over the Communication Interface (see section 4 of order-trail-assembly.md).
    • assemble_genealogy (engine/traceability.py) does the same with peers (see section 4 of traceability.md).
    • The Task is built on MES because MES already carries store, activity_log and inference_client.

engine/node_main.py

MES answers peer queries

MES builds a PeerListener, so order status and in-progress-WIP queries can be asked at MES, as erp_main.py's listener answers ERP's.

_build_mes_answer dispatches on the shape of the incoming envelope, not just on event_fields["query"] the way erp_main.py's _build_answer does:

Incoming envelopeAnswered by
event_fields["query"] == IN_PROGRESS_WIP_QUERY (the convention in engine/inventory_shortage.py) _in_progress_orders_for_material
A bare order_id identity key with no event_fields at all The order status answer. OrderStatusQueryTask's outgoing envelope (engine/order_status_query.py) never sets a query marker of its own. This is the one shape no other query this Node instance answers can produce, so it is dispatched on directly. That avoids adding a marker field to an already built, already tested Task module.
event_fields["query"] == "activity_log_entries" or "identity_record" This Node's own Activity Log entries, or its own identity record for one (entity_type, reference_id). Both are answered from its own stores only (see communication-interface.md). Every Node Type answers both.
Anything else Empty event_fields: the same fail-safe-and-report stance erp_main.py's _build_answer takes.

Where _in_progress_orders_for_material reads from

It reads two already-existing local stores, not a fresh live poll. MES's own OPC-UA ingestion is subscription-shaped (see the module docstring of engine/node_runtime.py). There is no per-order "read this one live" query like the RestPollingConnector.poll(path=...) override behind ERP's live standard_cost answer.

Instead, it works in three steps:

  1. Every material_id-linked order comes from the Genealogy Link entries in engine/traceability.py (activity_log.query(reference_id=material_id), filtered to TASK_TYPE_GENEALOGY_LINK).
  2. Each linked order is cross-referenced against its current IdentityRecord.attributes["status"].
  3. It reports every order still reading "in-progress", not just the first found. A shared material genealogy-linked to more than one order is not schema-prevented.

MesRuntime and order_narrative_task

MesRuntime carries store: IdentityStore. A caller needs it to assemble an OrderTrail or Genealogy before handing it to order_narrative_task.narrate(), and _answer_order_status needs it to look up an order's current status.

order_narrative_task is built whenever inference is configured. That is the same existing config fragment CaseTriage already requires, so no new Configuration Schema property is needed. It runs on demand: it is not scheduled and not wired to any TriggerHandler. This follows the "request/response shape, not a scheduled roll-up" precedent that time-ranged-activity-narrative.md established for TimeRangedActivityNarrativeTask. A caller assembles the trail or genealogy itself and calls .narrate(...) directly:

from engine.order_trail import assemble_order_trail

trail = assemble_order_trail(
    runtime.store, runtime.activity_log, order_id, peers=runtime.peer_client
)
narrative = runtime.order_narrative_task.narrate(trail)

A caller outside the process asks for the same narrative over HTTP. The Node can serve it behind a correlation token (see order-narrative-route.md), and the route is off until its port is set.

runtime.peer_client is None unless the site configures the Communication Interface. The trail then holds this Node's entries alone, and it says so: it is not complete, and its narrative opens with an "Incomplete Trail" section stating that no peers were asked. A caller that knows the site is a single Node passes single_node=True instead of peers, and the trail is complete when its own parts are.

The listener and the outgoing pair

The listener and the outgoing peer_registry and peer_client pair are built together, whenever communication_interface is configured at all. This is the same "optional at the top level" convention every other fragment follows.

The pair is not tied to the costing_variance branch. shift_handoff's optional live "current shift" peer query (see shift-handoff-live-license-gating.md) is a second, independent consumer, and it must not require costing_variance to also be configured.

engine/erp_main.py

Configuration

ERP has an inference config fragment and an outgoing PeerRegistry and PeerClient pair. erp_main.py's PeerListener is purely an answering collaborator, and the pair is what lets build_erp_runtime query a peer. node-types/erp/node_type.json declares:

"dependentRequired": {
  "inference": ["communication_interface"]
}

inference's schema fragment is a byte-for-byte copy of MES's (node-types/mes/node_type.json). InferenceClient is ERP's only consumer, for order_status_query_task and inventory_shortage_task below. The dependentRequired rule mirrors the config-time-enforced ordering that shift_handoff's own dependentRequired applies for MES.

What build_erp_runtime builds

Whenever inference is configured, build_erp_runtime builds:

  • an InferenceClient;
  • an outgoing PeerRegistry and PeerClient pair, mirroring the costing-variance-poller pair in engine/node_main.py, including a "peer-rescan" ScheduledTask on the same PEER_RESCAN_INTERVAL_SECONDS cadence;
  • the two on-demand Tasks themselves, OrderStatusQueryTask and InventoryShortageExplainerTask, both querying "MES" as their peer.

Neither Task is scheduled or registered on handlers. A caller invokes .query() or .explain() directly:

result = runtime.order_status_query_task.query(order_id, "MES")
explanation = runtime.inventory_shortage_task.explain(
    MaterialShortage(material_id=material_id, shortage_quantity=160.0, unit="each")
)

node-types/erp/example_node_config.json

"inference": {
  "endpoint": "http://ollama.example.local:11434",
  "model": "example-llm",
  "context_window_tokens": 32768,
  "reserved_output_tokens": 2048,
  "reasoning_effort": "none",
  "backend_trust": "local"
}

This matches the inference fragment of MES's example config exactly (same endpoint, model and limits). The example configs share one inference target across all Node Types, not one scoped per Node Type.

Testing without a live simulator

  • MES's answering side is proved directly in tests/test_node_main.py. A raw PeerClient stands in for ERP, the same "stand in for the other side" precedent the costing-variance tests establish in reverse. It queries a real loopback PeerListener seeded with real IdentityStore and ActivityLog state.
  • ERP's querying side is proved in tests/test_erp_main.py against a real MES peer. _build_minimal_mes_peer builds a genuine engine.node_main.build_mes_runtime instance, with bare opcua and communication_interface config and nothing else (the rest of the MES runtime is covered elsewhere), and points ERP's communication_interface.peers at its real bound loopback port. These tests run against a running MES+ERP pair, not a stand-in on either side, for both order_status_query_task and inventory_shortage_task.
  • A shared table. activity_log (tests/conftest.py) is the one real production table shared across every test in the suite. It is not isolated per test the way the store and queue fixtures are (IdentityStore and TriggerQueue both take a table_name= override; ActivityLog doesn't). Both integration tests therefore use a uuid.uuid4()-suffixed material_id rather than a fixed literal (already reused by several other tests in tests/test_erp_main.py), so activity_log.query(reference_id=...) can't pick up an unrelated test's entries.

Pitfalls

  • _answer_order_status validates the stored status against engine.envelope.Status's literal set (engine.envelope.is_status) before putting it on the wire. A misconfigured field_map can resolve some other string, or a value that is not a string at all (a list, an object), into attributes["status"]. That answers status=None, the same fail-safe-on-the-unknown stance that OrderStatusQueryTask's ABNORMAL branch expects. The alternative would be handing a CrossTypeEnvelope a value its own Status field would reject.
  • _in_progress_orders_for_material only finds orders if something upstream has written Genealogy Link entries. It walks the entries that genealogy-link a material to orders, a mechanism Traceability builds for a different purpose. It never queries the shortage-observing order's own material.
    • engine/node_main.py's optional material_consumption config fragment is that something. engine.node_runtime.OpcuaMaterialConsumptionPoller polls a configured OPC UA node for a material_id reading and calls GenealogyLinkTask.run against this Node instance's configured order_id whenever it changes. This is the same "integrator addresses the gap at the source" framing the module docstring of engine/traceability.py documents for genealogy data generally.
    • A simulator's consume_material command is one such source.
    • material_consumption is optional, not dependentRequired on anything. A Node instance that never configures it answers this query [].
  • ERP's build_erp_runtime has no close-on-partial-failure safety net, unlike MES's _build_optional_mes_collaborators and _close_mes_collaborators pair. If InferenceClient succeeds but a later collaborator in the same if "inference" in config: block raises (a missing prompt asset file, say), inference_client's eagerly opened httpx.Client leaks. The same gap exists for connector and producer in that function.
  • order_narrative_task shares MES's single inference_client with CaseTriage. Both are built in the same if "inference" in config: branch, and ShiftHandoffTask shares it too. A real deployment's inference endpoint sees all of these Tasks' calls.

Release: v0.11.0