Search and contents

ERP Runtime Entrypoint

This guide covers how build_erp_runtime in engine/erp_main.py turns ERP's own config file into a running process, the way node_main.py does for MES. It wires together the ERP-side mechanisms: ErpIngestion, ErpReporting and the Communication Interface's PeerListener.

What the entrypoint does

engine/erp_main.py mirrors node_main.py's shape. build_erp_runtime reads ERP's Node Type and config file through the real production config-loading path (engine/config_loader.py) and builds ERP's collaborators. main() hands off to run_trigger_dispatch_loop exactly as MES's entrypoint does. This module owns no ingestion or dispatch logic of its own either.

A polling ingestion producer

ErpIngestionProducer in engine/node_runtime.py is the polling ingestion producer. REST has no push subscription the way OPC UA does, so a polling connector's own cadence drives ingestion.

  • Shape. It is ScheduledTask-shaped (a poll_once() method), rather than MesIngestionProducer's run()-started subscription.
  • Cadence. A Node instance's configured poll_interval_seconds (engine/erp_config.py) drives it through the same ScheduledTask mechanism OpcuaScalarDeviationPoller uses.
  • Deduplication. It skips an unchanged poll result, for the reason OpcuaScalarDeviationPoller's _same_value guard documents (_same_record, key-wise _same_value). A poll cadence shorter than how often the underlying Material record changes must not re-resolve Identity and enqueue a fresh Trigger on every poll of a record that hasn't moved.

A PeerListener answer callable

_build_answer (engine/erp_main.py) dispatches an incoming cross-node query on its event_fields["query"]:

Query (event_fields)Response (event_fields)Answered
{"query": "standard_cost", "milestone_type": ...} {"standard_cost": <float>} Live
{"query": "material_held_for_orders"} {"held_for_order": {<order_id>: <qty>, ...}, "on_hand": <float | None>} Local
{"query": "report", "trigger_type": ..., "report_id": ..., ...domain fields} {"reported": <bool>} Outward delivery
{"query": "activity_log_entries", ...} {"entries": [...], "next_cursor": ...} Local
{"query": "identity_record", "entity_type": ..., "reference_id": ...} {"record": {...} | null} Local

How each is answered:

  • standard_cost: live. It reuses the RestPollingConnector that the regular ingestion poll cadence already authenticates with. That connector is called again through its poll(path=...) override (engine/connector.py), pointed at the path from build_standard_cost_path (default /costing/standard-rate), and polled fresh on every incoming query. There is one connector and one cached bearer token, not a second independently authenticating one. standard_cost = labor_rate_per_hour * standard_hours_per_unit, a per-unit figure (for example $42/hr × 0.5 hr/unit = $21/unit).
  • material_held_for_orders: local. It reads ErpIngestionProducer.last_poll, an atomic (record, material_id) snapshot of whatever this instance's regular ingestion poll cadence already knows. It makes no fresh call.
  • report: outward delivery. _answer_report strips query, trigger_type and report_id and hands the rest straight to ErpReporting.report(), reusing the same connector and its cached bearer token. reported is True only once delivery to the real ERP system genuinely succeeded (Outcome.SUCCEEDED), not merely because this Node instance was reachable. The module docstring of engine/erp_reporting_wiring.py describes the querying side (_order_release_step and _costing_variance_point_builder in engine/node_main.py).
  • activity_log_entries: local. This Node's own Activity Log, one page at a time. See communication-interface.md.
  • identity_record: local. This Node's own Identity Store, the one record named. See communication-interface.md.

Every query above is logged through the existing Task Execution logging for free. run_cross_node_dialogue (engine/communication_interface.py) already writes exactly one ActivityLogEntry per incoming query (task_type=cross-node-dialogue), whichever query this Node instance's answer callable ran. No branch above needs its own logging call.

Why material_held_for_orders is its own convention

ai-narrative-drafting-task-wiring.md's cross-node convention table already documents in_progress_wip_for_material (IN_PROGRESS_WIP_QUERY in engine/inventory_shortage.py). That convention is answered by MES, with ERP as the querier: InventoryShortageExplainerTask's peer_node_type default is "MES", correlating an ERP-observed shortage against MES's floor-side in-progress WIP. Nothing in this codebase has MES querying ERP for that convention.

material_held_for_orders is about ERP as the answering side. ERP's PeerListener answers it as a WIP-style query over local data.

  • ERP's local data, held_for_order from its own polled Material records, is a genuinely different view: material currently committed to an in-progress order, from ERP's reservation-tracking perspective. It is not MES's floor-state WIP.
  • It is "WIP-style" in that sense but not the same fact as in_progress_wip_for_material. Reusing that convention name for a structurally different answer would silently conflate the two. MATERIAL_HELD_QUERY documents this as its own convention instead.
  • ERP only answers it. Nothing in this codebase queries it, so a peer that wants it asks for it by name.

The queries ERP itself asks of MES are described in cross-node-query-and-narrative-wiring.md.

Two Configuration Schema fields

Both are optional on config.rest, with sensible defaults. A Node instance's config only needs to override what it wants different:

"config": {
  "rest": {
    "...": "...",
    "poll_interval_seconds": 5.0,
    "standard_cost_path": "/costing/standard-rate"
  }
}
  • poll_interval_seconds defaults to 5.0 (DEFAULT_POLL_INTERVAL_SECONDS in engine/erp_config.py). This coincides with the default of the same-named field in engine/deviation_flagging_config.py, but it is not a shared constant. Each module keeps its own default, following the codebase's convention of not cross-importing for a coincidental value match.
  • standard_cost_path defaults to /costing/standard-rate (DEFAULT_STANDARD_COST_PATH), the route a typical ERP simulator or test config serves, so such a config needs no override.

