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 (apoll_once()method), rather thanMesIngestionProducer'srun()-started subscription. - Cadence. A Node instance's configured
poll_interval_seconds(engine/erp_config.py) drives it through the sameScheduledTaskmechanismOpcuaScalarDeviationPolleruses. - Deduplication. It skips an unchanged poll result, for the reason
OpcuaScalarDeviationPoller's_same_valueguard 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 theRestPollingConnectorthat the regular ingestion poll cadence already authenticates with. That connector is called again through itspoll(path=...)override (engine/connector.py), pointed at the path frombuild_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 readsErpIngestionProducer.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_reportstripsquery,trigger_typeandreport_idand hands the rest straight toErpReporting.report(), reusing the same connector and its cached bearer token.reportedisTrueonly once delivery to the real ERP system genuinely succeeded (Outcome.SUCCEEDED), not merely because this Node instance was reachable. The module docstring ofengine/erp_reporting_wiring.pydescribes the querying side (_order_release_stepand_costing_variance_point_builderinengine/node_main.py).activity_log_entries: local. This Node's own Activity Log, one page at a time. Seecommunication-interface.md.identity_record: local. This Node's own Identity Store, the one record named. Seecommunication-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_orderfrom 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_QUERYdocuments 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_secondsdefaults to5.0(DEFAULT_POLL_INTERVAL_SECONDSinengine/erp_config.py). This coincides with the default of the same-named field inengine/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_pathdefaults 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.jsonis a bareconfig.restandconfig.communication_interfacefragment, consumed directly by config-parsing-level tests. It is never wrapped in thenode_type,node_type_version,config_versionandconfigenvelope thatload_node_config(engine/config_loader.py) requires.example_node_config.jsonis the properly enveloped counterpart.erp_main.py's--configCLI default points at it, and it mirrors the shape ofnode-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
ErpIngestionProducerpublishes oneLastPollsnapshot. The record and itsmaterial_idare bundled into one frozenLastPoll(engine/node_runtime.py) and published with a single attribute assignment, which is atomic under the GIL. TheScheduledTask's poll thread writes it after a realingest()call, and aPeerListenerrequest thread reads it. Two independently mutated attributes would let a query pair a fresh record with a stalematerial_id._answer_material_held(engine/erp_main.py) readsproducer.last_pollexactly once.- Polling failures are logged, not fatal.
RestPollingConnector.poll()documentshttpx.HTTPErrorplusKeyError,TypeErrorandValueErrorfor a malformed response.ErpIngestionProducer.poll_onceand_answer_standard_costboth route through the sharedpoll_or_loghelper (engine/node_runtime.py), which catches that full set. A malformed response therefore neither kills theScheduledTask's thread nor turns into a bare 500 for the querying peer. - One connector, one cached bearer token.
RestPollingConnector.pollaccepts apath=override (engine/connector.py), so_answer_standard_costreuses 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_definitionis shared by both entrypoints.poll_or_logis the one poll-and-log-on-failure idiom (OpcuaScalarDeviationPoller,ErpIngestionProducer,_answer_standard_cost)._answer_standard_costchecks numeric values with a local_is_numerichelper (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.
| Flag | Meaning |
|---|---|
--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_observedonly records the observation. Nothing in this codebase drafts anything from a bare Material observation (unlike MES'sorder_releasetriggering First Article Inspection). The handler registered for it,observed_only_handler(shared with Production Scheduling'sschedule_observed), marks the row done and leaves one Activity Log entry, task typetrigger-dispatch: observation recorded. It does not dead-letter through the unroutable-trigger_typepath, 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.ErpIngestionProducertracks exactly onelast_pollsnapshot at a time. Amaterial_held_for_ordersquery 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 (onepoll_pathGET per cadence tick), not a general per-material cache.- The
standard_costanswer's live poll has no retry or Try/Catch of its own. A transient failure mid-query (any ofpoll_or_log's documented exception set) answers with nostandard_costfield at all, logged as a warning.build_variance_data_pointinengine/costing_variance.pyalready treats that asCostingVarianceError. 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
recordandmaterial_idtogether must readproducer.last_pollonce, notlast_recordandlast_material_idseparately. The latter two convenience properties each readlast_pollinternally and are individually safe, but reading them as two separate calls reopens the torn-read window theLastPollsnapshot exists to close.
Release: v0.11.0