Communication Interface
This guide covers how engine/communication_interface.py implements the Communication Interface: the node-to-node protocol half of the Node Type Agreement.
Every Node Type declares relevant_peer_node_types on its Identity & Metadata facet. MES's node_type.json names ["ERP"]. The declaration names the peers a Node Type queries, and this module consumes it.
Three built-in use cases are cross-node and depend on this module: the order status query, the Costing Milestone variance explainer and the inventory shortage explainer. The use-case Tasks themselves are described in ai-narrative-drafting-task-wiring.md.
Contents
- Discovery: the peers Configuration Schema fragment
- Querying side:
PeerClient - Answering side:
run_cross_node_dialogueandPeerListener, including Activity Log entries and identity records - Private-network-only listener bind
- Mutual TLS between peers
1. Discovery: the peers Configuration Schema fragment
"communication_interface": {
"listen_host": "10.0.0.10",
"listen_port": 8420,
"peers": [
{ "node_type": "ERP", "host": "10.0.0.11", "port": 8420 }
]
}
Discovery is a config-declared registry. It is not broadcast or mDNS auto-discovery, which would add an unauthenticated LAN broadcast surface that the design does not need at typical single-hypervisor site scale.
COMMUNICATION_INTERFACE_CONFIG_SCHEMAis the fragment a Node Type embeds under its ownconfig_schema's"communication_interface"property. It is validated like any other Configuration Schema fragment.node-types/mes/node_type.jsonandnode-types/erp/node_type.jsonboth carry it.build_communication_interface_profileturns an already schema-validated object into aCommunicationInterfaceProfile.
from engine.communication_interface import PeerDeclaration, PeerRegistry
registry = PeerRegistry([PeerDeclaration(node_type="ERP", host="10.0.0.11", port=8420)])
# constructor rescans immediately - registry.reachable_peer("ERP") reflects real reachability
# before this registry's first query, not an assumed-reachable default.
Rescanning
PeerRegistry.rescan() has the shape of ScheduledTask.run (engine/node_runtime.py). A caller wires periodic re-scanning through the Node Runtime's own scheduled-check mechanism, not a second, separately invented timer:
from engine.node_runtime import ScheduledTask
rescan_task = ScheduledTask(name="peer-rescan", interval_seconds=30.0, run=registry.rescan)
run_trigger_dispatch_loop(queue, activity_log, handlers, ..., scheduled_tasks=[rescan_task])
A config can declare more than one candidate peer instance per Relevant Peer Node Type. reachable_peer(node_type) returns the first one the last rescan() found reachable. Among unreachable ones, config order is not guaranteed.
2. Querying side: PeerClient
from engine.communication_interface import PeerClient
from engine.envelope import CrossTypeEnvelope
client = PeerClient(registry, activity_log, node_type="MES", node_instance_id="mes-line-3")
response = client.query(
"ERP",
CrossTypeEnvelope(
identity_keys={"order_id": "MO-1001"}, activity_log_reference="mes-line-3:evt-42"
),
trigger="order_status_query",
) # -> CrossTypeEnvelope
What a query does
- Finds a peer. It looks up a currently reachable peer through
PeerRegistry.reachable_peer. - Sends the envelope. It POSTs the envelope to
/cross-node-queryover plainhttpx. It does not usebuild_guarded_clientfromengine/network_posture.py: peer traffic is same-LAN, so it is not "outbound" under that module's posture definition, and that guard's allowlist is reserved for the License Server's one static, known target. - Negotiates the response. The response is negotiated down to this client's own
consumer_versionthroughnegotiate()inengine/envelope.py. No new schema is invented here.
The call is wrapped as a one-step Prompt Chaining Task purely to route through Task Execution logging (see wiring-task-execution-to-activity-log.md). ErpReporting.report in engine/erp_reporting.py is the closest existing precedent for this shape.
It is retried under Try/Catch like any other call to an external target. Exhausting the retry budget raises UnresponsiveServiceFailure rather than returning a partial result.
Fails closed
NoReachablePeerError is raised when no declared peer for the requested Relevant Peer Node Type is reachable. It is raised before any request is attempted and before anything is logged. The client never falls back to a stale local copy or fabricates an answer. LicenseManager and the retrieval quality gate take the same fail-closed stance.
Looks again once before giving up
The registry's answer can be merely out of date. A peer that started, or came back, since the last scheduled rescan is still marked down until the next one. So when reachable_peer finds none, the query calls PeerRegistry.rescan_if_due and looks once more.
- A scan that finished within
rescan_floor_secondsmakes another scan unnecessary. The default isPEER_RESCAN_FLOOR_SECONDS, 5 s, and scheduled and on-demand scans both count. A peer that stays down therefore costs one scan per interval, not one per failed query. - Scans never overlap, so callers arriving together share one.
- A Node type with no declared peer at all gets no look-again, since a scan cannot help.
- The cost: a failure with the peer genuinely down can take up to one health-check timeout (5 s by default) longer to surface, once per interval.
- The retries inside a query do not look again. They retry the one peer chosen at the start.
3. Answering side: run_cross_node_dialogue and PeerListener
from engine.communication_interface import PeerListener
def answer(incoming: CrossTypeEnvelope) -> CrossTypeEnvelope:
# local-data lookup only - the actual order-status/Costing-Milestone-variance/shortage
# logic is the use-case Tasks' own job (ai-narrative-drafting-task-wiring.md)
return CrossTypeEnvelope(status="completed", activity_log_reference="erp-node-1:evt-99")
with PeerListener(
"10.0.0.11", 8420, activity_log, answer, node_type="ERP", node_instance_id="erp-node-1"
):
... # serves in a background daemon thread until closed
An incoming POST /cross-node-query goes through these steps:
- It is validated as a
CrossTypeEnvelope. - It is negotiated down to the listener's own
consumer_version. - It is run through
run_cross_node_dialogueoveranswer. This is the cross-node dialogue Task type, one of the engine's Task types. - Exactly one
ActivityLogEntryis logged (task_type="cross-node-dialogue",trigger="peer_query"), through the same Task Execution logging every other Task run uses. - Once the answer is logged, one INFO line is written:
cross-node query: <node type> answered (<query>).<query>is the envelope'sevent_fields["query"], orno query namedif absent. The answering Node's own console thus shows the query arrived. The querying side already printscross-node query: MES -> ERP (<trigger>). The envelope carries no sender, so the answering line can't name the asker. A failed answer logs no such line.
GET /health answers a peer's PeerRegistry.rescan().
The guarantee is structural, not just a convention. Both directions on the wire are CrossTypeEnvelope-validated JSON. A malformed or non-envelope-shaped body never reaches answer at all: it gets a 400 first. This is the Inter-Node Reasoning Boundary, enforced by this module's own type signatures. A raw prompt or a peer's freeform AI or reasoning output can never cross.
Asking a Node for its own Activity Log entries
The MES, ERP and Production Scheduling Nodes all answer event_fields["query"] = "activity_log_entries" from their own ActivityLog only. The answer never reaches another peer, so a Node on a real appliance, with its own Postgres, reports exactly what it logged itself.
Request
Request event_fields | Meaning |
|---|---|
reference_id |
Optional. Entries naming this value anywhere in their reference_ids. |
reference_ids_key |
Optional. Narrows reference_id to that one key. Needs reference_id. |
task_type |
Optional. Entries of exactly this task_type. May be given with or without reference_id. |
start, end |
Optional ISO 8601 times with a UTC offset. The window is half-open, [start, end). |
after |
Optional. The next_cursor of the previous answer. |
limit |
Optional whole number of at least 1. Capped at 200, and a larger request is given 200. |
When given, reference_id, reference_ids_key and task_type are non-empty strings without a NUL character. The asking side raises ValueError for any other value, and a Node answers one with a 400.
Answer
The answer's event_fields hold:
entries, inActivityLog.query_pageorder;next_cursor, which isnullon the last page. A peer repeats the same filters with eachafter.
Each entry carries id, node_type, node_instance_id, occurred_at, trigger, task_type, workflow_pattern, outcome, peer_nodes_queried and reference_ids. The chain hashes stay on the Node whose chain they belong to.
A request with an unknown field, a bad value or a cursor the Node did not issue is a 400 with a fixed reason and no entries.
The answering Node logs the fetch as an ordinary cross-node-dialogue entry that names only an activity_log_reference, so asking about a reference_id does not add to the trail it asks about.
The querying side: fetch_activity_log_entries
client.fetch_activity_log_entries(
trigger=...,
reference_id=...,
reference_ids_key=...,
task_type=...,
start=...,
end=...,
page_size=...,
max_pages_per_peer=...,
deadline_seconds=...,
retry=...,
)
It returns this Node's own matching entries together with each declared peer's, following a peer page by page to the last. It never raises for one peer's failure.
-
Per-peer result. Each peer gets a
PeerFetchResult(outcome, adetailthis side composed,pages,entries).completeis false unless every peer answered every page. -
Outcomes. The
outcomeis aPeerFetchOutcome:Outcome Meaning answeredThe peer answered every page. unreachableDown at the last rescan, or the connection failed. timed_outThe peer did not answer in time. refusedAn HTTP error status, or a peer that does not know the query. malformedA body, entry or cursor this side cannot use. truncatedThe page or time limit stopped it before the last page. -
Limits.
DEFAULT_MAX_PAGES_PER_PEER = 50pages.DEFAULT_FETCH_DEADLINE_SECONDS = 30for the whole fetch, with retries.MAX_PEER_RESPONSE_BYTESof 8 MiB read from one answer. -
Retries. A transient failure (no connection, a timeout, a 5xx, 408 or 429) is retried per
retry. Any other error status is a refusal. -
Duplicates. An entry id seen twice is kept once: this Node's first, then peers in declaration order.
-
Logging. Every peer asked leaves exactly one entry on this side. A peer found down is not asked and logs nothing.
-
Nothing fetched is stored.
Asking a Node for its own identity record
The same three Nodes answer event_fields["query"] = "identity_record" from their own IdentityStore only.
Request. The request's event_fields name an entity_type (order, material, qualification or schedule) and a reference_id, a non-empty string without a NUL character, and nothing else. A record with no reference_id therefore can never be fetched. Any other field, an unknown entity_type or a bad reference_id is a 400 with a fixed reason that repeats nothing from the request.
Answer. The answer's event_fields always hold record: the Node's record for that pair, or null when it holds none. "None" is an answer. A Node that does not know the query (an older one) answers with empty event_fields, which the asking side reads as a refusal, not as "none". A Node with no identity store behaves the same way.
What crosses. A record crosses as entity_type, reference_id, attributes and status.
- The store's row id, the match candidate and score, the timestamps, and who settled or re-opened the record stay on the Node they belong to.
attributescrosses whole, for the one record named by exact key and no other. It is free-form, so a Node Type should not keep in it what its peers must not see.- A record that is pending, rejected or merged is sent with that status, so the asking side can refuse it.
from engine.identity_resolution import EntityType
fetch = client.fetch_identity_records(
EntityType.ORDER, "MO-1001", trigger="order_trail", local_store=store
)
fetch.complete # False if any declared peer did not answer
[p.name for p in fetch.not_answered] # who, by Node Type and address
fetch.peers[0].record # a PeerIdentityRecord, or None
fetch.peers[0].has_no_record # answered, and holds none
fetch.unresolved # peers whose record is pending, rejected or merged
fetch.disagreements # pairs of Nodes whose records differ, naming both
How the fetch behaves
- It asks every declared peer at the same time and never raises for one peer's failure. A peer found down at the last rescan is named and not asked.
- Requests, retries, the cap on a response's size and the one logged entry per peer asked are those of
fetch_activity_log_entries, with the samePeerFetchOutcomevocabulary. - A peer's record is a
PeerIdentityRecord, not anIdentityRecord. It carries no row id and cannot be saved to a store, so nothing fetched is written anywhere. - This Node's own record is read from
local_storeand returned beside the peers', never in place of them.
Disagreements
Records for one (entity_type, reference_id) that differ are listed in disagreements. None is merged into another, because each Node that ingests an order resolves its own record.
- A disagreement names both Nodes (each by name and address, and by Node Type alone) and the keys that differ, but no value.
- Records are compared on the record
statusand on each attribute key both carry. A key only one record has is not a difference, since each Node resolves the fields its own source reports. - A record that is not resolved differs in status from one that is. It is listed in both
disagreementsandunresolved: the first says what differs, the second what a caller must refuse.
4. Private-network-only listener bind
PeerListener is the only inbound-accepting listener. Its host is validated at construction, before any socket is bound.
- It must be a literal private or loopback IP address (
ipaddress.ip_address(host).is_private), excluding0.0.0.0and the unspecified address. - It must never be a public address, and never a hostname. A hostname's eventual DNS resolution can't be verified against this posture at config time.
- A misconfigured
listen_hostfails closed withConfigValidationErrorrather than silently binding an internet-reachable interface.
This is the fifth canonical fault case in the Conformance Suite's fault-injection list (see cross-node-type-validation-fault-injection.md). It is not injectable through run_fault_tolerant_ingestion's fetch/ingest shape, because the fault isn't about a Node Type's System Connector or Data Transformation Layer at all. tests/test_communication_interface.py's construction-time tests cover it directly instead.
5. Mutual TLS between peers
Peer traffic runs over mutual TLS on the site trust model (site-pki.md):
- each side presents its Node certificate;
- each side trusts only the site CA's bundle;
- the querying side checks who answered.
In production mode (PRODUCTION_MODE=True, which provision_node.sh sets), a Node refuses to start its Communication Interface without it. Outside production, a config with no tls section keeps plain HTTP, so development and the test suite are unchanged.
"communication_interface": {
"listen_host": "10.0.0.10",
"listen_port": 8420,
"tls": {
"certificate_path": "/home/kindred/.kindred-node-pki/node.crt",
"private_key_path": "/home/kindred/.kindred-node-pki/node.key",
"trust_bundle_path": "/home/kindred/.kindred-node-pki/trust-bundle.pem"
},
"peers": [
{ "node_type": "ERP", "host": "10.0.0.11", "port": 8420, "identity": "urn:kindred:plant1:erp" }
]
}
- The shipped
example_node_config.jsonfiles are plain HTTP, for development. A production Node's config adds thetlssection and each peer'sidentityas above, or it is refused. tlsholds paths only. The three files are whatinstall_node_certificate.shleaves in the Node's PKI directory. Key material never goes in the config, which lives in a repo.- Each peer names the identity it must present (
identity, theurn:kindred:<site>:<node>in its certificate).- Peers are addressed by IP, so the identity is what is checked, inside the handshake. A host presenting a valid site certificate for a different Node is treated as unreachable and never receives a query.
- The listener answers any certificate from its own site and records who asked in the Activity Log entry (
reference_ids.asker_identity). - Which Node Type may be asked what is still the
peersdeclaration, not the PKI.
- Production refuses to start, before anything binds, in these cases:
- No
tlssection,lab_mode, or a peer with noidentityraiseConfigValidationError. - A certificate that is expired, for another key, from another CA, or without a Kindred identity raises its specific
PkiError. lab_mode(a pinned self-signed certificate) is for development and is refused in production.
- No
- Limits on the listener.
- At most 64 connections are open at once, and at most 16 from any one client address. More are dropped at once, so one host holding silent connections cannot lock the peers out. A host with several addresses has several allowances.
- A handshake must finish within 5 seconds and a request within 30 seconds in total. A peer sending one byte at a time is cut off, not waited for.
- A request body over 1 MiB is a
413. - A certificate from the Node's own site is all that is needed to be answered. A compromised Node of the same site can therefore still query its peers, at a rate nothing here limits. Revoke it by replacing the CA bundle (see below).
- The MES, ERP and Production Scheduling entrypoints load this fragment. The PLC / Generic Device Node Type's schema has no
communication_interface, so it runs no listener and has no certificate to reload. GET /healthalso needs a certificate. A refused connection (no certificate, another CA, another site, plain HTTP) is logged to standard logging only, never the Activity Log.
Renewing a certificate on a running Node
A Node loads its certificate, key and trust bundle at start and again on SIGHUP.
- A reload validates all three first and keeps the current ones if anything is wrong, logging why. It never leaves a Node without a certificate.
- The next connection uses the new files. A request already in flight finishes on the old ones.
reload()refuses a certificate that names a different identity from the Node's own.- After a CA replacement, the old CA stops being trusted as soon as the Node reloads the bundle that no longer holds it. No restart is needed.
- Once an hour the Node logs a warning when its certificate, or a CA in its bundle, enters the 30-day warning window, and an error when one lapses.
How the reload is triggered
- The pid file. The Node writes its process id to
node.pidand installs the signal handler when it starts. The file is in$KINDRED_NODE_PKI_DIRif the Node's environment sets it (the directory the install script and the hook use), otherwise beside the certificate files. Keep the two the same. One Node runs per appliance, so one pid file serves one PKI directory. - The hook.
deployment/link_node_reload_hook.shlinksreload_node_tls.shinto the Node'sreload.d, so everyinstall_node_certificate.shrun signals the Node.provision_node.shruns it for the default~/.kindred-node-pki. Run it yourself withKINDRED_NODE_PKI_DIRset for another directory. - Which processes the hook signals. Only a process whose command line matches one of the entry points that reload:
engine.node_main,engine.erp_mainorengine.production_scheduling_main(or the same with/).KINDRED_NODE_PROCESS_MATCHcan give another extended regex.- The PLC / Generic Device entry point is not signalled, because it has no certificate. The hook says there is nothing to reload and succeeds.
- If the pid file names something else, the hook fails, and the install says a reload is owed (see
site-pki.md).
- Keep the paths together. The Node reads the three files its
tlssection names, while the install script, the hook, the pid file and the management API find them throughKINDRED_NODE_PKI_DIR(default~/.kindred-node-pki). Keep thetlspaths in that directory. At start the Node logs a warning if they are not, since a renewal installed there would never reach it.
No extra deployment step
engine/communication_interface.py is built on Python's stdlib http.server and ssl and the httpx dependency. It needs no extra native package and no deployment/install_*.sh script.
The poetry install step of deployment/provision_node.sh is the only provisioning this component needs. It builds from a bare OS like every other component, and tests/test_communication_interface.py runs against nothing but the repo's own test environment.
Pitfalls
reachable_peerreflects the lastrescan(), not real-time reachability. A peer that goes down between rescans still looks reachable until the next scheduled check runs. This is the same staleness windowLicenseManager's grace-period design accepts. It is bounded by whateverinterval_secondsa caller'sScheduledTaskuses, not by this module.PeerListener.close()beforestart()is safe, butclose()twice is not tested. This module assumes the same single-owner lifecycle every other closeable collaborator here does (RestPollingConnector,OpcuaConnector).- A genuine bug in
answergets a500response and a logged error entry, not a crashed listener.PeerListener's request handler catches any exceptionrun_cross_node_dialoguepropagates. The exception is already logged, throughlog_task_execution's terminal-entry-then-re-raise behavior. One bad incoming query therefore can't take down the wholeThreadingHTTPServer. - Without a
tlssection,/cross-node-queryand/healthhave no authentication. That configuration is for development only, since production refuses it (section 5). It matches this module's "not outbound" classification for same-LAN peer traffic. Even with mutual TLS, a genuinely hostile actor already holding a certificate from the site's own CA is out of scope for this design, which follows the posture theengine/network_posture.pymodule docstring draws around what "outbound" protects against.
Release: v0.11.0