Drift-check test. test_erp_node_type_fragment_matches_python_constant in tests/test_erp_config.py guards the copy of REST_CONFIG_SCHEMA embedded in node-types/erp/node_type.json against drifting from the Python constant. Both fields are kept identical in both representations.

node-types/erp/example_node_config.json

There are two example files:

  • node-types/erp/example_config.json is a bare config.rest and config.communication_interface fragment, consumed directly by config-parsing-level tests. It is never wrapped in the node_type, node_type_version, config_version and config envelope that load_node_config (engine/config_loader.py) requires.
  • example_node_config.json is the properly enveloped counterpart. erp_main.py's --config CLI default points at it, and it mirrors the shape of node-types/mes/example_node_config.json.

Both use the same illustrative 10.0.0.11, 8420 and peer-at-10.0.0.10 addresses, because the two Node Types' example configs pair with each other.

Testing without a live simulator

tests/test_erp_main.py drives the real production wiring throughout: build_erp_runtime, run_trigger_dispatch_loop, and a real loopback PeerListener and PeerClient pair.

It replaces only the one genuinely external boundary, RestPollingConnector's HTTP transport. That is patched at its poll() seam (the same private seam the weld-strength deviation-connector tests in test_node_main.py use), rather than requiring a live target system.

The communication_interface fragment's 10.0.0.11 and 8420 values aren't bindable in a test sandbox. Tests therefore override them to 127.0.0.1 and port 0 before building the runtime (see _loopback_config).

Concurrency and error handling

  • ErpIngestionProducer publishes one LastPoll snapshot. The record and its material_id are bundled into one frozen LastPoll (engine/node_runtime.py) and published with a single attribute assignment, which is atomic under the GIL. The ScheduledTask's poll thread writes it after a real ingest() call, and a PeerListener request thread reads it. Two independently mutated attributes would let a query pair a fresh record with a stale material_id. _answer_material_held (engine/erp_main.py) reads producer.last_poll exactly once.
  • Polling failures are logged, not fatal. RestPollingConnector.poll() documents httpx.HTTPError plus KeyError, TypeError and ValueError for a malformed response. ErpIngestionProducer.poll_once and _answer_standard_cost both route through the shared poll_or_log helper (engine/node_runtime.py), which catches that full set. A malformed response therefore neither kills the ScheduledTask's thread nor turns into a bare 500 for the querying peer.
  • One connector, one cached bearer token. RestPollingConnector.poll accepts a path= override (engine/connector.py), so _answer_standard_cost reuses the connector the regular ingestion poll cadence already authenticates with. It does not build a second, independently authenticating one (see the query list above).
  • Shared helpers. engine.node_type.load_node_type_definition is shared by both entrypoints. poll_or_log is the one poll-and-log-on-failure idiom (OpcuaScalarDeviationPoller, ErpIngestionProducer, _answer_standard_cost). _answer_standard_cost checks numeric values with a local _is_numeric helper (isinstance(x, int | float) and not isinstance(x, bool)).

Running it

python -m engine.erp_main --node-instance-id ID starts one ERP Node instance and runs its dispatch loop until stopped.

FlagMeaning
--node-instance-id The instance's id.
--node-type-dir Default node-types/erp.
--config Default node-types/erp/example_node_config.json.
--shared-config-dir The directory the config's $shared fragment references resolve against.

Two environment variables are read:

  • RUNTIME_STATE_PATH: where the runtime state file is written. Unset means none is.
  • PENDING_SUMMARY_HEARTBEAT_SECONDS: the interval of the pending-items summary. An unusable value stops start-up with a usage error.

When the config also declares an inference fragment (which requires communication_interface), the runtime builds an inference client, a peer client and two on-demand querying Tasks that ask MES: OrderStatusQueryTask and InventoryShortageExplainerTask. Neither is scheduled, and a caller invokes .query() or .explain() directly. See cross-node-query-and-narrative-wiring.md.

Pitfalls

  • material_observed only records the observation. Nothing in this codebase drafts anything from a bare Material observation (unlike MES's order_release triggering First Article Inspection). The handler registered for it, observed_only_handler (shared with Production Scheduling's schedule_observed), marks the row done and leaves one Activity Log entry, task type trigger-dispatch: observation recorded. It does not dead-letter through the unroutable-trigger_type path, which would log a failure for something that is not one. Replace the handler for the trigger type if a Task needs to react to a Material observation directly.
  • ErpIngestionProducer tracks exactly one last_poll snapshot at a time. A material_held_for_orders query for any material other than the one this instance most recently polled answers empty ({"held_for_order": {}, "on_hand": None}), not an error. This matches the Node reading a single record per poll (one poll_path GET per cadence tick), not a general per-material cache.
  • The standard_cost answer's live poll has no retry or Try/Catch of its own. A transient failure mid-query (any of poll_or_log's documented exception set) answers with no standard_cost field at all, logged as a warning. build_variance_data_point in engine/costing_variance.py already treats that as CostingVarianceError. It is the same fail-closed-on-unusable-data path a genuinely absent field takes, not a crash of this cross-node dialogue answer callable.
  • A caller needing both record and material_id together must read producer.last_poll once, not last_record and last_material_id separately. The latter two convenience properties each read last_poll internally and are individually safe, but reading them as two separate calls reopens the torn-read window the LastPoll snapshot exists to close.

Release: v0.11.0