Data Transformation Layer: petl vs. rule-based, and the generic fallback
This guide covers how TransformationRegistry, build_petl_transform and build_rule_based_transform in engine/transformation.py implement the Data Transformation Layer.
The layer sits one step downstream of a System Connector and turns one already-received raw record into one of Kindred's own canonical event dicts. Its neighbors are:
- Upstream: the System Connector gets the raw record across the wire (see
mes-node-type-opc-ua.mdanderp-node-type.md). - Downstream: the caller assembles the result into a Cross-Type Envelope.
Both builders produce the identical TransformFunc shape, Callable[[dict], dict]. TransformationRegistry, and any Task calling .transform(), never needs to know which one is behind a given source_type.
1. A realistic case: inferring events from a legacy PLC tag stream
Most of an integrator's actual time on this layer goes here, not into a one-line field rename.
- The easy case is a modern REST API or an OPC-UA feed that already carries real order or job identifiers.
build_petl_transformhandles it (contrasted below). - The hard case is common. Whether a source exposes those identifiers varies by site, and a raw PLC/SCADA layer with no concept of an order at all is a routine starting point, not a rare exception. It is the whole reason the inferred, rule-based path exists.
The running example is a bond-fixture weld cell. The PLC doesn't know what an "order" is. It exposes a status word and a force reading, nothing else.
Where the record actually comes from
The PLC's OPC-UA server doesn't hand over a bundled record. It exposes each value as its own node with its own NodeId: ns=2;s=Cell3.StatusWord, ns=2;s=Cell3.CycleCount, ns=2;s=Cell3.ForceN and ns=2;s=Cell3.PartPresent.
- Configuration. An integrator's Configuration Schema names one as the record's primary
node_idand the rest asextra_fields(the{node_id, source_key}shape inengine/opcua_config.py). Kindred'sOpcuaConnectorthen subscribes to each independently. - Events. Each OPC-UA data-change event delivers exactly one field's new value.
- Buffering.
MesIngestionProducer._on_event(engine/node_runtime.py) writes the value into a per-record buffer. It re-ingests the whole accumulated buffer every time any one of the record's fields changes, not just the field that changed. - When ingestion happens. Only once the record's own identity field has been observed with a real value. A record's primary
node_idalways reports under the source keyvalue, not under the node's name. Earlier events for other fields just update the buffer and wait, so the eventual ingestion always carries a genuine reference id.
That accumulated buffer, not anything the PLC sent as one message, is the record: dict that actually reaches the Data Transformation Layer:
{"StatusWord": 4, "CycleCount": 1182, "ForceN": 7.9, "PartPresent": True}
Why a flat rename can't express it
StatusWord is a legacy enum the PLC vendor defined once, years before Kindred existed: 1 running, 4 cycle complete, 8 fault.
Only a 4 frame's ForceN is a real weld-strength measurement. A 1 frame is mid-cycle noise, and treating every poll's ForceN as a genuine reading would flag the machine spinning up as a deviation. The meaning of one field depends on another field's value, and that is the shape a flat rename can't express.
The rule set
from engine.transformation import build_rule_based_transform, MappingRule
weld_cell_transform = build_rule_based_transform(
[
MappingRule(
when={"StatusWord": 4},
then={"weld_strength_n": "ForceN", "cycle_count": "CycleCount"},
literals={"event_type": "weld_cycle_complete"},
),
MappingRule(
when={"StatusWord": 8},
then={},
literals={"event_type": "cell_fault"},
),
MappingRule(
when={}, then={}, literals={"event_type": "heartbeat"}
), # catch-all, deliberate
]
)
Three real records through it:
weld_cell_transform({"StatusWord": 4, "CycleCount": 1182, "ForceN": 7.9, "PartPresent": True})
# -> {"weld_strength_n": 7.9, "cycle_count": 1182, "event_type": "weld_cycle_complete"}
weld_cell_transform({"StatusWord": 8, "CycleCount": 1183, "ForceN": 0.0})
# -> {"event_type": "cell_fault"} -- 0.0 isn't a real reading, and this rule never touches ForceN
weld_cell_transform({"StatusWord": 1, "CycleCount": 1183})
# -> {"event_type": "heartbeat"} -- mid-cycle poll, correctly not mistaken for a measurement
The catch-all rule is doing real work, not boilerplate. The catch-all is when={}, last in the list. Without it, a StatusWord: 1 frame would fall through build_rule_based_transform's no-match passthrough (section 5, below). It would land in the canonical event stream as raw, unlabeled PLC noise, {"StatusWord": 1, "CycleCount": 1183}, instead of a clearly tagged heartbeat a downstream Task can cheaply ignore.
What that third rule should be (heartbeat, ignore entirely, something else) is a genuine per-site judgment call. It is exactly what an integrator works out for the site: which raw signals are noise, which are real, and what "real" means for this specific cell.
What the buffering means for a when clause
Two real integration issues to know before writing one:
- A record can be incomplete on its first event. The per-record buffer starts empty, and a field only appears in it once its own OPC-UA node has fired at least one data-change event. If
StatusWordis the first of the four tags to update, awhen={"StatusWord": 4}rule can match whileForceNis still absent from the buffer. Mechanically this is already covered: a missingthensource reads asNone, not a crash (see Pitfalls). But the cause is worth recognizing. It is a cold-start gap, not bad data. - A match doesn't guarantee the other fields are current. A re-ingest fires whenever any one subscribed field changes, carrying whatever is currently buffered for the rest.
StatusWordflipping to4doesn't guaranteeForceN's buffered value was read at that same instant. It is only the most recent value Kindred has seen for that tag as of this event. If the PLC doesn't update all four tags in lockstep, a rule can fire against aForceNreading that is a poll or two stale relative to theStatusWordtransition that triggered it.
Contrast: the easy case
A REST-based ERP's API already returns clean, self-describing JSON. This is what build_petl_transform is for:
from engine.transformation import build_petl_transform
inventory_transform = build_petl_transform(
{
"material_id": "MaterialId",
"on_hand_qty": "OnHandQty",
"required_qty": "RequiredQty",
}
)
inventory_transform({"MaterialId": "MAT-001", "OnHandQty": 120, "RequiredQty": 200})
# -> {"material_id": "MAT-001", "on_hand_qty": 120, "required_qty": 200}
There is no branching and no inference, because the source already agrees with Kindred on what each field means.
Recognizing which of the two cases a given feed is, five minutes with build_petl_transform or sitting down with the PLC vendor's tag documentation to build a real rule set, is the actual skill this layer asks of an integrator.
2. Register a transform per source type
from engine.transformation import TransformationRegistry
registry = TransformationRegistry() # seeds GENERIC_TRANSFORM: a plain pass-through copy
registry.register("weld_cell_reading", weld_cell_transform) # either builder above fits here
canonical = registry.transform("weld_cell_reading", raw_record)
transform() never raises for an unregistered source_type. It silently falls back to GENERIC_TRANSFORM. This handles the Conformance Suite's "no matching transformation rule" fault by design, rather than leaving it to crash a Task mid-run.
registered_source_types lists everything currently registered, GENERIC_TRANSFORM included. That is useful for a dry-run or audit check of what a site's config actually covers.
3. build_petl_transform, in more depth
It is built on petl.fieldmap, wrapped so each mapping is a plain record.get(source_field) lookup rather than a bare string. Without the wrapper, petl.fieldmap treats a string mapping that isn't an exact column match as a Python expression to eval. That crashes on an ordinary field name containing a space, and would silently misinterpret one that happens to parse as an expression.
- A source field genuinely absent from a given record maps to
None, never aKeyError. - Internally, the record is wrapped as a one-row petl table and unwrapped back to a single dict.
transform()is always called one record at a time, never in bulk. - See the inventory example above for a worked case.
4. build_rule_based_transform, in more depth
Rules are tried in order, and the first whose when fully matches wins.
thenis read off the matched record the same waybuild_petl_transform'sfield_mapis.literalslayers fixed values on top afterward, such as anevent_typetag the source itself never sends, as in the weld-cell example.- A record matching no rule passes through unchanged. See the two "nothing matched" cases below before assuming that is the same thing as the registry-level fallback.
when matching is exact-and-present, not loose. A rule matches only if record.get(key, _MISSING) == value holds for every entry in when.
- A key genuinely absent from the record never satisfies a rule, including one that expects
None.when={"ErrorCode": None}only matches a record that explicitly carriesErrorCode: null, never one that omits the field entirely. - An empty
when({}) always matches. That is the mechanism behind the weld-cell example's catch-all rule.
A rule an earlier rule always takes is never used. Order decides, so a rule whose when holds every entry of an earlier rule's when, and more, can never be the first match:
from engine.transformation import MappingRule
rules = [
MappingRule(
when={"StatusWord": 4},
then={"cycle_count": "CycleCount"},
literals={"event_type": "weld_cycle_complete"},
),
MappingRule(
when={"StatusWord": 4, "PartPresent": True}, # rule 0 takes every record this matches
then={"weld_strength_n": "ForceN"},
literals={"event_type": "weld_measured"},
),
]
A record with StatusWord: 4 and PartPresent: True is taken by rule 0, so rule 1 never runs. The mapping preview reports it as rule 1 is never reached: rule 0 matches every record it would and exits 1; the fix is to put the narrower rule first. An earlier rule with an empty when makes every rule after it dead in the same way. See mapping-preview.md.
5. Two different "nothing matched" cases — don't conflate them
| Case | What happens | Why |
|---|---|---|
TransformationRegistry.transform() called with an unregistered source_type |
Routes to the transform registered under GENERIC_TRANSFORM (the reserved source-type name "generic"; the function is generic_transform), a plain pass-through copy of the raw record. |
This is the Conformance Suite's fault-injection case: no matching transformation rule at all for this source type. |
build_rule_based_transform's rules list, with none of its when clauses matching a record |
Also passes the record through unchanged. | The engine ran. It just had nothing to do with this particular record. The weld-cell example's catch-all rule exists to prevent exactly this. Add a trailing when={} rule if a rule-based transform should never fall through silently for a source type it is registered for. The mapping preview prints a note for a rule set with none, and leaves its exit code alone. |
Choosing between them
build_petl_transformsuits a source whose records are uniform, such as the ERP inventory case above.build_rule_based_transformsuits a source that multiplexes several record kinds through one feed, where the mapping needs to branch on content, not just rename columns. The weld-cell case above is one.
Both are ordinary Python. Nothing stops a Node Type from registering a hand-written TransformFunc instead of either builder when a mapping needs logic neither shape covers. TransformationRegistry only requires the Callable[[dict], dict] shape, not that it come from one of these two builders.
Pitfalls
- Validate a mapping offline before pointing it at a live system. The preview harness (
engine/mapping_preview.pyandengine/preview_candidate.py) replays sample records through a configured mapping.engine/gap_report.pyreports what is missing, driven bypython -m engine.mapping_preview_cli. Seemapping-preview.md. Calling theTransformFuncdirectly against a captured sample record in a REPL or a test also still works. build_petl_transform's petl machinery is overhead with no behavioral upside for a plain rename. It earns its keep only once a mapping genuinely needs petl's row-processing features. For a one-to-one field rename it produces the same result a bare dict comprehension would.register()silently replaces any existing registration for thatsource_type, includingGENERIC_TRANSFORMitself. Registering it again is the supported way for a Node Type to swap its own default fallback, not an error.MappingRule.thenvalues missing from the matched record becomeNonein the canonical event, not a validation error at this layer.record.get(source_field)is a lookup, not a required-field check. A missing required canonical field should be caught downstream, by Cross-Type Envelope or Event schema validation. For an OPC-UA-sourced record specifically, the buffering note in section 1 is the real-world cause to check first: a cold-start gap or a stale-but-present field, not necessarily a badfield_mapor rule.- A rule set with no catch-all can silently under-report. The weld-cell example's third rule isn't decoration. Leaving it out means every non-cycle-complete, non-fault poll passes the raw PLC frame through unchanged instead of a labeled
heartbeat. That is exactly the kind of unlabeled-noise gap the Conformance Suite's fault list exists to catch at the registry level, not at the rule level.
Release: v0.11.0